release: native macOS preview, approved graph identity, and guarded CLI failover
This commit is contained in:
+42
-33
@@ -22,7 +22,7 @@
|
|||||||
"better": "Recognition, parsing, transcription and hashing all run on your machine. A file that has been through once is recognised by its hash and never reaches a paid model again.",
|
"better": "Recognition, parsing, transcription and hashing all run on your machine. A file that has been through once is recognised by its hash and never reaches a paid model again.",
|
||||||
"how": "One run walks the whole path. Every stage leaves evidence, and the run does not close while a single file is still unaccounted for.",
|
"how": "One run walks the whole path. Every stage leaves evidence, and the run does not close while a single file is still unaccounted for.",
|
||||||
"quick_intro": "You need Node.js 20 or newer, Python 3.11 or newer, and git. A Mac is better: image recognition only exists there. On Linux the rest still works.",
|
"quick_intro": "You need Node.js 20 or newer, Python 3.11 or newer, and git. A Mac is better: image recognition only exists there. On Linux the rest still works.",
|
||||||
"quick_extra": "`setup.sh` is the guided path: it checks the prerequisites, asks where the inbox goes, and can deploy the Telegram bot. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` previews it without touching anything, and `bash install.sh` is the non-interactive skeleton if you already know what you want. No Git? Download [the ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) or [the tarball](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) and run the same script inside. First time here? Open the project in Claude Code and run `/mnemazine-setup`: the install goes as a conversation, one question at a time, and nothing is installed without your yes.",
|
"quick_extra": "`setup.sh` is the guided path: it checks the prerequisites, asks where the inbox goes, and can deploy the Telegram bot. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` previews it without touching anything, and `bash install.sh` is the non-interactive skeleton if you already know what you want. No Git? Download [the ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) or [the tarball](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) and run the same script inside. First time here? Open the project in Claude Code and run `/mnemazine-setup`: the install goes as a conversation, one question at a time, and nothing is installed without your yes.\n\nTo try the macOS menu-bar preview after setup, run `npm run app:build`, then `open .mnemazine/tmp/Mnemazine.app`. It runs on macOS 14+; building needs Xcode 26+ with the macOS 26 SDK. The app opens a Spotlight-style search capsule beside separate round controls for links, files, clipboard and settings. Dragging a file turns the row into a drop target; processing starts only after confirmation. Native Liquid Glass is used on macOS 26, with system materials on older versions. The icon is a connected-node graph. See [the app guide (Russian)](docs/macos-app.ru.md).",
|
||||||
"quick_result": "the folders are ready, the engines say plainly what is installed and what is degraded, and `vault/` opens as an Obsidian vault.",
|
"quick_result": "the folders are ready, the engines say plainly what is installed and what is degraded, and `vault/` opens as an Obsidian vault.",
|
||||||
"compare": [
|
"compare": [
|
||||||
[
|
[
|
||||||
@@ -98,7 +98,10 @@
|
|||||||
"Apple Vision recognition is macOS only; on Linux screenshots fall back to the model or stay unread.",
|
"Apple Vision recognition is macOS only; on Linux screenshots fall back to the model or stay unread.",
|
||||||
"Verification finds sources and contradictions, but the final judgement is still yours.",
|
"Verification finds sources and contradictions, but the final judgement is still yours.",
|
||||||
"A very large first run takes time and, in deep mode, tokens.",
|
"A very large first run takes time and, in deep mode, tokens.",
|
||||||
"The vault is plain Markdown: no hosted service keeps a backup for you."
|
"The vault is plain Markdown: no hosted service keeps a backup for you.",
|
||||||
|
"The macOS app is a source preview with an ad-hoc signature, not a notarized download or installer. Its local repository and Node.js paths must remain valid; the bundle does not include a standalone backend.",
|
||||||
|
"The app accepts URLs, including YouTube links, or titles as research requests. A full page or video transcript is not guaranteed.",
|
||||||
|
"CLI discovery includes built-in Claude Code, Codex and Kimi adapters. After a quota or rate-limit error, fallback uses only eligible providers; other CLIs need an adapter. Discovery does not confirm login or quota."
|
||||||
],
|
],
|
||||||
"docs": "Deeper: [the full reference](docs/DETAILS.md) covers site and video intake, the quality contract, the agent roster, exit codes and troubleshooting.",
|
"docs": "Deeper: [the full reference](docs/DETAILS.md) covers site and video intake, the quality contract, the agent roster, exit codes and troubleshooting.",
|
||||||
"license": "Mnemazine Community License 1.0: free for one person, including a solo business. An organisation needs a separate agreement. See [LICENSE](LICENSE).",
|
"license": "Mnemazine Community License 1.0: free for one person, including a solo business. An organisation needs a separate agreement. See [LICENSE](LICENSE).",
|
||||||
@@ -115,54 +118,54 @@
|
|||||||
"ru": {
|
"ru": {
|
||||||
"title": "Mnemazine",
|
"title": "Mnemazine",
|
||||||
"name": "Mnemazine",
|
"name": "Mnemazine",
|
||||||
"tagline": "Mnemazine читает вашу кучу скриншотов и ссылок и оставляет заметки, которыми вы потом реально пользуетесь.",
|
"tagline": "Mnemazine читает твою кучу скриншотов и ссылок и оставляет заметки, которыми ты потом пользуешься.",
|
||||||
"hero_alt": "Мнемозина из белого мрамора у классической колонны превращает сырые обрывки в слоистую систему знания",
|
"hero_alt": "Мнемозина из белого мрамора у классической колонны превращает сырые обрывки в слоистую систему знания",
|
||||||
"what": "Mnemazine это фабрика знания. Во входящие вы кладете что попало: скриншоты, PDF, ссылки, голосовые. Наружу выходят заметки в базе Obsidian. Читает, распознает и расшифровывает ваш же компьютер, а в базу заметка попадает только с источником и вердиктом.",
|
"what": "Mnemazine это фабрика знания. Во входящие ты кладешь что попало: скриншоты, PDF, ссылки, голосовые. Наружу выходят заметки в базе Obsidian. Читает, распознает и расшифровывает твой же компьютер, а в базу заметка попадает только с источником и вердиктом.",
|
||||||
"why": "Ссылки копятся, скриншоты копятся, знание нет. Куча растет, читать ее некому, а через полгода вы уже не помните, зачем это сохранили. Mnemazine читает эту кучу за вас и пишет заметку для вас будущего: с источником, без дублей, короткую настолько, чтобы ее открыли.",
|
"why": "Ссылки копятся, скриншоты копятся, знание нет. Куча растет, читать ее некому, а через полгода ты уже не помнишь, зачем это сохранил. Mnemazine читает эту кучу за тебя и пишет заметку для тебя через полгода: с источником, без дублей, короткую настолько, чтобы ее открыли.",
|
||||||
"advantage": "тяжелое делается локально, поэтому повторный файл не стоит ничего.",
|
"advantage": "тяжелое делается локально, поэтому повторный файл не стоит ничего.",
|
||||||
"better": "Распознавание, разбор, расшифровка и хеширование идут на вашей машине. Файл, который уже проходил обработку, узнается по хешу и больше не доезжает до платной модели.",
|
"better": "Распознавание, разбор, расшифровка и хеширование идут на твоей машине. Файл, который уже проходил обработку, узнается по хешу и больше не доезжает до платной модели.",
|
||||||
"how": "Один прогон проходит весь путь. Каждая стадия оставляет доказательство, и прогон не закрывается, пока хоть один файл не учтен.",
|
"how": "Один прогон проходит весь путь. Каждая стадия оставляет доказательство, и прогон не закрывается, пока хоть один файл не учтен.",
|
||||||
"quick_intro": "Нужны Node.js 20 или новее, Python 3.11 или новее и git. Лучше Mac: распознавание картинок работает только там. На Linux остальное работает.",
|
"quick_intro": "Нужны Node.js 20 или новее, Python 3.11 или новее и git. Лучше Mac: распознавание картинок работает только там. На Linux остальное работает.",
|
||||||
"quick_extra": "`setup.sh` это ведомый путь: он проверяет предпосылки, спрашивает, где будут входящие, и умеет развернуть Telegram-бота. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` показывает план, ничего не трогая, а `bash install.sh` это неинтерактивный скелет, если вы уже знаете, что хотите. Нет Git? Скачайте [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) или [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) и запустите тот же скрипт внутри. Первый раз? Откройте проект в Claude Code и запустите `/mnemazine-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без вашего «да».",
|
"quick_extra": "`setup.sh` это ведомый путь: он проверяет предпосылки, спрашивает, где будут входящие, и умеет развернуть Telegram-бота. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` показывает план, ничего не трогая, а `bash install.sh` это неинтерактивный скелет, если ты уже знаешь, что хочешь. Нет Git? Скачай [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) или [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) и запусти тот же скрипт внутри. Первый раз? Открой проект в Claude Code и запусти `/mnemazine-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без твоего «да».\n\nЧтобы попробовать приложение в строке меню macOS после настройки проекта, выполни `npm run app:build`, затем `open .mnemazine/tmp/Mnemazine.app`. Для запуска нужна macOS 14+, для сборки Xcode 26+ с macOS 26 SDK. Рядом с поиском в стиле Spotlight стоят отдельные круглые кнопки ссылок, файлов, буфера и настроек. При переносе файла строка становится зоной приема; обработка начинается только после подтверждения. На macOS 26 используется нативное Liquid Glass, на более ранних версиях системные материалы. Значок приложения изображает граф связанных узлов. Подробнее: [приложение macOS](docs/macos-app.ru.md).",
|
||||||
"quick_result": "папки готовы, движки честно говорят, что стоит, а что урезано, и `vault/` открывается как база Obsidian.",
|
"quick_result": "папки готовы, движки честно говорят, что стоит, а что урезано, и `vault/` открывается как база Obsidian.",
|
||||||
"compare": [
|
"compare": [
|
||||||
[
|
[
|
||||||
"**Mnemazine**",
|
"**Mnemazine**",
|
||||||
"Локальная фабрика знания",
|
"Локальная фабрика знания",
|
||||||
"На вашей машине",
|
"На твоей машине",
|
||||||
"Да, ради этого и сделано",
|
"Да, ради этого и сделано",
|
||||||
"Проверенные заметки, дедуп, недельная сводка",
|
"Проверенные заметки, дедуп, недельная сводка",
|
||||||
"Лучший результат на Mac, установка занимает несколько минут"
|
"Лучший результат на Mac, установка занимает несколько минут"
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"Obsidian руками",
|
"Obsidian руками",
|
||||||
"Заметочник, который вы наполняете сами",
|
"Заметочник, который ты наполняешь сам",
|
||||||
"На вашей машине",
|
"На твоей машине",
|
||||||
"Нет, читаете вы",
|
"Нет, читаешь ты",
|
||||||
"Полный контроль над структурой",
|
"Полный контроль над структурой",
|
||||||
"За вас никто не читает, не проверяет и не убирает дубли"
|
"За тебя никто не читает, не проверяет и не убирает дубли"
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"NotebookLM",
|
"NotebookLM",
|
||||||
"Облачный блокнот, куда вы загружаете документы",
|
"Облачный блокнот, куда ты загружаешь документы",
|
||||||
"На серверах Google",
|
"На серверах Google",
|
||||||
"Да, после загрузки",
|
"Да, после загрузки",
|
||||||
"Быстрые ответы по загруженному",
|
"Быстрые ответы по загруженному",
|
||||||
"Материал уходит с вашей машины, заметки остаются в сервисе"
|
"Материал уходит с твоей машины, заметки остаются в сервисе"
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"Notion AI",
|
"Notion AI",
|
||||||
"Рабочее пространство с помощником",
|
"Рабочее пространство с помощником",
|
||||||
"На серверах Notion",
|
"На серверах Notion",
|
||||||
"Да, внутри пространства",
|
"Да, внутри пространства",
|
||||||
"Поиск и черновики по вашим страницам",
|
"Поиск и черновики по твоим страницам",
|
||||||
"Ваш корпус живет внутри чужого продукта"
|
"Твой корпус живет внутри чужого продукта"
|
||||||
],
|
],
|
||||||
[
|
[
|
||||||
"Readwise Reader",
|
"Readwise Reader",
|
||||||
"Читалка отложенного с цитатами",
|
"Читалка отложенного с цитатами",
|
||||||
"На серверах Readwise",
|
"На серверах Readwise",
|
||||||
"Ссылки и статьи, но не ваши папки",
|
"Ссылки и статьи, но не твои папки",
|
||||||
"Цитаты, которые уезжают в заметки",
|
"Цитаты, которые уезжают в заметки",
|
||||||
"Он сохраняет и напоминает, но не проверяет"
|
"Он сохраняет и напоминает, но не проверяет"
|
||||||
],
|
],
|
||||||
@@ -186,31 +189,34 @@
|
|||||||
]
|
]
|
||||||
],
|
],
|
||||||
"safety": [
|
"safety": [
|
||||||
"Локально по умолчанию: распознавание, разбор, расшифровка и хеширование идут на вашей машине.",
|
"Локально по умолчанию: распознавание, разбор, расшифровка и хеширование идут на твоей машине.",
|
||||||
"Глубокий режим отправляет материал вашему провайдеру модели, только если вы согласились; с выключенным режимом прогон стоит ноль токенов.",
|
"Глубокий режим отправляет материал твоему провайдеру модели, только если ты согласился; с выключенным режимом прогон стоит ноль токенов.",
|
||||||
"Telegram-бот ваш, а не общий, и без него система работает точно так же.",
|
"Telegram-бот твой, а не общий, и без него система работает точно так же.",
|
||||||
"Токен бота лежит с закрытыми правами и не попадает в Git.",
|
"Токен бота лежит с закрытыми правами и не попадает в Git.",
|
||||||
"Заметки, помеченные как персональные данные, ворота экспорта не выпускают наружу.",
|
"Заметки, помеченные как персональные данные, ворота экспорта не выпускают наружу.",
|
||||||
"Разбор сайтов и видео трогает только тот адрес, который вы дали сами."
|
"Разбор сайтов и видео трогает только тот адрес, который ты дал сам."
|
||||||
],
|
],
|
||||||
"safety_tail": "Что и куда уходит по каждому каналу и какой сторож это держит, расписано в [полном разборе](docs/DETAILS.ru.md).",
|
"safety_tail": "Что и куда уходит по каждому каналу и какой сторож это держит, расписано в [полном разборе](docs/DETAILS.ru.md).",
|
||||||
"status": "Статус: работает, есть релизная проверка и честные коды возврата.",
|
"status": "Статус: работает, есть релизная проверка и честные коды возврата.",
|
||||||
"limits": [
|
"limits": [
|
||||||
"Распознавание Apple Vision только на macOS; на Linux скриншоты уходят модели или остаются непрочитанными.",
|
"Распознавание Apple Vision только на macOS; на Linux скриншоты уходят модели или остаются непрочитанными.",
|
||||||
"Проверка находит источники и противоречия, но итоговое суждение остается за вами.",
|
"Проверка находит источники и противоречия, но итоговое суждение остается за тобой.",
|
||||||
"Очень большой первый прогон занимает время, а в глубоком режиме еще и токены.",
|
"Очень большой первый прогон занимает время, а в глубоком режиме еще и токены.",
|
||||||
"База это обычный Markdown: никакой сервис не держит для вас резервную копию."
|
"База это обычный Markdown: никакой сервис не держит для тебя резервную копию.",
|
||||||
|
"Приложение macOS пока собирается из исходников с ad-hoc подписью. Готового нотарифицированного приложения для скачивания и установщика нет. Пути к локальному проекту и Node.js должны оставаться рабочими: самостоятельный backend в сборку не входит.",
|
||||||
|
"В приложение можно вставить URL, включая ссылку YouTube, или название как запрос на исследование. Полный текст страницы и расшифровка видео не гарантируются.",
|
||||||
|
"Встроены CLI-адаптеры Claude Code, Codex и Kimi. После ошибки квоты или частоты запросов замена выбирается только среди допущенных исполнителей; другим CLI нужен адаптер. Обнаружение не подтверждает вход в аккаунт или квоту."
|
||||||
],
|
],
|
||||||
"docs": "Глубже: [полный разбор](docs/DETAILS.ru.md) про прием сайтов и видео, контракт качества, состав агентов, коды возврата и разбор поломок.",
|
"docs": "Глубже: [полный разбор](docs/DETAILS.ru.md) про прием сайтов и видео, контракт качества, состав агентов, коды возврата и разбор поломок.",
|
||||||
"license": "Mnemazine Community License 1.0: бесплатно одному человеку, включая работу на себя. Организации нужно отдельное соглашение. Текст в файле [LICENSE](LICENSE).",
|
"license": "Mnemazine Community License 1.0: бесплатно одному человеку, включая работу на себя. Организации нужно отдельное соглашение. Текст в файле [LICENSE](LICENSE).",
|
||||||
"welcome": "Привет. Я, как и все, сохраняю ссылки и делаю скриншоты, и, как и все, никогда к ним не возвращался. Куча росла, знание нет.\n\nMnemazine читает эту кучу на моей же машине и оставляет заметки, написанные для меня через полгода. Если она сделает то же для вас, забирайте и делайте своей.",
|
"welcome": "Привет. Я, как и все, сохраняю ссылки и делаю скриншоты, и, как и все, никогда к ним не возвращался. Куча росла, знание нет.\n\nMnemazine читает эту кучу на моей же машине и оставляет заметки, написанные для меня через полгода. Если она сделает то же для тебя, забирай и делай своей.",
|
||||||
"compare_header": [
|
"compare_header": [
|
||||||
"Вариант",
|
"Вариант",
|
||||||
"Что это",
|
"Что это",
|
||||||
"Где идет работа",
|
"Где идет работа",
|
||||||
"Читает ваши файлы",
|
"Читает твои файлы",
|
||||||
"Что получаете",
|
"Что получаешь",
|
||||||
"Чем платите"
|
"Чем платишь"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"zh": {
|
"zh": {
|
||||||
@@ -224,7 +230,7 @@
|
|||||||
"better": "识别、解析、转写和哈希都在你的机器上跑。处理过的文件靠哈希认出来,不会再送到付费模型那边。",
|
"better": "识别、解析、转写和哈希都在你的机器上跑。处理过的文件靠哈希认出来,不会再送到付费模型那边。",
|
||||||
"how": "一次运行走完整条路。每个阶段都留下证据,只要还有一个文件没交代,这次运行就不结束。",
|
"how": "一次运行走完整条路。每个阶段都留下证据,只要还有一个文件没交代,这次运行就不结束。",
|
||||||
"quick_intro": "需要 Node.js 20 以上、Python 3.11 以上和 git。最好是 Mac:图片识别只有那里有。在 Linux 上其余照常。",
|
"quick_intro": "需要 Node.js 20 以上、Python 3.11 以上和 git。最好是 Mac:图片识别只有那里有。在 Linux 上其余照常。",
|
||||||
"quick_extra": "`setup.sh` 是带引导的路径:它检查前置条件,问你收件箱放在哪里,还能部署 Telegram 机器人。`MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` 只看计划,不动任何文件;`bash install.sh` 是非交互的骨架安装,适合你已经清楚要什么的时候。没有 Git?下载 [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) 或 [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz),在里面跑同样的脚本。 第一次用?在 Claude Code 里打开项目并运行 `/mnemazine-setup`:安装以对话方式进行,一次问一个问题,没有你的同意不会装任何东西。",
|
"quick_extra": "`setup.sh` 是带引导的路径:它检查前置条件,问你收件箱放在哪里,还能部署 Telegram 机器人。`MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` 只看计划,不动任何文件;`bash install.sh` 是非交互的骨架安装,适合你已经清楚要什么的时候。没有 Git?下载 [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) 或 [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz),在里面跑同样的脚本。 第一次用?在 Claude Code 里打开项目并运行 `/mnemazine-setup`:安装以对话方式进行,一次问一个问题,没有你的同意不会装任何东西。\n\n配置项目后,运行 `npm run app:build`,再运行 `open .mnemazine/tmp/Mnemazine.app`,即可试用 macOS 菜单栏预览版。运行需要 macOS 14+;构建需要 Xcode 26+ 和 macOS 26 SDK。Spotlight 风格的搜索栏旁有独立圆形按钮,用于链接、文件、剪贴板和设置。拖入文件时,整行变为接收区域;确认后才开始处理。macOS 26 使用原生 Liquid Glass,旧版本使用系统材质。应用图标是相连的图谱节点。详见[应用指南(俄语)](docs/macos-app.ru.md)。",
|
||||||
"quick_result": "目录建好,各个引擎老实说明哪些可用、哪些降级,`vault/` 可以直接当 Obsidian 知识库打开。",
|
"quick_result": "目录建好,各个引擎老实说明哪些可用、哪些降级,`vault/` 可以直接当 Obsidian 知识库打开。",
|
||||||
"compare": [
|
"compare": [
|
||||||
[
|
[
|
||||||
@@ -300,7 +306,10 @@
|
|||||||
"Apple Vision 识别只在 macOS 上;在 Linux 上截图要么交给模型,要么留着不读。",
|
"Apple Vision 识别只在 macOS 上;在 Linux 上截图要么交给模型,要么留着不读。",
|
||||||
"核验能找到来源和矛盾,但最终判断仍然是你的。",
|
"核验能找到来源和矛盾,但最终判断仍然是你的。",
|
||||||
"第一次处理很大的一堆材料会花时间,在深度模式下还会花 token。",
|
"第一次处理很大的一堆材料会花时间,在深度模式下还会花 token。",
|
||||||
"知识库就是普通的 Markdown:没有哪个服务替你做备份。"
|
"知识库就是普通的 Markdown:没有哪个服务替你做备份。",
|
||||||
|
"macOS 应用目前需从源码构建,使用 ad-hoc 签名,尚无经过公证的下载包或安装程序。本地项目和 Node.js 路径必须有效,应用包不包含独立后端。",
|
||||||
|
"应用可接收 URL(包括 YouTube 链接)或标题作为研究请求,不保证取得完整网页或视频转写。",
|
||||||
|
"内置 Claude Code、Codex 和 Kimi 的 CLI 适配器。遇到配额或频率限制错误,只会切换到获准且具备所需能力的服务;其他 CLI 需要适配器。检测到程序不代表已登录或仍有配额。"
|
||||||
],
|
],
|
||||||
"docs": "想更深:[完整参考](docs/DETAILS.md) 讲网站与视频接入、质量契约、智能体名单、退出码和故障排查。",
|
"docs": "想更深:[完整参考](docs/DETAILS.md) 讲网站与视频接入、质量契约、智能体名单、退出码和故障排查。",
|
||||||
"license": "Mnemazine Community License 1.0:一个人使用免费,包括你自己单干的生意。组织使用需要单独协议。见 [LICENSE](LICENSE)。",
|
"license": "Mnemazine Community License 1.0:一个人使用免费,包括你自己单干的生意。组织使用需要单独协议。见 [LICENSE](LICENSE)。",
|
||||||
@@ -325,9 +334,9 @@
|
|||||||
},
|
},
|
||||||
"ru": {
|
"ru": {
|
||||||
"short": "Скриншоты, PDF, ссылки, заметки, аудио, видео",
|
"short": "Скриншоты, PDF, ссылки, заметки, аудио, видео",
|
||||||
"body": "Вы кладете файлы в одну папку или отправляете их своему Telegram-боту. Больше от вас ничего не нужно.",
|
"body": "Ты кладешь файлы в одну папку или отправляешь их своему Telegram-боту. Больше от тебя ничего не нужно.",
|
||||||
"result": "одни входящие, где лежит все, что ждет прочтения.",
|
"result": "одни входящие, где лежит все, что ждет прочтения.",
|
||||||
"alt": "Этап 1 такта Mnemazine: Положите материал во входящие, показан широкой мраморной сценой Pantheon"
|
"alt": "Этап 1 такта Mnemazine: Положи материал во входящие, показан широкой мраморной сценой Pantheon"
|
||||||
},
|
},
|
||||||
"zh": {
|
"zh": {
|
||||||
"short": "截图、PDF、链接、笔记、音频、视频",
|
"short": "截图、PDF、链接、笔记、音频、视频",
|
||||||
@@ -405,7 +414,7 @@
|
|||||||
},
|
},
|
||||||
"ru": {
|
"ru": {
|
||||||
"short": "Длинный материал режется на переиспользуемые атомы",
|
"short": "Длинный материал режется на переиспользуемые атомы",
|
||||||
"body": "Длинный гайд превращается в несколько узких заметок, у каждой понятный заголовок и короткий блок о том, чем она вам поможет. Близкие дубли находятся по смыслу и сливаются, а не копятся.",
|
"body": "Длинный гайд превращается в несколько узких заметок, у каждой понятный заголовок и короткий блок о том, чем она тебе поможет. Близкие дубли находятся по смыслу и сливаются, а не копятся.",
|
||||||
"result": "заметки такой длины, что будущий запрос тянет только нужную.",
|
"result": "заметки такой длины, что будущий запрос тянет только нужную.",
|
||||||
"alt": "Этап 5 такта Mnemazine: Одна заметка на одну мысль, показан широкой мраморной сценой Pantheon"
|
"alt": "Этап 5 такта Mnemazine: Одна заметка на одну мысль, показан широкой мраморной сценой Pantheon"
|
||||||
},
|
},
|
||||||
@@ -446,7 +455,7 @@
|
|||||||
"ru": {
|
"ru": {
|
||||||
"short": "HTML-сводка, отчет по знанию и запросы к графу",
|
"short": "HTML-сводка, отчет по знанию и запросы к графу",
|
||||||
"body": "Недельная HTML-сводка показывает, что изменилось и на что стоит потратить время. Граф позволяет агенту спросить базу, а не загружать ее целиком в контекст.",
|
"body": "Недельная HTML-сводка показывает, что изменилось и на что стоит потратить время. Граф позволяет агенту спросить базу, а не загружать ее целиком в контекст.",
|
||||||
"result": "знание, которое возвращается к вам само, а не ждет, пока его вспомнят.",
|
"result": "знание, которое возвращается к тебе само, а не ждет, пока его вспомнят.",
|
||||||
"alt": "Этап 7 такта Mnemazine: Недельная сводка и поиск, показан широкой мраморной сценой Pantheon"
|
"alt": "Этап 7 такта Mnemazine: Недельная сводка и поиск, показан широкой мраморной сценой Pantheon"
|
||||||
},
|
},
|
||||||
"zh": {
|
"zh": {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
"project": {
|
"project": {
|
||||||
"slug": "mnemazine",
|
"slug": "mnemazine",
|
||||||
"deity": "Mnemosyne",
|
"deity": "Mnemosyne",
|
||||||
"symbol": "memory scroll and knowledge graph"
|
"symbol": "horizontal knowledge graph; memory scroll remains a narrative prop"
|
||||||
},
|
},
|
||||||
"visuals": {
|
"visuals": {
|
||||||
"style_anchor_sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
|
"style_anchor_sha256": "ce524f9d22cb0092cb17aa280832e1b2ab2a77a0e01602065ec502232a3bb2d2",
|
||||||
@@ -33,7 +33,7 @@
|
|||||||
{
|
{
|
||||||
"id": "capture",
|
"id": "capture",
|
||||||
"title_en": "Drop material into the inbox",
|
"title_en": "Drop material into the inbox",
|
||||||
"title_ru": "Положите материал во входящие",
|
"title_ru": "Положи материал во входящие",
|
||||||
"diagram_en": "Capture",
|
"diagram_en": "Capture",
|
||||||
"diagram_ru": "Захват",
|
"diagram_ru": "Захват",
|
||||||
"title_zh": "把材料丢进收件箱",
|
"title_zh": "把材料丢进收件箱",
|
||||||
@@ -168,6 +168,10 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"doc_pages": [
|
"doc_pages": [
|
||||||
|
{
|
||||||
|
"path": "docs/macos-app.ru.md",
|
||||||
|
"frames": ["assets/pantheon/app-icon-mnemazine.png"]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"path": "docs/DETAILS.md",
|
"path": "docs/DETAILS.md",
|
||||||
"frames": [
|
"frames": [
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ __pycache__/
|
|||||||
.env
|
.env
|
||||||
.mnemazine/cache/
|
.mnemazine/cache/
|
||||||
.mnemazine/tmp/
|
.mnemazine/tmp/
|
||||||
|
.mnemazine/design-review/
|
||||||
.mnemazine/bin/
|
.mnemazine/bin/
|
||||||
.mnemazine/archive/
|
.mnemazine/archive/
|
||||||
.mnemazine/state/
|
.mnemazine/state/
|
||||||
@@ -44,6 +45,7 @@ handoff-*.md
|
|||||||
|
|
||||||
# Internal audit/plan docs (local vault paths + project names; not public).
|
# Internal audit/plan docs (local vault paths + project names; not public).
|
||||||
docs/PLAN-*.md
|
docs/PLAN-*.md
|
||||||
|
docs/theia-ui-review-prompt.ru.md
|
||||||
|
|
||||||
# Private/generated vault maintenance waves. They may contain local vault paths,
|
# Private/generated vault maintenance waves. They may contain local vault paths,
|
||||||
# project names, or one-off migration content and must not ship publicly.
|
# project names, or one-off migration content and must not ship publicly.
|
||||||
|
|||||||
@@ -141,6 +141,8 @@ npm run doctor # plain terminal: is it alive?
|
|||||||
|
|
||||||
`setup.sh` is the guided path: it checks the prerequisites, asks where the inbox goes, and can deploy the Telegram bot. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` previews it without touching anything, and `bash install.sh` is the non-interactive skeleton if you already know what you want. No Git? Download [the ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) or [the tarball](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) and run the same script inside. First time here? Open the project in Claude Code and run `/mnemazine-setup`: the install goes as a conversation, one question at a time, and nothing is installed without your yes.
|
`setup.sh` is the guided path: it checks the prerequisites, asks where the inbox goes, and can deploy the Telegram bot. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` previews it without touching anything, and `bash install.sh` is the non-interactive skeleton if you already know what you want. No Git? Download [the ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) or [the tarball](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) and run the same script inside. First time here? Open the project in Claude Code and run `/mnemazine-setup`: the install goes as a conversation, one question at a time, and nothing is installed without your yes.
|
||||||
|
|
||||||
|
To try the macOS menu-bar preview after setup, run `npm run app:build`, then `open .mnemazine/tmp/Mnemazine.app`. It runs on macOS 14+; building needs Xcode 26+ with the macOS 26 SDK. The app opens a Spotlight-style search capsule beside separate round controls for links, files, clipboard and settings. Dragging a file turns the row into a drop target; processing starts only after confirmation. Native Liquid Glass is used on macOS 26, with system materials on older versions. The icon is a connected-node graph. See [the app guide (Russian)](docs/macos-app.ru.md).
|
||||||
|
|
||||||
Never done this before? [The onboarding](docs/ONBOARDING.md) walks the whole first run step by step and says what you see after every command.
|
Never done this before? [The onboarding](docs/ONBOARDING.md) walks the whole first run step by step and says what you see after every command.
|
||||||
|
|
||||||
**You get:** the folders are ready, the engines say plainly what is installed and what is degraded, and `vault/` opens as an Obsidian vault.
|
**You get:** the folders are ready, the engines say plainly what is installed and what is degraded, and `vault/` opens as an Obsidian vault.
|
||||||
@@ -187,6 +189,9 @@ Status: working, with a release check and honest exit codes.
|
|||||||
- Verification finds sources and contradictions, but the final judgement is still yours.
|
- Verification finds sources and contradictions, but the final judgement is still yours.
|
||||||
- A very large first run takes time and, in deep mode, tokens.
|
- A very large first run takes time and, in deep mode, tokens.
|
||||||
- The vault is plain Markdown: no hosted service keeps a backup for you.
|
- The vault is plain Markdown: no hosted service keeps a backup for you.
|
||||||
|
- The macOS app is a source preview with an ad-hoc signature, not a notarized download or installer. Its local repository and Node.js paths must remain valid; the bundle does not include a standalone backend.
|
||||||
|
- The app accepts URLs, including YouTube links, or titles as research requests. A full page or video transcript is not guaranteed.
|
||||||
|
- CLI discovery includes built-in Claude Code, Codex and Kimi adapters. After a quota or rate-limit error, fallback uses only eligible providers; other CLIs need an adapter. Discovery does not confirm login or quota.
|
||||||
|
|
||||||
Deeper: [the full reference](docs/DETAILS.md) covers site and video intake, the quality contract, the agent roster, exit codes and troubleshooting.
|
Deeper: [the full reference](docs/DETAILS.md) covers site and video intake, the quality contract, the agent roster, exit codes and troubleshooting.
|
||||||
|
|
||||||
|
|||||||
+28
-23
@@ -1,6 +1,6 @@
|
|||||||
# Mnemazine
|
# Mnemazine
|
||||||
|
|
||||||
Mnemazine читает вашу кучу скриншотов и ссылок и оставляет заметки, которыми вы потом реально пользуетесь.
|
Mnemazine читает твою кучу скриншотов и ссылок и оставляет заметки, которыми ты потом пользуешься.
|
||||||
|
|
||||||
[English](README.md) · [中文](README.zh.md)
|
[English](README.md) · [中文](README.zh.md)
|
||||||
|
|
||||||
@@ -12,7 +12,7 @@ Mnemazine читает вашу кучу скриншотов и ссылок и
|
|||||||
|
|
||||||
> Привет. Я, как и все, сохраняю ссылки и делаю скриншоты, и, как и все, никогда к ним не возвращался. Куча росла, знание нет.
|
> Привет. Я, как и все, сохраняю ссылки и делаю скриншоты, и, как и все, никогда к ним не возвращался. Куча росла, знание нет.
|
||||||
>
|
>
|
||||||
> Mnemazine читает эту кучу на моей же машине и оставляет заметки, написанные для меня через полгода. Если она сделает то же для вас, забирайте и делайте своей.
|
> Mnemazine читает эту кучу на моей же машине и оставляет заметки, написанные для меня через полгода. Если она сделает то же для тебя, забирай и делай своей.
|
||||||
>
|
>
|
||||||
> — Филипп Зарубин
|
> — Филипп Зарубин
|
||||||
|
|
||||||
@@ -35,17 +35,17 @@ Mnemazine читает вашу кучу скриншотов и ссылок и
|
|||||||
|
|
||||||
## Что это
|
## Что это
|
||||||
|
|
||||||
Mnemazine это фабрика знания. Во входящие вы кладете что попало: скриншоты, PDF, ссылки, голосовые. Наружу выходят заметки в базе Obsidian. Читает, распознает и расшифровывает ваш же компьютер, а в базу заметка попадает только с источником и вердиктом.
|
Mnemazine это фабрика знания. Во входящие ты кладешь что попало: скриншоты, PDF, ссылки, голосовые. Наружу выходят заметки в базе Obsidian. Читает, распознает и расшифровывает твой же компьютер, а в базу заметка попадает только с источником и вердиктом.
|
||||||
|
|
||||||
## Зачем это нужно
|
## Зачем это нужно
|
||||||
|
|
||||||
Ссылки копятся, скриншоты копятся, знание нет. Куча растет, читать ее некому, а через полгода вы уже не помните, зачем это сохранили. Mnemazine читает эту кучу за вас и пишет заметку для вас будущего: с источником, без дублей, короткую настолько, чтобы ее открыли.
|
Ссылки копятся, скриншоты копятся, знание нет. Куча растет, читать ее некому, а через полгода ты уже не помнишь, зачем это сохранил. Mnemazine читает эту кучу за тебя и пишет заметку для тебя через полгода: с источником, без дублей, короткую настолько, чтобы ее открыли.
|
||||||
|
|
||||||
## Главное преимущество
|
## Главное преимущество
|
||||||
|
|
||||||
**Главное преимущество:** тяжелое делается локально, поэтому повторный файл не стоит ничего.
|
**Главное преимущество:** тяжелое делается локально, поэтому повторный файл не стоит ничего.
|
||||||
|
|
||||||
**Почему это лучше:** Распознавание, разбор, расшифровка и хеширование идут на вашей машине. Файл, который уже проходил обработку, узнается по хешу и больше не доезжает до платной модели.
|
**Почему это лучше:** Распознавание, разбор, расшифровка и хеширование идут на твоей машине. Файл, который уже проходил обработку, узнается по хешу и больше не доезжает до платной модели.
|
||||||
|
|
||||||
## Как это работает
|
## Как это работает
|
||||||
|
|
||||||
@@ -67,11 +67,11 @@ Mnemazine это фабрика знания. Во входящие вы кла
|
|||||||
| 6. Хранение | Разделы, связи, оглавления и ворота полноты |
|
| 6. Хранение | Разделы, связи, оглавления и ворота полноты |
|
||||||
| 7. Возврат | HTML-сводка, отчет по знанию и запросы к графу |
|
| 7. Возврат | HTML-сводка, отчет по знанию и запросы к графу |
|
||||||
|
|
||||||
### Шаг 1: Положите материал во входящие
|
### Шаг 1: Положи материал во входящие
|
||||||
|
|
||||||
Вы кладете файлы в одну папку или отправляете их своему Telegram-боту. Больше от вас ничего не нужно.
|
Ты кладешь файлы в одну папку или отправляешь их своему Telegram-боту. Больше от тебя ничего не нужно.
|
||||||
|
|
||||||
<p align="center"><img src="docs/assets/pantheon/workflow/01-capture.png" alt="Этап 1 такта Mnemazine: Положите материал во входящие, показан широкой мраморной сценой Pantheon" width="100%"></p>
|
<p align="center"><img src="docs/assets/pantheon/workflow/01-capture.png" alt="Этап 1 такта Mnemazine: Положи материал во входящие, показан широкой мраморной сценой Pantheon" width="100%"></p>
|
||||||
|
|
||||||
**Что получится:** одни входящие, где лежит все, что ждет прочтения.
|
**Что получится:** одни входящие, где лежит все, что ждет прочтения.
|
||||||
|
|
||||||
@@ -101,7 +101,7 @@ Mnemazine это фабрика знания. Во входящие вы кла
|
|||||||
|
|
||||||
### Шаг 5: Одна заметка на одну мысль
|
### Шаг 5: Одна заметка на одну мысль
|
||||||
|
|
||||||
Длинный гайд превращается в несколько узких заметок, у каждой понятный заголовок и короткий блок о том, чем она вам поможет. Близкие дубли находятся по смыслу и сливаются, а не копятся.
|
Длинный гайд превращается в несколько узких заметок, у каждой понятный заголовок и короткий блок о том, чем она тебе поможет. Близкие дубли находятся по смыслу и сливаются, а не копятся.
|
||||||
|
|
||||||
<p align="center"><img src="docs/assets/pantheon/workflow/05-refine.png" alt="Этап 5 такта Mnemazine: Одна заметка на одну мысль, показан широкой мраморной сценой Pantheon" width="100%"></p>
|
<p align="center"><img src="docs/assets/pantheon/workflow/05-refine.png" alt="Этап 5 такта Mnemazine: Одна заметка на одну мысль, показан широкой мраморной сценой Pantheon" width="100%"></p>
|
||||||
|
|
||||||
@@ -121,7 +121,7 @@ Mnemazine это фабрика знания. Во входящие вы кла
|
|||||||
|
|
||||||
<p align="center"><img src="docs/assets/pantheon/workflow/07-retrieve.png" alt="Этап 7 такта Mnemazine: Недельная сводка и поиск, показан широкой мраморной сценой Pantheon" width="100%"></p>
|
<p align="center"><img src="docs/assets/pantheon/workflow/07-retrieve.png" alt="Этап 7 такта Mnemazine: Недельная сводка и поиск, показан широкой мраморной сценой Pantheon" width="100%"></p>
|
||||||
|
|
||||||
**Что получится:** знание, которое возвращается к вам само, а не ждет, пока его вспомнят.
|
**Что получится:** знание, которое возвращается к тебе само, а не ждет, пока его вспомнят.
|
||||||
|
|
||||||
## Быстрый старт
|
## Быстрый старт
|
||||||
|
|
||||||
@@ -139,7 +139,9 @@ code . # an editor, no agent at all
|
|||||||
npm run doctor # plain terminal: is it alive?
|
npm run doctor # plain terminal: is it alive?
|
||||||
```
|
```
|
||||||
|
|
||||||
`setup.sh` это ведомый путь: он проверяет предпосылки, спрашивает, где будут входящие, и умеет развернуть Telegram-бота. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` показывает план, ничего не трогая, а `bash install.sh` это неинтерактивный скелет, если вы уже знаете, что хотите. Нет Git? Скачайте [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) или [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) и запустите тот же скрипт внутри. Первый раз? Откройте проект в Claude Code и запустите `/mnemazine-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без вашего «да».
|
`setup.sh` это ведомый путь: он проверяет предпосылки, спрашивает, где будут входящие, и умеет развернуть Telegram-бота. `MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` показывает план, ничего не трогая, а `bash install.sh` это неинтерактивный скелет, если ты уже знаешь, что хочешь. Нет Git? Скачай [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) или [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz) и запусти тот же скрипт внутри. Первый раз? Открой проект в Claude Code и запусти `/mnemazine-setup`: установка пройдет разговором, по одному вопросу, и ничего не поставится без твоего «да».
|
||||||
|
|
||||||
|
Чтобы попробовать приложение в строке меню macOS после настройки проекта, выполни `npm run app:build`, затем `open .mnemazine/tmp/Mnemazine.app`. Для запуска нужна macOS 14+, для сборки Xcode 26+ с macOS 26 SDK. Рядом с поиском в стиле Spotlight стоят отдельные круглые кнопки ссылок, файлов, буфера и настроек. При переносе файла строка становится зоной приема; обработка начинается только после подтверждения. На macOS 26 используется нативное Liquid Glass, на более ранних версиях системные материалы. Значок приложения изображает граф связанных узлов. Подробнее: [приложение macOS](docs/macos-app.ru.md).
|
||||||
|
|
||||||
Делаешь это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
|
Делаешь это впервые? [Онбординг](docs/ONBOARDING.ru.md) проводит весь первый запуск по шагам и говорит, что видно после каждой команды.
|
||||||
|
|
||||||
@@ -147,13 +149,13 @@ npm run doctor # plain terminal: is it alive?
|
|||||||
|
|
||||||
## Простое сравнение
|
## Простое сравнение
|
||||||
|
|
||||||
| Вариант | Что это | Где идет работа | Читает ваши файлы | Что получаете | Чем платите |
|
| Вариант | Что это | Где идет работа | Читает твои файлы | Что получаешь | Чем платишь |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| **Mnemazine** | Локальная фабрика знания | На вашей машине | Да, ради этого и сделано | Проверенные заметки, дедуп, недельная сводка | Лучший результат на Mac, установка занимает несколько минут |
|
| **Mnemazine** | Локальная фабрика знания | На твоей машине | Да, ради этого и сделано | Проверенные заметки, дедуп, недельная сводка | Лучший результат на Mac, установка занимает несколько минут |
|
||||||
| Obsidian руками | Заметочник, который вы наполняете сами | На вашей машине | Нет, читаете вы | Полный контроль над структурой | За вас никто не читает, не проверяет и не убирает дубли |
|
| Obsidian руками | Заметочник, который ты наполняешь сам | На твоей машине | Нет, читаешь ты | Полный контроль над структурой | За тебя никто не читает, не проверяет и не убирает дубли |
|
||||||
| NotebookLM | Облачный блокнот, куда вы загружаете документы | На серверах Google | Да, после загрузки | Быстрые ответы по загруженному | Материал уходит с вашей машины, заметки остаются в сервисе |
|
| NotebookLM | Облачный блокнот, куда ты загружаешь документы | На серверах Google | Да, после загрузки | Быстрые ответы по загруженному | Материал уходит с твоей машины, заметки остаются в сервисе |
|
||||||
| Notion AI | Рабочее пространство с помощником | На серверах Notion | Да, внутри пространства | Поиск и черновики по вашим страницам | Ваш корпус живет внутри чужого продукта |
|
| Notion AI | Рабочее пространство с помощником | На серверах Notion | Да, внутри пространства | Поиск и черновики по твоим страницам | Твой корпус живет внутри чужого продукта |
|
||||||
| Readwise Reader | Читалка отложенного с цитатами | На серверах Readwise | Ссылки и статьи, но не ваши папки | Цитаты, которые уезжают в заметки | Он сохраняет и напоминает, но не проверяет |
|
| Readwise Reader | Читалка отложенного с цитатами | На серверах Readwise | Ссылки и статьи, но не твои папки | Цитаты, которые уезжают в заметки | Он сохраняет и напоминает, но не проверяет |
|
||||||
| Читать потом руками | План, который на деле есть у большинства куч | Нигде | Нет | Ставить нечего | «Потом» почти не наступает |
|
| Читать потом руками | План, который на деле есть у большинства куч | Нигде | Нет | Ставить нечего | «Потом» почти не наступает |
|
||||||
|
|
||||||
## Простые слова
|
## Простые слова
|
||||||
@@ -170,12 +172,12 @@ npm run doctor # plain terminal: is it alive?
|
|||||||
|
|
||||||
## Безопасность и приватность
|
## Безопасность и приватность
|
||||||
|
|
||||||
- Локально по умолчанию: распознавание, разбор, расшифровка и хеширование идут на вашей машине.
|
- Локально по умолчанию: распознавание, разбор, расшифровка и хеширование идут на твоей машине.
|
||||||
- Глубокий режим отправляет материал вашему провайдеру модели, только если вы согласились; с выключенным режимом прогон стоит ноль токенов.
|
- Глубокий режим отправляет материал твоему провайдеру модели, только если ты согласился; с выключенным режимом прогон стоит ноль токенов.
|
||||||
- Telegram-бот ваш, а не общий, и без него система работает точно так же.
|
- Telegram-бот твой, а не общий, и без него система работает точно так же.
|
||||||
- Токен бота лежит с закрытыми правами и не попадает в Git.
|
- Токен бота лежит с закрытыми правами и не попадает в Git.
|
||||||
- Заметки, помеченные как персональные данные, ворота экспорта не выпускают наружу.
|
- Заметки, помеченные как персональные данные, ворота экспорта не выпускают наружу.
|
||||||
- Разбор сайтов и видео трогает только тот адрес, который вы дали сами.
|
- Разбор сайтов и видео трогает только тот адрес, который ты дал сам.
|
||||||
|
|
||||||
Что и куда уходит по каждому каналу и какой сторож это держит, расписано в [полном разборе](docs/DETAILS.ru.md).
|
Что и куда уходит по каждому каналу и какой сторож это держит, расписано в [полном разборе](docs/DETAILS.ru.md).
|
||||||
|
|
||||||
@@ -184,9 +186,12 @@ npm run doctor # plain terminal: is it alive?
|
|||||||
Статус: работает, есть релизная проверка и честные коды возврата.
|
Статус: работает, есть релизная проверка и честные коды возврата.
|
||||||
|
|
||||||
- Распознавание Apple Vision только на macOS; на Linux скриншоты уходят модели или остаются непрочитанными.
|
- Распознавание Apple Vision только на macOS; на Linux скриншоты уходят модели или остаются непрочитанными.
|
||||||
- Проверка находит источники и противоречия, но итоговое суждение остается за вами.
|
- Проверка находит источники и противоречия, но итоговое суждение остается за тобой.
|
||||||
- Очень большой первый прогон занимает время, а в глубоком режиме еще и токены.
|
- Очень большой первый прогон занимает время, а в глубоком режиме еще и токены.
|
||||||
- База это обычный Markdown: никакой сервис не держит для вас резервную копию.
|
- База это обычный Markdown: никакой сервис не держит для тебя резервную копию.
|
||||||
|
- Приложение macOS пока собирается из исходников с ad-hoc подписью. Готового нотарифицированного приложения для скачивания и установщика нет. Пути к локальному проекту и Node.js должны оставаться рабочими: самостоятельный backend в сборку не входит.
|
||||||
|
- В приложение можно вставить URL, включая ссылку YouTube, или название как запрос на исследование. Полный текст страницы и расшифровка видео не гарантируются.
|
||||||
|
- Встроены CLI-адаптеры Claude Code, Codex и Kimi. После ошибки квоты или частоты запросов замена выбирается только среди допущенных исполнителей; другим CLI нужен адаптер. Обнаружение не подтверждает вход в аккаунт или квоту.
|
||||||
|
|
||||||
Глубже: [полный разбор](docs/DETAILS.ru.md) про прием сайтов и видео, контракт качества, состав агентов, коды возврата и разбор поломок.
|
Глубже: [полный разбор](docs/DETAILS.ru.md) про прием сайтов и видео, контракт качества, состав агентов, коды возврата и разбор поломок.
|
||||||
|
|
||||||
|
|||||||
@@ -141,6 +141,8 @@ npm run doctor # plain terminal: is it alive?
|
|||||||
|
|
||||||
`setup.sh` 是带引导的路径:它检查前置条件,问你收件箱放在哪里,还能部署 Telegram 机器人。`MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` 只看计划,不动任何文件;`bash install.sh` 是非交互的骨架安装,适合你已经清楚要什么的时候。没有 Git?下载 [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) 或 [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz),在里面跑同样的脚本。 第一次用?在 Claude Code 里打开项目并运行 `/mnemazine-setup`:安装以对话方式进行,一次问一个问题,没有你的同意不会装任何东西。
|
`setup.sh` 是带引导的路径:它检查前置条件,问你收件箱放在哪里,还能部署 Telegram 机器人。`MNEMAZINE_SETUP_DRYRUN=1 bash setup.sh` 只看计划,不动任何文件;`bash install.sh` 是非交互的骨架安装,适合你已经清楚要什么的时候。没有 Git?下载 [ZIP](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.zip) 或 [tar.gz](https://github.com/zarubinvibe/mnemazine/archive/refs/heads/main.tar.gz),在里面跑同样的脚本。 第一次用?在 Claude Code 里打开项目并运行 `/mnemazine-setup`:安装以对话方式进行,一次问一个问题,没有你的同意不会装任何东西。
|
||||||
|
|
||||||
|
配置项目后,运行 `npm run app:build`,再运行 `open .mnemazine/tmp/Mnemazine.app`,即可试用 macOS 菜单栏预览版。运行需要 macOS 14+;构建需要 Xcode 26+ 和 macOS 26 SDK。Spotlight 风格的搜索栏旁有独立圆形按钮,用于链接、文件、剪贴板和设置。拖入文件时,整行变为接收区域;确认后才开始处理。macOS 26 使用原生 Liquid Glass,旧版本使用系统材质。应用图标是相连的图谱节点。详见[应用指南(俄语)](docs/macos-app.ru.md)。
|
||||||
|
|
||||||
第一次做这件事?[上手引导](docs/ONBOARDING.zh.md) 会一步一步带你走完第一次运行,并写清楚每条命令之后你会看到什么。
|
第一次做这件事?[上手引导](docs/ONBOARDING.zh.md) 会一步一步带你走完第一次运行,并写清楚每条命令之后你会看到什么。
|
||||||
|
|
||||||
**你会得到:** 目录建好,各个引擎老实说明哪些可用、哪些降级,`vault/` 可以直接当 Obsidian 知识库打开。
|
**你会得到:** 目录建好,各个引擎老实说明哪些可用、哪些降级,`vault/` 可以直接当 Obsidian 知识库打开。
|
||||||
@@ -187,6 +189,9 @@ npm run doctor # plain terminal: is it alive?
|
|||||||
- 核验能找到来源和矛盾,但最终判断仍然是你的。
|
- 核验能找到来源和矛盾,但最终判断仍然是你的。
|
||||||
- 第一次处理很大的一堆材料会花时间,在深度模式下还会花 token。
|
- 第一次处理很大的一堆材料会花时间,在深度模式下还会花 token。
|
||||||
- 知识库就是普通的 Markdown:没有哪个服务替你做备份。
|
- 知识库就是普通的 Markdown:没有哪个服务替你做备份。
|
||||||
|
- macOS 应用目前需从源码构建,使用 ad-hoc 签名,尚无经过公证的下载包或安装程序。本地项目和 Node.js 路径必须有效,应用包不包含独立后端。
|
||||||
|
- 应用可接收 URL(包括 YouTube 链接)或标题作为研究请求,不保证取得完整网页或视频转写。
|
||||||
|
- 内置 Claude Code、Codex 和 Kimi 的 CLI 适配器。遇到配额或频率限制错误,只会切换到获准且具备所需能力的服务;其他 CLI 需要适配器。检测到程序不代表已登录或仍有配额。
|
||||||
|
|
||||||
想更深:[完整参考](docs/DETAILS.md) 讲网站与视频接入、质量契约、智能体名单、退出码和故障排查。
|
想更深:[完整参考](docs/DETAILS.md) 讲网站与视频接入、质量契约、智能体名单、退出码和故障排查。
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
{
|
{
|
||||||
|
"app:build": { "purpose": "Нативное macOS-приложение: локальная сборка в .mnemazine/tmp, ad-hoc подпись без публикации", "writes": { "vault": false, "repo": true, "home": true, "net": false } },
|
||||||
|
"app:test": { "purpose": "Swift-тесты контракта клиента и безопасного отображения; только macOS", "writes": { "vault": false, "repo": true, "home": true, "net": false } },
|
||||||
|
"jobs": { "purpose": "Общая локальная очередь: submit/list/status/cancel/retry/work. Pending list/status возобновляют worker; --no-start только читает. Deep ingest пишет vault и обращается к сети", "writes": { "vault": true, "repo": true, "home": false, "net": true } },
|
||||||
|
"olympuz": { "purpose": "Адаптер координатора Олимпуса к общей очереди; проверка происхождения, приём с явным deep, статус/отмена/повтор", "writes": { "vault": true, "repo": true, "home": false, "net": true } },
|
||||||
"install:local": { "purpose": "Первичная установка: каталоги, .venv, skills в $HOME/.claude/$HOME/.codex, симлинки в ~/.local/bin, конфиг .mnemazine, протокол-нота в vault", "writes": { "vault": true, "repo": true, "home": true, "net": true } },
|
"install:local": { "purpose": "Первичная установка: каталоги, .venv, skills в $HOME/.claude/$HOME/.codex, симлинки в ~/.local/bin, конфиг .mnemazine, протокол-нота в vault", "writes": { "vault": true, "repo": true, "home": true, "net": true } },
|
||||||
"start": { "purpose": "Строгий live-протокол: прогон инбокса (deep+require-deep) и финальный complete-гейт", "writes": { "vault": true, "repo": true, "home": true, "net": true } },
|
"start": { "purpose": "Строгий live-протокол: прогон инбокса (deep+require-deep) и финальный complete-гейт", "writes": { "vault": true, "repo": true, "home": true, "net": true } },
|
||||||
"desktop": { "purpose": "Алиас start — тот же desktop-протокол", "writes": { "vault": true, "repo": true, "home": true, "net": true } },
|
"desktop": { "purpose": "Алиас start — тот же desktop-протокол", "writes": { "vault": true, "repo": true, "home": true, "net": true } },
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 1.9 MiB |
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"asset": "app-icon-mnemazine.png",
|
||||||
|
"sha256": "281dd6481c06a1cbfeff88981e4c834c7fee937bd8b0f37bcab1e2344d4740c0",
|
||||||
|
"date": "2026-09-13",
|
||||||
|
"route": "codex:image_gen:managed-frontier",
|
||||||
|
"generation_id": "exec-556b4497-a267-4b98-a4d9-bff0d3d89a7f",
|
||||||
|
"purpose": "macOS launcher icon",
|
||||||
|
"prompt": "Replace radial mark with approved horizontally extended option 5 in a wide rectangular glass tile. Preserve marble Olympus Mons, caldera, stars and reflection. Correct top-middle to right-middle bond to top-middle to upper-right terminal. Eight nodes, nine bonds.",
|
||||||
|
"reference": "User-selected option 5, followed by explicit approval of both adaptation proofs",
|
||||||
|
"user_override": "Connected graph atoms replace scroll; preserve Olympus Mons and Iriz family materials.",
|
||||||
|
"visual_review": {
|
||||||
|
"result": "accepted",
|
||||||
|
"checks": [
|
||||||
|
"Eight nodes and nine bonds match approved option 5",
|
||||||
|
"Wide rectangular glass tile",
|
||||||
|
"Olympus Mons preserved"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"owner_approval": {
|
||||||
|
"at": "2026-09-13T12:24:13.709Z",
|
||||||
|
"source": "art-review-server",
|
||||||
|
"asset": "01-launch-icon",
|
||||||
|
"sha256_12": "281dd6481c06",
|
||||||
|
"verdict": "годится"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
# Application identity
|
||||||
|
|
||||||
|
The application mark is a horizontal graph with eight nodes and nine bonds.
|
||||||
|
Use `app-icon-mnemazine.png` for the launcher: the graph sits in a wide glass tile above marble Olympus Mons.
|
||||||
|
|
||||||
|
The menu bar uses the same graph as a native monochrome template image in
|
||||||
|
`macos/Sources/Mnemazine/MnemazineMark.swift`. macOS chooses its color for the current appearance.
|
||||||
|
The drawing is 32 by 18 points; the status item reserves 40 points.
|
||||||
|
|
||||||
|
The scroll in older narrative illustrations describes source material. It is not the application logo.
|
||||||
|
Do not substitute a radial cluster or squeeze the mark into a square.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# CLI и переключение при лимитах
|
||||||
|
|
||||||
|
Настройки приложения показывают найденные CLI и время паузы после лимита. Обнаружение читает PATH и стандартные каталоги установки; не выполняет вход в аккаунт, не вызывает модель и не проверяет баланс. «Найден» не означает, что авторизация и квота действуют.
|
||||||
|
|
||||||
|
Встроены адаптеры Claude Code, Codex и Kimi. Другой CLI подключается записью в `config/cli-registry.local.json`: `invoke`, `probe`, `model`, `effort`, `data_classes`, `capabilities`, `cost_tier`, `local`. Ядро поддерживает stdin/аргумент промпта и три механизма вывода. `json_schema_inline` совместим с протоколом Claude, `json_schema_file` с Codex; `json_in_prompt` подходит CLI с обычным текстовым ответом. Флаги конкретного CLI нужно проверить по его документации. Само наличие программы не даёт ей разрешение читать память. Неизвестные найденные инструменты отображаются как требующие адаптера.
|
||||||
|
|
||||||
|
При неуспешном вызове распознаются quota и rate limit. CLI получает общую для процессов паузу: по умолчанию 5 часов для квоты, 60 секунд для rate limit. Это защитный интервал, не подтверждённое время сброса подписки. Состояние в `~/.mnemazine/cli-cooldowns`, путь меняет `MNEMAZINE_CLI_COOLDOWNS`. После истечения паузы CLI снова пробуется. Успешный текст со словом «лимит» не считается ошибкой.
|
||||||
|
|
||||||
|
Следующий исполнитель должен иметь допуск к классу данных и все требуемые возможности. Веб-исследование не переключается на CLI без web_search. Запрет отправки персональных данных не снимается ради обхода лимита. Первичный провайдер проходит тот же контроль, что и резервные. Если подходящих CLI нет, вызов завершается явной ошибкой.
|
||||||
|
|
||||||
|
Общий бюджет цепочки по умолчанию 7 минут; `MNEMAZINE_LLM_CHAIN_TIMEOUT_MS` или `opts.totalTimeoutMs` меняет его в пределах 30 минут. `MNEMAZINE_LLM_FALLBACK=0` отключает резервную цепочку. `opts.provider_used` содержит фактического исполнителя, `opts.attempts` категории попыток без содержимого документов и stderr. Модель и effort в реестре не подтверждают фактическую модель процесса: запускаемые флаги задаёт invoke/адаптер, это отдельная граница конфигурации.
|
||||||
|
|
||||||
|
Проверки: `node scripts/mnemazine-cli-discover.mjs`, `node tests/test-cli-failover.mjs`. Тесты используют имитации CLI, без платных вызовов.
|
||||||
|
|
||||||
|
## Завершение обработки
|
||||||
|
|
||||||
|
Финальная проверка pipeline теперь предшествует архивированию копии источника. Ошибка проверки оставляет её во входящих задания. Общий baseline качества читается из канонического состояния репозитория и проверяется на принадлежность vault; изолированное состояние задания не заменяет baseline. Ранее неудачные задания автоматически не переигрываются.
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# Локальные задания Мнемозины
|
||||||
|
|
||||||
|
Один CLI обслуживает приложение macOS и адаптер Олимпуса. Node.js, без сервера и новых пакетов.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node scripts/mnemazine-jobs.mjs submit --kind search --query "память агентов"
|
||||||
|
node scripts/mnemazine-jobs.mjs submit --kind brief --query "память агентов" --mode deep
|
||||||
|
node scripts/mnemazine-jobs.mjs submit --kind ingest --file /absolute/document.pdf --mode deep
|
||||||
|
node scripts/mnemazine-jobs.mjs submit --kind ingest --text "https://www.youtube.com/watch?v=VIDEO_ID" --mode deep
|
||||||
|
node scripts/mnemazine-jobs.mjs submit --kind ingest --text "Название книги или тема" --mode deep
|
||||||
|
node scripts/mnemazine-jobs.mjs list
|
||||||
|
node scripts/mnemazine-jobs.mjs status --id UUID
|
||||||
|
node scripts/mnemazine-jobs.mjs cancel --id UUID
|
||||||
|
node scripts/mnemazine-jobs.mjs retry --id UUID
|
||||||
|
```
|
||||||
|
|
||||||
|
Каждая команда пишет один JSON в stdout. Ошибка: stderr и ненулевой exit code. `submit/status/cancel/retry` возвращают `{job}`, `list` — `{jobs}`. Поля задания: `id`, `kind`, `status`, `query`, `mode`, `project`, `provenance`, `files`, `created_at`, `updated_at`, `attempts`, `events`, `result`, `error`. Необязательные поля могут отсутствовать. Результат содержит `text` и `report_path`.
|
||||||
|
|
||||||
|
Статусы: `queued`, `running`, `completed`, `failed`, `cancelled`. Отмена выполняющегося задания сначала выставляет `cancel_requested`; окончательное `cancelled` появляется после остановки дочернего процесса. Повтор доступен для `failed/cancelled`; история попыток сохраняется. Отмена не откатывает уже записанные знания.
|
||||||
|
|
||||||
|
Ошибка обработки включает причину из состояния pipeline и путь к логу. Если текст извлечён, но после очистки короче 80 символов, приложение сообщает длину и просит добавить контекст. Этот отказ не означает, что файл не был прочитан; порог качества не ослабляется.
|
||||||
|
|
||||||
|
По умолчанию `mode=local`. Поиск и локальная справка работают без LLM, даже если окружение включает deep. Обработка файлов требует явного `--mode deep`: используется строгий desktop pipeline с enrichment и проверками перед архивом. Внешние вызовы выполняются через настроенных провайдеров. `--project` — метаданные, **не ACL и не ограничение поиска**. `--provenance` принимает JSON объекта для происхождения задания.
|
||||||
|
|
||||||
|
`--file` повторяемый. Текущий лимит — 512 MiB на файл, проверяется до чтения содержимого. Файл копируется в закрытый каталог задания, хэшируется SHA-256; оригинал остаётся на месте. Повтор той же группы содержимого с теми же project/provenance возвращает активное или завершённое задание с `deduplicated:true`. Новая версия файла — новое задание. Symlink в последнем компоненте входного пути отвергается. Снимки проверяются перед ingest. Pipeline получает отдельные inbox, state, reports, archive, cache/extracted. Существующий настроенный vault наследуется.
|
||||||
|
|
||||||
|
`--text` принимает ссылку http/https или название/тему, до 8 KiB UTF-8. Используется вместо файлов, только для ingest. Внешние пробелы удаляются; пустой ввод, управляющие символы, другие URL-схемы и URL с логином/паролем отвергаются. В задании сохраняются `input_text` и `input_kind` (`url/title`). Точный очищенный ввод и project/provenance определяют dedup.
|
||||||
|
|
||||||
|
Текст сохраняется прямо в `sources/*-research-request.md` как запрос на исследование с буквальным вводом и требованием не выдумывать факты. У такого элемента `files` нет `original`: внешнего временного файла нет. Это использует существующий путь `text-read → synthesize.publicSources/extractUrls → enrichPrompt(WebSearch/WebFetch) → atomize/verify`. Короткое название превращается в содержательный исследовательский запрос, а не в искусственно подтверждённую заметку. Успех зависит от найденных источников и существующих проверок. YouTube принимается как ссылка для исследования; скачивание видео и получение расшифровки по URL не гарантируются текущим pipeline.
|
||||||
|
|
||||||
|
`--root PATH` задаёт каталог очереди. По умолчанию `.mnemazine/state/jobs` внутри репозитория. Всем клиентам нужен один root. Блокировка очереди сериализует её worker. Дополнительная блокировка `.mnemazine-pipeline-lock` внутри канонического vault не допускает одновременной обработки через strict desktop pipeline и прямой `mnemazine-run.mjs`, в том числе из разных очередей. JSON состояния и история событий записываются одним атомарным rename с fsync. Это локальная очередь, не распределённая БД; каталог должен находиться на локальном диске.
|
||||||
|
|
||||||
|
`submit/retry` запускают отделённый worker. `list/status` также запускают его при наличии queued/running, если не передан `--no-start`; это позволяет приложению восстановить очередь после перезапуска компьютера. Worker остаётся ждать новые задания до остановки процесса; приложение может закрыться. Launchd пока не устанавливается. `work` восстанавливает задания умершего worker и повторяет попытку. Семантика at-least-once: если процесс погиб после записи в vault, часть действий может повториться. Снимок оригинала остаётся для разбора. Рабочие логи: `output.log` и `error.log` в каталоге задания.
|
||||||
|
|
||||||
|
Отмена останавливает process group pipeline и зарегистрированные отдельные группы LLM (TERM, затем KILL). Bridge пишет PID и время старта в `process-groups.jsonl`; перед сигналом проверяется идентичность процесса. Тот же журнал используется при восстановлении worker. Произвольные сторонние утилиты, отделившие новую сессию без регистрации, этим механизмом не покрываются. Отмена не гарантирует прекращение уже принятого удалённого запроса или откат vault. После прерывания блокировка vault сохраняется: следующая обработка откажет с кодом 75 до ручной проверки оставшихся процессов. Автоматического захвата старой блокировки нет.
|
||||||
|
|
||||||
|
Если лидер зарегистрированной группы умер, а группа ещё жива, принадлежность процессов после возможного повторного использования PID недоказуема. Очередь не убивает такую группу: задание получает `failed`, `recovery_blocked:true` и видимую ошибку. Worker не запускает следующие задания, retry также отказывает, пока неоднозначная группа существует. После её завершения доступен явный retry. Это безопасный отказ, а не обещание автоматического восстановления любой аварии.
|
||||||
|
|
||||||
|
Для тестов: `submit --no-start`, `retry --no-start`, `work --once`. Проверка: `node tests/test-jobs.mjs` — только временные фикстуры, без обработки живого inbox и без LLM.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Мнемозина в строке меню macOS
|
||||||
|
|
||||||
|
<img src="assets/pantheon/app-icon-mnemazine.png" alt="Иконка Мнемозины: вытянутый золотой граф в стеклянной плашке над мраморным Олимпом на Марсе" width="100%">
|
||||||
|
|
||||||
|
Приложение доступно как предварительная версия из исходников. Оно открывает поиск, добавление материалов и очередь из строки меню. Значок: вытянутый граф связанных узлов. На иконке запуска тот же граф расположен над Олимпом.
|
||||||
|
|
||||||
|
Поисковая капсула и четыре круглые стеклянные кнопки стоят рядом с прозрачными промежутками: «Ссылка», «Файлы», «Буфер», «Настройки». Выбранная кнопка перемещается к началу строки и исчезает из внешнего ряда. Повторное нажатие возвращает поиск. Выбранное действие раскрывается ниже только при необходимости.
|
||||||
|
|
||||||
|
Локальное приложение: очередь задач, добавление файлов, поиск, справки и переход к источникам. Нужны macOS 14+, Node.js и настроенный проект Mnemazine. Для сборки нужен Swift SDK с macOS 26 (Xcode 26 или новее); на macOS 14–15 приложение использует системные материалы.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm run app:build
|
||||||
|
open .mnemazine/tmp/Mnemazine.app
|
||||||
|
```
|
||||||
|
|
||||||
|
Сборка создает локальный `.app` с ad-hoc подписью. Готового нотарифицированного приложения для скачивания и установщика нет. Внутри остаются пути к текущему проекту и Node.js: приложение не содержит самостоятельный backend. При переносе проекта или Node.js обнови пути в настройках.
|
||||||
|
|
||||||
|
Открывай созданный `.app` через Finder или командой выше. Если перенесешь его в папку «Программы», запускай оттуда. Запуск и повторное открытие сразу показывают панель; значок графа в строке меню также открывает ее. После Esc процесс остается запущен, «Выйти» завершает только интерфейс.
|
||||||
|
|
||||||
|
Нажми значок графа в строке меню. В режиме «Файлы» выбери документы (⌘O) или перенеси их в любую часть открытого окна. Появятся имена выбранных файлов. Нажми «Обработать» и подтверди передачу содержимого модели для разбора и веб-обогащения. Сам перенос ничего не отправляет. Исходные файлы сохраняются. Закрытый значок файлы не принимает.
|
||||||
|
|
||||||
|
В режиме «Поиск» введи запрос и нажми Enter. «Сделай справку: тема» создает справку, остальные запросы запускают поиск. Результат открывается отдельным окном.
|
||||||
|
|
||||||
|
Поиск по умолчанию локальный. AI включается в настройках и требует подтверждения перед каждым запросом. Приложение не сохраняет включенный глубокий режим между запусками.
|
||||||
|
|
||||||
|
Настройки раскрываются прямо в панели. Контекстное меню строки (правая кнопка мыши) открывает очередь или выход. Очередь показывает готовность, ошибки, отмену и повтор в отдельном окне. Фоновую обработку выполняет backend проекта, она не зависит от открытой панели.
|
||||||
|
|
||||||
|
В режиме «Ссылка» вставь http/https-адрес, название или короткий текст. Enter и кнопка «Исследовать и добавить» сначала запрашивают подтверждение. Название сохраняется как запрос, не как установленный факт; полный текст страницы и расшифровка видео не гарантируются. Лимит текста 8 КиБ.
|
||||||
|
|
||||||
|
«Буфер» читает текущий текст, ссылку или файлы только по нажатию этой кнопки либо «Прочитать снова». Показывается предпросмотр. Слежения за буфером и истории нет. Кнопка «Добавить в память» требует отдельного подтверждения; длинный текст предложено сохранить в файл.
|
||||||
|
|
||||||
|
В настройках выбери папку проекта и исполняемый файл Node.js, если приложение не нашло его само. Выбор сохраняется в локальных настройках macOS. Настройка моделей и хранилища остается в Mnemazine; отдельной базы у приложения нет.
|
||||||
|
|
||||||
|
Настройки показывают обнаруженные CLI. Встроены адаптеры Claude Code, Codex и Kimi; для другого CLI нужен проверенный адаптер. При ошибке квоты или частоты запросов backend пробует следующего разрешенного исполнителя с нужными возможностями и допуском к данным. Наличие CLI не подтверждает авторизацию или доступную квоту. Если замены нет, задача показывает ошибку. Подробности: [переключение CLI](cli-failover.ru.md).
|
||||||
|
|
||||||
|
Поисковая капсула и круглые кнопки используют нативное стекло без общей подложки. На macOS 26 их объединяет GlassEffectContainer. Стабильные glassEffectID и matchedGeometry переходы связывают перемещение выбранной кнопки.
|
||||||
|
|
||||||
|
При наведении файлов строка превращается в зону «Отпусти файл здесь»; после переноса показывает имя принятого файла. Наведение ничего не читает из буфера и ничего не отправляет.
|
||||||
|
|
||||||
|
Значок использует NSStatusItem, содержимое показывает прозрачная NSPanel. Панель остается открытой при переходе в Finder. Закрыть ее можно по Escape, повторным нажатием значка или переходом к результату либо очереди.
|
||||||
|
|
||||||
|
Выделение текста и подписи VoiceOver сохранены. Окна настроек, очереди и результата используют нативное стекло macOS 26 в режиме regular; на macOS 14–15 предусмотрено размытие. При «Уменьшении прозрачности» поверхности непрозрачные. При «Уменьшении движения» анимации отключены. Проверка поведения настоящими пользователями пока не проведена.
|
||||||
|
|
||||||
|
Проверка без обработки пользовательских файлов:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
swift test --package-path macos
|
||||||
|
```
|
||||||
|
|
||||||
|
Ручная приемка: запуск из Finder, настройка путей, локальный поиск по тестовому vault, перенос тестового файла с явным подтверждением, закрытие и повторный запуск приложения, просмотр результата, отмена и повтор. Отдельно проверь клавиатуру, VoiceOver, светлую/темную тему и уменьшение прозрачности. Пользовательские файлы для smoke-проверки не нужны.
|
||||||
|
|
||||||
|
Проверка общих поверхностей: `WindowSurfaceTests` измеряет реальное покрытие зоны
|
||||||
|
закрытия, safe area содержимого и радиусы до/после resize, а также переключение
|
||||||
|
непрозрачной подложки. Это не заменяет визуальную проверку тем и VoiceOver.
|
||||||
|
|
||||||
|
`SpotlightModeTests` проверяет маршрутизацию режимов, предел текста и чтение буфера
|
||||||
|
только по явному выбору через подставленный источник. Реальный буфер тесты не читают. Видимая ошибка карточки очереди передается
|
||||||
|
как accessibility value. Визуальный прогон темной темы выполнен на macOS 26.5;
|
||||||
|
фактическое голосовое чтение пока не подтверждено, несмотря на проверенный AX-вывод.
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# Мнемозина в Олимпусе: адаптер координатора
|
||||||
|
|
||||||
|
`scripts/mnemazine-olympuz.mjs` принимает исследование бога в ту же очередь, которую использует приложение Мнемозины. Отдельного сервера, базы и доступа богов к vault нет. Координатор вызывает CLI через `execFile` / `Bun.spawn` с массивом аргументов, без shell.
|
||||||
|
|
||||||
|
В существующем Олимпусе `Registry` пока вызывает `forwardResearchRequests` из `src/research-inbox.ts`: старый перенос в inbox продолжает работать. Этот адаптер в Олимпус ещё не подключён. При подключении нужно заменить старый вызов для выбранного запуска, иначе один материал попадёт в оба пути.
|
||||||
|
|
||||||
|
## Передать материал
|
||||||
|
|
||||||
|
Команда координатора (пути ниже служат примером; подставляются из доверенной конфигурации):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node /opt/mnemazine/scripts/mnemazine-olympuz.mjs submit \
|
||||||
|
--root /var/lib/mnemazine/state \
|
||||||
|
--god athena --run run-123 --project example --mode deep \
|
||||||
|
--worktree /srv/olympuz/worktrees/athena-run-123 \
|
||||||
|
--file /srv/olympuz/worktrees/athena-run-123/research/agent-research--example--retrieval.md
|
||||||
|
```
|
||||||
|
|
||||||
|
`--root` должен совпадать с root приложения и worker. Это каталог состояния ядра, не путь vault. Координатор берёт `god`, `run`, `project` и `worktree` из своего Registry; бог не задаёт их через содержимое заявки. CLI не проверяет личность процесса: граница доступа по-прежнему обеспечивается песочницей Олимпуса. Запрещено отдавать богам этот CLI, общий root или произвольный запуск команд на хосте.
|
||||||
|
|
||||||
|
Intake требует явный `--mode deep`, поскольку штатный конвейер использует внешние модели. Координатор выставляет его только в разрешённом владельцем режиме обработки. Без флага заявка отклоняется до чтения файла.
|
||||||
|
|
||||||
|
Принимается один обычный файл из непосредственного `worktree/research/`, имя `agent-research--PROJECT--SLUG.md`, до 256 KiB. Симлинки, hardlink и несовпадающий проект отклоняются. Адаптер читает ограниченный снимок, добавляет стабильный штамп `god/run/project` и передаёт его штатному jobs core. Время приёма хранится в `job.created_at`, исходный файл сохраняется. Повторная доставка того же содержимого с тем же происхождением возвращает существующий `job.id`, если задача ожидает, выполняется или завершена. Для отменённых и упавших задач доступен явный `retry`. Координатор записывает соответствие `(run, source) → job.id` из квитанции.
|
||||||
|
|
||||||
|
Ответ stdout: один JSON `{ "job": { "id": "…", "kind": "ingest", "status": "queued", "provenance": { "client": "olympuz", "god": "athena", "run": "run-123", "project": "example" }, "result": null, "citations": [], "error": null } }`. Есть также `created_at` и `updated_at`. Ошибка: ненулевой exit code и JSON `{"error":"…"}` в stderr.
|
||||||
|
|
||||||
|
## Состояние, отмена, повтор
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node /opt/mnemazine/scripts/mnemazine-olympuz.mjs status \
|
||||||
|
--root /var/lib/mnemazine/state \
|
||||||
|
--god athena --run run-123 --project example --id JOB_ID
|
||||||
|
```
|
||||||
|
|
||||||
|
`cancel` и `retry` вызываются так же. Перед действием адаптер сверяет все поля происхождения задачи. Чужая задача, включая созданную приложением владельца, возвращает `JOB_SCOPE_MISMATCH`. Повтор возвращает актуальный `job.id`: координатор сохраняет его из ответа. `--no-start` оставляет задачу в очереди для тестов или отдельного worker; в обычной работе его не передают.
|
||||||
|
|
||||||
|
В результате завершённого intake возвращается квитанция `result: {"accepted":true}`. Это не признание исследования достоверным: материал проходит действующие проверки конвейера, агентские утверждения остаются предварительными до предусмотренного ревью. Логи обработки и пути личного vault богам не выдаются. `citations: []` явно означает, что квитанция не содержит найденных источников.
|
||||||
|
|
||||||
|
## Поиск и справки
|
||||||
|
|
||||||
|
Команды `search` и `brief` пока отвечают `PROJECT_SCOPE_UNAVAILABLE` до вызова поиска. Поле `--project` в jobs core хранит происхождение; оно не ограничивает доступ к документам. Выдавать общий vault по такому фильтру нельзя.
|
||||||
|
|
||||||
|
Следующее условие подключения поиска: ядро должно проверять разрешённый корпус по доверенной конфигурации координатора и возвращать ссылки только на разрешённые источники. После этого адаптер сможет отдавать справку и citations. До тех пор владелец пользуется поиском приложения; боги получают только явно подготовленный координатором материал.
|
||||||
|
|
||||||
|
## Проверка без личных данных
|
||||||
|
|
||||||
|
```sh
|
||||||
|
node tests/test-olympuz-adapter.mjs
|
||||||
|
```
|
||||||
|
|
||||||
|
Тест создаёт временный общий root и публичный текст, обращается через клиент Олимпуса и прямой jobs CLI, проверяет видимость одной очереди, повторную доставку после смены времени, отмену, повтор, provenance и отказы при чужом запуске или опасном файле. Worker, LLM, сеть и живой vault не запускаются.
|
||||||
+392
-271
File diff suppressed because it is too large
Load Diff
+12530
-3555
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
|||||||
|
.build/
|
||||||
|
.swiftpm/
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0"><dict>
|
||||||
|
<key>CFBundleExecutable</key><string>Mnemazine</string>
|
||||||
|
<key>CFBundleIdentifier</key><string>org.mnemazine.menubar</string>
|
||||||
|
<key>CFBundleName</key><string>Mnemazine</string>
|
||||||
|
<key>CFBundleDisplayName</key><string>Мнемозина</string>
|
||||||
|
<key>CFBundleIconFile</key><string>AppIcon</string>
|
||||||
|
<key>CFBundlePackageType</key><string>APPL</string>
|
||||||
|
<key>CFBundleShortVersionString</key><string>0.1.0</string>
|
||||||
|
<key>CFBundleVersion</key><string>1</string>
|
||||||
|
<key>LSMinimumSystemVersion</key><string>14.0</string>
|
||||||
|
<key>LSUIElement</key><true/>
|
||||||
|
<key>NSHighResolutionCapable</key><true/>
|
||||||
|
</dict></plist>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// swift-tools-version: 5.9
|
||||||
|
import PackageDescription
|
||||||
|
|
||||||
|
let package = Package(
|
||||||
|
name: "Mnemazine", platforms: [.macOS(.v14)],
|
||||||
|
products: [.executable(name: "Mnemazine", targets: ["Mnemazine"])],
|
||||||
|
targets: [.executableTarget(name: "Mnemazine"),
|
||||||
|
.testTarget(name: "MnemazineTests", dependencies: ["Mnemazine"])])
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
struct Job: Decodable, Identifiable, Sendable {
|
||||||
|
let id: String
|
||||||
|
let kind: String
|
||||||
|
let status: String
|
||||||
|
var query: String?
|
||||||
|
var input_text: String?
|
||||||
|
var files: [JobFile]?
|
||||||
|
var result: JobResult?
|
||||||
|
var error: JobError?
|
||||||
|
var created_at: String?
|
||||||
|
var title: String { input_text ?? query ?? files?.map(\.name).joined(separator: ", ") ?? kind }
|
||||||
|
var active: Bool { status == "queued" || status == "running" }
|
||||||
|
var statusLabel: String {
|
||||||
|
["queued": "В очереди", "running": "Обрабатываю", "completed": "Готово",
|
||||||
|
"failed": "Не получилось", "cancelled": "Отменено"][status] ?? status
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct JobFile: Decodable, Sendable {
|
||||||
|
let name: String
|
||||||
|
let original: String?
|
||||||
|
let snapshot: String?
|
||||||
|
}
|
||||||
|
|
||||||
|
struct JobError: Decodable, Sendable {
|
||||||
|
let message: String
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.singleValueContainer()
|
||||||
|
if let text = try? container.decode(String.self) { message = text }
|
||||||
|
else {
|
||||||
|
let fields = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
message = try fields.decodeIfPresent(String.self, forKey: .message) ?? "Ошибка обработки"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
enum CodingKeys: String, CodingKey { case message }
|
||||||
|
}
|
||||||
|
|
||||||
|
struct JobResult: Decodable, Sendable {
|
||||||
|
var text: String?
|
||||||
|
var report_path: String?
|
||||||
|
var sources: [Source]?
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Source: Decodable, Sendable {
|
||||||
|
var title: String?
|
||||||
|
var path: String?
|
||||||
|
var url: String?
|
||||||
|
init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.singleValueContainer()
|
||||||
|
if let string = try? container.decode(String.self) {
|
||||||
|
title = string; path = string.hasPrefix("/") ? string : nil
|
||||||
|
url = string.hasPrefix("https://") || string.hasPrefix("http://") ? string : nil
|
||||||
|
} else {
|
||||||
|
let fields = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
title = try fields.decodeIfPresent(String.self, forKey: .title)
|
||||||
|
path = try fields.decodeIfPresent(String.self, forKey: .path)
|
||||||
|
url = try fields.decodeIfPresent(String.self, forKey: .url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
enum CodingKeys: String, CodingKey { case title, path, url }
|
||||||
|
var target: URL? {
|
||||||
|
if let path, path.hasPrefix("/") {
|
||||||
|
let target = URL(fileURLWithPath: path)
|
||||||
|
guard ["md", "markdown", "txt", "pdf", "docx", "rtf", "csv", "json", "png", "jpg", "jpeg"].contains(target.pathExtension.lowercased()) else { return nil }
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
guard let url, let target = URL(string: url), ["https", "http"].contains(target.scheme) else { return nil }
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Envelope: Decodable, Sendable {
|
||||||
|
var job: Job?
|
||||||
|
var jobs: [Job]?
|
||||||
|
var providers: [CLIProvider]?
|
||||||
|
}
|
||||||
|
|
||||||
|
struct CLIProvider: Decodable, Identifiable, Sendable {
|
||||||
|
let name: String
|
||||||
|
let installed: Bool
|
||||||
|
let supported: Bool
|
||||||
|
var cooldown: CLICooldown?
|
||||||
|
var id: String { name }
|
||||||
|
var status: String {
|
||||||
|
if !installed { return "Не установлен" }
|
||||||
|
if !supported { return "Нужен адаптер" }
|
||||||
|
if let cooldown {
|
||||||
|
return "Лимит до " + Date(timeIntervalSince1970: cooldown.until / 1000).formatted(date: .omitted, time: .shortened)
|
||||||
|
}
|
||||||
|
return "Найден · вход проверится при вызове"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
struct CLICooldown: Decodable, Sendable { let reason: String; let until: Double }
|
||||||
|
|
||||||
|
enum Backend {
|
||||||
|
static func arguments(_ command: String, kind: String? = nil, query: String? = nil,
|
||||||
|
mode: String = "local", files: [URL] = [], id: String? = nil, text: String? = nil) -> [String] {
|
||||||
|
var args = ["scripts/mnemazine-jobs.mjs", command]
|
||||||
|
if let kind { args += ["--kind", kind] }
|
||||||
|
if let query { args += ["--query", query] }
|
||||||
|
if let text { args += ["--text", text] }
|
||||||
|
if command == "submit" { args += ["--mode", mode] }
|
||||||
|
for file in files { args += ["--file", file.path] }
|
||||||
|
if let id { args += ["--id", id] }
|
||||||
|
return args
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process and both pipe readers live off the main actor. Drain stderr in parallel:
|
||||||
|
// a verbose child must never fill its pipe and deadlock the menu.
|
||||||
|
static func run(repository: String, node: String, args: [String]) async throws -> Envelope {
|
||||||
|
try await Task.detached {
|
||||||
|
guard FileManager.default.fileExists(atPath: repository + "/scripts/mnemazine-jobs.mjs") else {
|
||||||
|
throw NSError(domain: "Mnemazine", code: 1, userInfo: [NSLocalizedDescriptionKey: "Выбери папку Mnemazine в настройках."])
|
||||||
|
}
|
||||||
|
guard node.hasPrefix("/"), FileManager.default.isExecutableFile(atPath: node) else {
|
||||||
|
throw NSError(domain: "Mnemazine", code: 2, userInfo: [NSLocalizedDescriptionKey: "Node.js не найден. Выбери исполняемый файл в настройках."])
|
||||||
|
}
|
||||||
|
let process = Process()
|
||||||
|
process.executableURL = URL(fileURLWithPath: node)
|
||||||
|
process.arguments = args
|
||||||
|
process.currentDirectoryURL = URL(fileURLWithPath: repository)
|
||||||
|
var env = ProcessInfo.processInfo.environment
|
||||||
|
env["PATH"] = URL(fileURLWithPath: node).deletingLastPathComponent().path + ":/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:" + (env["PATH"] ?? "")
|
||||||
|
process.environment = env
|
||||||
|
let output = Pipe(), errors = Pipe()
|
||||||
|
process.standardOutput = output; process.standardError = errors
|
||||||
|
process.standardInput = FileHandle.nullDevice
|
||||||
|
try process.run()
|
||||||
|
let timeout = Task.detached {
|
||||||
|
try? await Task.sleep(for: .seconds(30))
|
||||||
|
if !Task.isCancelled, process.isRunning { process.terminate() }
|
||||||
|
}
|
||||||
|
defer { timeout.cancel() }
|
||||||
|
let errorRead = Task.detached { errors.fileHandleForReading.readDataToEndOfFile() }
|
||||||
|
let data = output.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
process.waitUntilExit()
|
||||||
|
let errorData = await errorRead.value
|
||||||
|
guard process.terminationStatus == 0 else {
|
||||||
|
let message = String(data: errorData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
throw NSError(domain: "Mnemazine", code: Int(process.terminationStatus), userInfo: [NSLocalizedDescriptionKey: message?.isEmpty == false ? message! : "Команда завершилась с ошибкой \(process.terminationStatus)"])
|
||||||
|
}
|
||||||
|
return try JSONDecoder().decode(Envelope.self, from: data)
|
||||||
|
}.value
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct ReadablePlate: ViewModifier {
|
||||||
|
var cornerRadius: CGFloat = 12
|
||||||
|
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
if reduceTransparency {
|
||||||
|
content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: cornerRadius))
|
||||||
|
} else {
|
||||||
|
content.background(.regularMaterial, in: RoundedRectangle(cornerRadius: cornerRadius))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ClearGlassPlate: ViewModifier {
|
||||||
|
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
if reduceTransparency {
|
||||||
|
content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: 16))
|
||||||
|
} else if #available(macOS 26.0, *) {
|
||||||
|
content.glassEffect(.clear, in: .rect(cornerRadius: 16))
|
||||||
|
} else {
|
||||||
|
content.background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GlassWindow: ViewModifier {
|
||||||
|
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
content
|
||||||
|
.background {
|
||||||
|
if reduceTransparency { Color(nsColor: .windowBackgroundColor).ignoresSafeArea() }
|
||||||
|
else { WindowGlassSurface().ignoresSafeArea() }
|
||||||
|
}
|
||||||
|
.background(WindowBacking(opaque: reduceTransparency).frame(width: 0, height: 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct WindowGlassSurface: NSViewRepresentable {
|
||||||
|
func makeNSView(context: Context) -> NSView {
|
||||||
|
if #available(macOS 26.0, *) {
|
||||||
|
let glass = NSGlassEffectView()
|
||||||
|
glass.style = .regular
|
||||||
|
glass.cornerRadius = 16
|
||||||
|
return glass
|
||||||
|
}
|
||||||
|
let blur = NSVisualEffectView()
|
||||||
|
blur.material = .hudWindow
|
||||||
|
blur.blendingMode = .behindWindow
|
||||||
|
blur.state = .active
|
||||||
|
blur.wantsLayer = true
|
||||||
|
blur.layer?.cornerRadius = 16
|
||||||
|
blur.layer?.masksToBounds = true
|
||||||
|
return blur
|
||||||
|
}
|
||||||
|
func updateNSView(_ view: NSView, context: Context) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
func configureGlassWindow(_ window: NSWindow, opaque: Bool) {
|
||||||
|
// Extend only the background under native traffic lights; SwiftUI keeps
|
||||||
|
// interactive content within the window's titlebar safe area.
|
||||||
|
window.styleMask.insert(.fullSizeContentView)
|
||||||
|
window.isOpaque = opaque
|
||||||
|
window.backgroundColor = opaque ? .windowBackgroundColor : .clear
|
||||||
|
window.titlebarAppearsTransparent = true
|
||||||
|
window.isReleasedWhenClosed = false
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct WindowBacking: NSViewRepresentable {
|
||||||
|
let opaque: Bool
|
||||||
|
func makeNSView(context: Context) -> Anchor { Anchor(opaque: opaque) }
|
||||||
|
func updateNSView(_ view: Anchor, context: Context) {
|
||||||
|
view.shouldBeOpaque = opaque
|
||||||
|
view.applyBacking()
|
||||||
|
}
|
||||||
|
final class Anchor: NSView {
|
||||||
|
var shouldBeOpaque: Bool
|
||||||
|
init(opaque: Bool) { self.shouldBeOpaque = opaque; super.init(frame: .zero) }
|
||||||
|
required init?(coder: NSCoder) { fatalError("Use init(opaque:)") }
|
||||||
|
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); applyBacking() }
|
||||||
|
func applyBacking() {
|
||||||
|
guard let window else { return }
|
||||||
|
configureGlassWindow(window, opaque: shouldBeOpaque)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct MarkdownBlock: Equatable {
|
||||||
|
enum Kind: Equatable { case paragraph, heading(Int), quote, code, item, divider }
|
||||||
|
var kind: Kind
|
||||||
|
var text: String
|
||||||
|
|
||||||
|
// ponytail: the result format needs prose, lists, quotes and fenced code.
|
||||||
|
// Tables remain selectable text until real reports require a table renderer.
|
||||||
|
static func parse(_ text: String) -> [MarkdownBlock] {
|
||||||
|
var blocks: [MarkdownBlock] = []
|
||||||
|
var paragraph: [String] = [], code: [String] = []
|
||||||
|
var inCode = false
|
||||||
|
func flush() {
|
||||||
|
if !paragraph.isEmpty { blocks.append(.init(kind: .paragraph, text: paragraph.joined(separator: "\n"))); paragraph = [] }
|
||||||
|
}
|
||||||
|
for line in text.components(separatedBy: .newlines) {
|
||||||
|
if line.hasPrefix("```") {
|
||||||
|
flush()
|
||||||
|
if inCode { blocks.append(.init(kind: .code, text: code.joined(separator: "\n"))); code = [] }
|
||||||
|
inCode.toggle(); continue
|
||||||
|
}
|
||||||
|
if inCode { code.append(line); continue }
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty { flush(); continue }
|
||||||
|
let heading = line.prefix { $0 == "#" }.count
|
||||||
|
if (1...6).contains(heading), line.dropFirst(heading).first == " " {
|
||||||
|
flush(); blocks.append(.init(kind: .heading(heading), text: String(line.dropFirst(heading + 1))))
|
||||||
|
} else if trimmed == "---" || trimmed == "***" {
|
||||||
|
flush(); blocks.append(.init(kind: .divider, text: ""))
|
||||||
|
} else if trimmed.hasPrefix("> ") {
|
||||||
|
flush(); blocks.append(.init(kind: .quote, text: String(trimmed.dropFirst(2))))
|
||||||
|
} else if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") {
|
||||||
|
flush(); blocks.append(.init(kind: .item, text: "• " + trimmed.dropFirst(2)))
|
||||||
|
} else if trimmed.range(of: #"^\d+\. "#, options: .regularExpression) != nil {
|
||||||
|
flush(); blocks.append(.init(kind: .item, text: trimmed))
|
||||||
|
} else { paragraph.append(line) }
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
if inCode { blocks.append(.init(kind: .code, text: code.joined(separator: "\n"))) }
|
||||||
|
return blocks
|
||||||
|
}
|
||||||
|
|
||||||
|
static func inline(_ text: String) -> AttributedString {
|
||||||
|
var result = (try? AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(text)
|
||||||
|
// Markdown comes from documents and models. Links may navigate the web;
|
||||||
|
// local documents are opened using the separate vetted source buttons.
|
||||||
|
for run in result.runs {
|
||||||
|
if let link = run.link, !["https", "http"].contains(link.scheme?.lowercased() ?? "") {
|
||||||
|
result[run.range].link = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MarkdownContent: View {
|
||||||
|
let text: String
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 12) {
|
||||||
|
ForEach(Array(MarkdownBlock.parse(text).enumerated()), id: \.offset) { _, block in
|
||||||
|
switch block.kind {
|
||||||
|
case .heading(let level):
|
||||||
|
Text(MarkdownBlock.inline(block.text))
|
||||||
|
.font(level == 1 ? .title : level == 2 ? .title2 : .headline)
|
||||||
|
.fontWeight(.semibold).accessibilityAddTraits(.isHeader)
|
||||||
|
case .code:
|
||||||
|
ScrollView(.horizontal) {
|
||||||
|
Text(block.text).font(.system(.body, design: .monospaced)).padding(12)
|
||||||
|
}.background(.quaternary, in: RoundedRectangle(cornerRadius: 8))
|
||||||
|
case .quote:
|
||||||
|
HStack(alignment: .top, spacing: 12) {
|
||||||
|
RoundedRectangle(cornerRadius: 2).fill(.secondary).frame(width: 3)
|
||||||
|
Text(MarkdownBlock.inline(block.text)).foregroundStyle(.secondary)
|
||||||
|
}.fixedSize(horizontal: false, vertical: true)
|
||||||
|
case .item:
|
||||||
|
Text(MarkdownBlock.inline(block.text)).padding(.leading, 8)
|
||||||
|
case .divider: Divider()
|
||||||
|
case .paragraph: Text(MarkdownBlock.inline(block.text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.environment(\.openURL, OpenURLAction { url in
|
||||||
|
["http", "https"].contains(url.scheme?.lowercased() ?? "") ? .systemAction : .discarded
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,513 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
import UniformTypeIdentifiers
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
final class Store: ObservableObject {
|
||||||
|
@Published var jobs: [Job] = []
|
||||||
|
@Published var error: String?
|
||||||
|
@Published var busy = false
|
||||||
|
@Published var selectedID: String?
|
||||||
|
@Published var pendingFiles: [URL] = []
|
||||||
|
@Published var deep = false
|
||||||
|
var openWindow: ((String) -> Void)?
|
||||||
|
var panelSizeChanged: ((CGSize) -> Void)?
|
||||||
|
@Published var repository: String { didSet { UserDefaults.standard.set(repository, forKey: "repository") } }
|
||||||
|
@Published var node: String { didSet { UserDefaults.standard.set(node, forKey: "node") } }
|
||||||
|
private var refreshing = false
|
||||||
|
init() {
|
||||||
|
repository = UserDefaults.standard.string(forKey: "repository") ?? Bundle.main.object(forInfoDictionaryKey: "MnemazineRepository") as? String ?? ""
|
||||||
|
node = UserDefaults.standard.string(forKey: "node") ?? Bundle.main.object(forInfoDictionaryKey: "MnemazineNode") as? String ?? ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"].first { FileManager.default.isExecutableFile(atPath: $0) } ?? ""
|
||||||
|
}
|
||||||
|
var configured: Bool { !repository.isEmpty && !node.isEmpty }
|
||||||
|
var selected: Job? { jobs.first { $0.id == selectedID } }
|
||||||
|
func refresh() async {
|
||||||
|
guard configured, !refreshing else { return }
|
||||||
|
refreshing = true
|
||||||
|
defer { refreshing = false }
|
||||||
|
do { jobs = try await Backend.run(repository: repository, node: node, args: Backend.arguments("list")).jobs ?? [] }
|
||||||
|
catch { self.error = error.localizedDescription }
|
||||||
|
}
|
||||||
|
func submit(kind: String, query: String? = nil, mode: String = "local", files: [URL] = [], text: String? = nil) async {
|
||||||
|
guard !busy else { return }
|
||||||
|
busy = true; error = nil
|
||||||
|
defer { busy = false }
|
||||||
|
do {
|
||||||
|
let result = try await Backend.run(repository: repository, node: node, args: Backend.arguments("submit", kind: kind, query: query, mode: mode, files: files, text: text))
|
||||||
|
selectedID = result.job?.id
|
||||||
|
await refresh()
|
||||||
|
} catch { self.error = error.localizedDescription }
|
||||||
|
}
|
||||||
|
func action(_ command: String, id: String) async {
|
||||||
|
do {
|
||||||
|
_ = try await Backend.run(repository: repository, node: node, args: Backend.arguments(command, id: id))
|
||||||
|
await refresh()
|
||||||
|
} catch { self.error = error.localizedDescription }
|
||||||
|
}
|
||||||
|
func chooseFiles() {
|
||||||
|
let panel = NSOpenPanel()
|
||||||
|
panel.allowsMultipleSelection = true; panel.canChooseDirectories = false
|
||||||
|
panel.message = "Файлы попадут в очередь Мнемозины. Оригиналы останутся на месте."
|
||||||
|
panel.begin { response in
|
||||||
|
guard response == .OK else { return }
|
||||||
|
Task { @MainActor in self.pendingFiles = panel.urls }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func chooseRepository() {
|
||||||
|
let panel = NSOpenPanel(); panel.canChooseFiles = false; panel.canChooseDirectories = true
|
||||||
|
panel.message = "Выбери папку проекта Mnemazine"
|
||||||
|
panel.begin { response in
|
||||||
|
guard response == .OK, let url = panel.url else { return }
|
||||||
|
Task { @MainActor in self.repository = url.path; await self.refresh() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func chooseNode() {
|
||||||
|
let panel = NSOpenPanel(); panel.message = "Выбери исполняемый файл node"
|
||||||
|
panel.begin { response in
|
||||||
|
guard response == .OK, let url = panel.url else { return }
|
||||||
|
Task { @MainActor in self.node = url.path; await self.refresh() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@main
|
||||||
|
struct MnemazineApp: App {
|
||||||
|
@NSApplicationDelegateAdaptor(StatusAppDelegate.self) private var delegate
|
||||||
|
var body: some Scene {
|
||||||
|
Settings { EmptyView() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GlassPlate: ViewModifier {
|
||||||
|
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
if reduceTransparency { content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: 16)) }
|
||||||
|
else {
|
||||||
|
if #available(macOS 26.0, *) {
|
||||||
|
content.background(.thinMaterial, in: RoundedRectangle(cornerRadius: 16))
|
||||||
|
.glassEffect(.regular, in: .rect(cornerRadius: 16))
|
||||||
|
} else { content.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16)) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func fileActionAccessibilityLabel(configured: Bool, pendingCount: Int) -> String {
|
||||||
|
if !configured { return "Открыть настройки Мнемозины" }
|
||||||
|
if pendingCount > 0 { return "Обработать файлы: \(pendingCount)" }
|
||||||
|
return "Добавить файлы: перенеси сюда или нажми для выбора"
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MenuPanel: View {
|
||||||
|
@EnvironmentObject var store: Store
|
||||||
|
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||||
|
@State private var input = ""
|
||||||
|
@State private var mode: SpotlightMode = .search
|
||||||
|
@State private var clipboard = ClipboardPreview()
|
||||||
|
@State private var confirmedRequest: SpotlightRequest?
|
||||||
|
@State private var confirmedFiles: [URL] = []
|
||||||
|
@State private var confirmExternal = false
|
||||||
|
@State private var targeted = false
|
||||||
|
@State private var validation: String?
|
||||||
|
@State private var panel = MenuPanelWindow()
|
||||||
|
@FocusState private var inputFocused: Bool
|
||||||
|
@Namespace private var glassNamespace
|
||||||
|
var body: some View {
|
||||||
|
VStack(spacing: 0) {
|
||||||
|
glassHeader
|
||||||
|
if mode != .search || validation != nil {
|
||||||
|
VStack(alignment: .leading, spacing: 14) {
|
||||||
|
if let validation {
|
||||||
|
Text(validation).font(.callout).foregroundStyle(.red).textSelection(.enabled)
|
||||||
|
}
|
||||||
|
expansion
|
||||||
|
}.padding(18).frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.modifier(ReadablePlate(cornerRadius: 20)).padding(.top, 12)
|
||||||
|
.transition(.opacity)
|
||||||
|
}
|
||||||
|
}.frame(width: min(620, (NSScreen.main?.visibleFrame.width ?? 672) - 52))
|
||||||
|
.padding(10)
|
||||||
|
.animation(reduceMotion ? nil : .spring(response: 0.32, dampingFraction: 0.86), value: targeted)
|
||||||
|
.animation(reduceMotion ? nil : .spring(response: 0.32, dampingFraction: 0.86), value: mode)
|
||||||
|
.background(GeometryReader { proxy in
|
||||||
|
Color.clear.preference(key: SpotlightSizeKey.self, value: proxy.size)
|
||||||
|
})
|
||||||
|
.onPreferenceChange(SpotlightSizeKey.self) { size in
|
||||||
|
guard size.width > 0, size.height > 0 else { return }
|
||||||
|
store.panelSizeChanged?(size)
|
||||||
|
}
|
||||||
|
.background(MenuPanelAnchor(panel: panel).frame(width: 0, height: 0))
|
||||||
|
.onAppear { DispatchQueue.main.async { panel.window?.makeKey(); inputFocused = true } }
|
||||||
|
.onExitCommand { panel.window?.close() }
|
||||||
|
.task { await store.refresh() }
|
||||||
|
.dropDestination(for: URL.self) { urls, _ in
|
||||||
|
guard !store.busy, !urls.isEmpty, urls.allSatisfy(\.isFileURL) else { return false }
|
||||||
|
store.pendingFiles = urls; mode = .files; validation = nil
|
||||||
|
return true
|
||||||
|
} isTargeted: { targeted = $0 }
|
||||||
|
.onChange(of: store.pendingFiles) { _, files in
|
||||||
|
if !files.isEmpty { mode = .files; validation = nil }
|
||||||
|
}
|
||||||
|
.alert("Передать данные для обработки?", isPresented: $confirmExternal) {
|
||||||
|
Button("Отмена", role: .cancel) {}
|
||||||
|
Button("Отправить и обработать") { sendConfirmed() }
|
||||||
|
} message: {
|
||||||
|
Text(confirmedRequest?.kind == "ingest" || !confirmedFiles.isEmpty
|
||||||
|
? "Содержимое будет передано настроенной модели для исследования с вебом. Оригиналы файлов сохранятся. Полный текст страницы и расшифровка видео не гарантируются."
|
||||||
|
: "Провайдер получит запрос и найденные фрагменты памяти.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@ViewBuilder private var glassHeader: some View {
|
||||||
|
if #available(macOS 26.0, *) {
|
||||||
|
GlassEffectContainer(spacing: 6) { headerRow }
|
||||||
|
} else { headerRow }
|
||||||
|
}
|
||||||
|
private var headerRow: some View {
|
||||||
|
HStack(spacing: 8) {
|
||||||
|
HStack(spacing: 12) {
|
||||||
|
if targeted {
|
||||||
|
Image(systemName: "doc.badge.plus").font(.system(size: 28, weight: .light))
|
||||||
|
VStack(alignment: .leading, spacing: 3) {
|
||||||
|
Text("Отпусти файл здесь").font(.system(size: 24))
|
||||||
|
Text("Сначала покажу выбранное").font(.caption).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
} else {
|
||||||
|
if mode == .search {
|
||||||
|
Button { select(.search) } label: {
|
||||||
|
Image(systemName: "magnifyingglass").font(.system(size: 24))
|
||||||
|
.foregroundStyle(.secondary)
|
||||||
|
}.buttonStyle(.plain).help("Поиск").accessibilityLabel("Поиск")
|
||||||
|
} else { modeCircle(mode, selected: true) }
|
||||||
|
if case .received(let summary) = SpotlightHeaderContent.resolve(targeted: false, mode: mode, files: store.pendingFiles.map(\.lastPathComponent)) {
|
||||||
|
Text(summary).font(.system(size: 20)).lineLimit(1)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
.accessibilityLabel("Получены файлы: " + summary)
|
||||||
|
} else {
|
||||||
|
TextField(mode.placeholder, text: $input).textFieldStyle(.plain)
|
||||||
|
.font(.system(size: 26)).focused($inputFocused).onSubmit { performAction() }
|
||||||
|
.disabled(mode == .files || mode == .settings).accessibilityLabel(mode.placeholder)
|
||||||
|
}
|
||||||
|
if store.busy { ProgressView().controlSize(.small) }
|
||||||
|
}
|
||||||
|
}.padding(.leading, mode == .search || targeted ? 22 : 11).padding(.trailing, 20)
|
||||||
|
.frame(maxWidth: .infinity).frame(height: 64)
|
||||||
|
.modifier(SpotlightCapsule(id: "search", namespace: glassNamespace))
|
||||||
|
if !targeted {
|
||||||
|
ForEach(SpotlightGlassLayout.externalModes(selected: mode), id: \.self) { option in
|
||||||
|
modeCircle(option, selected: false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.contextMenu {
|
||||||
|
Button("Очередь и результаты") { show("queue") }
|
||||||
|
Button("Выйти") { NSApp.terminate(nil) }.keyboardShortcut("q")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private func modeCircle(_ option: SpotlightMode, selected: Bool) -> some View {
|
||||||
|
Button { select(selected ? .search : option) } label: {
|
||||||
|
Image(systemName: option.symbol).font(.system(size: 17))
|
||||||
|
.frame(width: 42, height: 42).contentShape(Circle())
|
||||||
|
}.buttonStyle(.plain)
|
||||||
|
.modifier(SpotlightCapsule(id: "mode-" + option.rawValue, namespace: glassNamespace, circle: true))
|
||||||
|
.help(selected ? "Вернуться к поиску" : option.rawValue)
|
||||||
|
.accessibilityLabel(selected ? option.rawValue + ", вернуться к поиску" : option.rawValue)
|
||||||
|
.accessibilityAddTraits(selected ? .isSelected : [])
|
||||||
|
}
|
||||||
|
@ViewBuilder private var expansion: some View {
|
||||||
|
switch mode {
|
||||||
|
case .search: EmptyView()
|
||||||
|
case .link:
|
||||||
|
Text("Добавь ссылку, название или короткий текст в строку сверху.").font(.callout).foregroundStyle(.secondary)
|
||||||
|
Text("Модель исследует тему с вебом. Получение полного текста страницы или видео не гарантируется.")
|
||||||
|
.font(.caption).foregroundStyle(.secondary)
|
||||||
|
Button("Исследовать и добавить") { performAction() }.buttonStyle(.borderedProminent).disabled(store.busy || input.isEmpty)
|
||||||
|
case .files:
|
||||||
|
filePreview
|
||||||
|
case .clipboard:
|
||||||
|
if !clipboard.files.isEmpty {
|
||||||
|
Text("Файлы из буфера").font(.headline)
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
ForEach(clipboard.files, id: \.self) { file in
|
||||||
|
Label(file.lastPathComponent, systemImage: "doc").lineLimit(1)
|
||||||
|
}
|
||||||
|
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}.frame(maxHeight: 115)
|
||||||
|
} else if !clipboard.text.isEmpty {
|
||||||
|
Text("Прочитано по нажатию «Буфер»").font(.caption).foregroundStyle(.secondary)
|
||||||
|
ScrollView { Text(clipboard.text).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading) }.frame(maxHeight: 100)
|
||||||
|
} else { Text("В буфере нет текста или файлов.").foregroundStyle(.secondary) }
|
||||||
|
HStack {
|
||||||
|
Button("Прочитать снова") { select(.clipboard) }
|
||||||
|
Spacer()
|
||||||
|
Button("Добавить в память") { performAction() }.buttonStyle(.borderedProminent)
|
||||||
|
.disabled(store.busy || (clipboard.files.isEmpty && input.isEmpty))
|
||||||
|
}
|
||||||
|
case .settings:
|
||||||
|
SettingsView(embedded: true).frame(height: 390)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private var filePreview: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 12) {
|
||||||
|
if store.pendingFiles.isEmpty {
|
||||||
|
Label("Перенеси файлы в это окно", systemImage: "tray.and.arrow.down").font(.headline)
|
||||||
|
} else {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 8) {
|
||||||
|
ForEach(store.pendingFiles, id: \.self) { file in
|
||||||
|
Label(file.lastPathComponent, systemImage: "doc").lineLimit(1).help(file.path)
|
||||||
|
}
|
||||||
|
}.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}.frame(maxHeight: 115)
|
||||||
|
Text("Оригиналы останутся на месте.").font(.caption).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
HStack {
|
||||||
|
Button("Выбрать файлы…") { store.chooseFiles() }.keyboardShortcut("o")
|
||||||
|
if !store.pendingFiles.isEmpty {
|
||||||
|
Button("Убрать") { store.pendingFiles = [] }
|
||||||
|
Spacer()
|
||||||
|
Button("Обработать") { performAction() }.buttonStyle(.borderedProminent).disabled(store.busy)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private func select(_ option: SpotlightMode) {
|
||||||
|
mode = option; validation = nil
|
||||||
|
if let preview = ClipboardPreview.onSelection(option, read: {
|
||||||
|
let pasteboard = NSPasteboard.general
|
||||||
|
let urls = pasteboard.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []
|
||||||
|
return ClipboardPreview(text: urls.isEmpty ? pasteboard.string(forType: .string) ?? pasteboard.string(forType: .URL) ?? "" : "", files: urls)
|
||||||
|
}) {
|
||||||
|
clipboard = preview
|
||||||
|
input = preview.text
|
||||||
|
}
|
||||||
|
if option != .files && option != .settings { inputFocused = true }
|
||||||
|
}
|
||||||
|
private func performAction() {
|
||||||
|
guard !store.busy else { return }
|
||||||
|
guard store.configured else { mode = .settings; return }
|
||||||
|
validation = nil
|
||||||
|
let files = mode == .files ? store.pendingFiles : mode == .clipboard ? clipboard.files : []
|
||||||
|
if !files.isEmpty {
|
||||||
|
confirmedFiles = files; confirmedRequest = nil; confirmExternal = true; return
|
||||||
|
}
|
||||||
|
guard let request = SpotlightRequest.resolve(mode: mode, input: input) else {
|
||||||
|
if input.utf8.count > 8192 { validation = "Текст больше 8 КиБ. Сохрани его в файл и добавь через «Файлы»." }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
confirmedFiles = []; confirmedRequest = request
|
||||||
|
if request.kind == "ingest" || store.deep { confirmExternal = true }
|
||||||
|
else { sendConfirmed() }
|
||||||
|
}
|
||||||
|
private func sendConfirmed() {
|
||||||
|
let files = confirmedFiles, request = confirmedRequest
|
||||||
|
let executionMode = !files.isEmpty || request?.kind == "ingest" || store.deep ? "deep" : "local"
|
||||||
|
Task {
|
||||||
|
if !files.isEmpty { await store.submit(kind: "ingest", mode: "deep", files: files) }
|
||||||
|
else if let request { await store.submit(kind: request.kind, query: request.query, mode: executionMode, text: request.text) }
|
||||||
|
else { return }
|
||||||
|
if store.error == nil && !files.isEmpty { store.pendingFiles = [] }
|
||||||
|
show(store.error == nil && files.isEmpty && request?.kind != "ingest" ? "result" : "queue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private func show(_ id: String) { panel.window?.close(); store.openWindow?(id) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct SpotlightSizeKey: PreferenceKey {
|
||||||
|
static var defaultValue: CGSize = .zero
|
||||||
|
static func reduce(value: inout CGSize, nextValue: () -> CGSize) { value = nextValue() }
|
||||||
|
}
|
||||||
|
struct SearchRequest: Equatable {
|
||||||
|
let kind: String
|
||||||
|
let query: String
|
||||||
|
static func parse(_ input: String) -> SearchRequest {
|
||||||
|
let text = input.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
let prefix = "сделай справку"
|
||||||
|
let lower = text.lowercased()
|
||||||
|
if lower == prefix || lower.hasPrefix(prefix + " ") || lower.hasPrefix(prefix + ":") || lower.hasPrefix(prefix + "\n") {
|
||||||
|
let topic = String(text.dropFirst(prefix.count)).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ":")))
|
||||||
|
return .init(kind: "brief", query: topic.isEmpty ? text : topic)
|
||||||
|
}
|
||||||
|
return .init(kind: "search", query: text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct QueueView: View {
|
||||||
|
@EnvironmentObject var store: Store
|
||||||
|
var body: some View {
|
||||||
|
VStack(alignment: .leading, spacing: 16) {
|
||||||
|
HStack {
|
||||||
|
Text("Очередь").font(.title2.weight(.semibold))
|
||||||
|
Spacer()
|
||||||
|
Button { Task { await store.refresh() } } label: { Image(systemName: "arrow.clockwise") }
|
||||||
|
.accessibilityLabel("Обновить очередь")
|
||||||
|
}.padding(12).modifier(ReadablePlate())
|
||||||
|
if let error = store.error {
|
||||||
|
HStack {
|
||||||
|
Text(error).foregroundStyle(.red).textSelection(.enabled)
|
||||||
|
Button("Скрыть") { store.error = nil }
|
||||||
|
}.padding(12).modifier(GlassPlate())
|
||||||
|
}
|
||||||
|
if store.jobs.isEmpty {
|
||||||
|
ContentUnavailableView("Пока нет задач", systemImage: "tray", description: Text("Добавь файлы или задай вопрос через значок в строке меню."))
|
||||||
|
.modifier(ReadablePlate())
|
||||||
|
} else {
|
||||||
|
ScrollView {
|
||||||
|
LazyVStack(alignment: .leading, spacing: 10) {
|
||||||
|
ForEach(Array(store.jobs.sorted { ($0.created_at ?? "") > ($1.created_at ?? "") }.prefix(20))) { job in
|
||||||
|
HStack(spacing: 0) {
|
||||||
|
Button {
|
||||||
|
store.selectedID = job.id; store.openWindow?("result")
|
||||||
|
} label: {
|
||||||
|
VStack(alignment: .leading, spacing: 5) {
|
||||||
|
Text(job.title).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
Text(job.statusLabel).font(.caption).foregroundStyle(.secondary)
|
||||||
|
if let error = job.error { Text(error.message).font(.caption).foregroundStyle(.red).lineLimit(3) }
|
||||||
|
}.padding(14).contentShape(Rectangle())
|
||||||
|
}.buttonStyle(.plain).accessibilityLabel("\(job.title), \(job.statusLabel), открыть")
|
||||||
|
.accessibilityValue(job.error?.message ?? "")
|
||||||
|
if job.active {
|
||||||
|
Button("Отменить") { Task { await store.action("cancel", id: job.id) } }
|
||||||
|
.padding(.trailing, 14)
|
||||||
|
} else if ["failed", "cancelled"].contains(job.status) {
|
||||||
|
Button("Повторить") { Task { await store.action("retry", id: job.id) } }
|
||||||
|
.padding(.trailing, 14)
|
||||||
|
}
|
||||||
|
}.modifier(GlassPlate())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.padding(22).frame(minWidth: 460, minHeight: 320)
|
||||||
|
.modifier(GlassWindow())
|
||||||
|
.task {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
await store.refresh()
|
||||||
|
try? await Task.sleep(for: .seconds(2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@MainActor
|
||||||
|
final class MenuPanelWindow {
|
||||||
|
weak var window: NSWindow?
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MenuPanelAnchor: NSViewRepresentable {
|
||||||
|
let panel: MenuPanelWindow
|
||||||
|
func makeNSView(context: Context) -> NSView { Anchor(panel: panel) }
|
||||||
|
func updateNSView(_ nsView: NSView, context: Context) {}
|
||||||
|
private final class Anchor: NSView {
|
||||||
|
let panel: MenuPanelWindow
|
||||||
|
init(panel: MenuPanelWindow) { self.panel = panel; super.init(frame: .zero) }
|
||||||
|
required init?(coder: NSCoder) { fatalError("Use init(panel:)") }
|
||||||
|
override func viewDidMoveToWindow() {
|
||||||
|
super.viewDidMoveToWindow()
|
||||||
|
panel.window = window
|
||||||
|
window?.isReleasedWhenClosed = false
|
||||||
|
// MenuBarExtra owns a nonactivating NSPanel. Make it key without
|
||||||
|
// activating the whole app so normal typing reaches the search field.
|
||||||
|
if window?.isVisible == true { window?.makeKey() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ResultView: View {
|
||||||
|
@EnvironmentObject var store: Store
|
||||||
|
var body: some View {
|
||||||
|
Group {
|
||||||
|
if let job = store.selected {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 16) {
|
||||||
|
Text(job.title).font(.title2).textSelection(.enabled)
|
||||||
|
Text(job.statusLabel).foregroundStyle(.secondary)
|
||||||
|
if let error = job.error { Text(error.message).foregroundStyle(.red).textSelection(.enabled) }
|
||||||
|
if let text = job.result?.text { MarkdownContent(text: text) }
|
||||||
|
if let report = job.result?.report_path, report.hasPrefix("/") {
|
||||||
|
Button("Открыть справку") { NSWorkspace.shared.open(URL(fileURLWithPath: report)) }
|
||||||
|
}
|
||||||
|
if let sources = job.result?.sources, !sources.isEmpty {
|
||||||
|
Divider(); Text("Источники").font(.headline)
|
||||||
|
ForEach(Array(sources.enumerated()), id: \.offset) { _, source in
|
||||||
|
if let url = source.target {
|
||||||
|
Button(source.title ?? source.path ?? source.url ?? "Источник") { NSWorkspace.shared.open(url) }
|
||||||
|
} else { Text(source.title ?? "Источник без ссылки") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if job.active { ProgressView("Задача продолжается. Окно можно закрыть.") }
|
||||||
|
}.padding(20).modifier(ReadablePlate(cornerRadius: 16)).padding(20)
|
||||||
|
}
|
||||||
|
} else { ContentUnavailableView("Выбери задачу", systemImage: "doc.text.magnifyingglass", description: Text("Открой результат из очереди в строке меню.")).modifier(ReadablePlate()).padding(20) }
|
||||||
|
}.frame(minWidth: 500, minHeight: 350)
|
||||||
|
.modifier(GlassWindow())
|
||||||
|
.task {
|
||||||
|
while !Task.isCancelled {
|
||||||
|
await store.refresh()
|
||||||
|
try? await Task.sleep(for: .seconds(2))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SettingsView: View {
|
||||||
|
var embedded = false
|
||||||
|
@EnvironmentObject var store: Store
|
||||||
|
@State private var providers: [CLIProvider] = []
|
||||||
|
@State private var providerError: String?
|
||||||
|
@ViewBuilder var body: some View {
|
||||||
|
if embedded { settingsContent }
|
||||||
|
else { settingsContent.modifier(GlassWindow()) }
|
||||||
|
}
|
||||||
|
private var settingsContent: some View {
|
||||||
|
ScrollView {
|
||||||
|
VStack(alignment: .leading, spacing: 20) {
|
||||||
|
Text("Настройки").font(.title2.weight(.semibold))
|
||||||
|
LabeledContent("Папка Mnemazine") {
|
||||||
|
VStack(alignment: .leading) {
|
||||||
|
Text(store.repository.isEmpty ? "Не выбрана" : store.repository)
|
||||||
|
.font(.caption).lineLimit(2).truncationMode(.middle)
|
||||||
|
.textSelection(.enabled).help(store.repository)
|
||||||
|
Button("Выбрать папку…") { store.chooseRepository() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LabeledContent("Node.js") {
|
||||||
|
VStack(alignment: .leading) {
|
||||||
|
Text(store.node.isEmpty ? "Не найден" : store.node)
|
||||||
|
.font(.caption).lineLimit(2).truncationMode(.middle)
|
||||||
|
.textSelection(.enabled).help(store.node)
|
||||||
|
Button("Выбрать Node.js…") { store.chooseNode() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Toggle("Глубокий поиск с AI", isOn: $store.deep)
|
||||||
|
VStack(alignment: .leading, spacing: 10) {
|
||||||
|
HStack {
|
||||||
|
Text("Установленные CLI").font(.headline)
|
||||||
|
Spacer()
|
||||||
|
Button("Обновить") { Task { await refreshProviders() } }
|
||||||
|
}
|
||||||
|
ForEach(providers) { provider in
|
||||||
|
HStack {
|
||||||
|
Text(provider.name)
|
||||||
|
Spacer()
|
||||||
|
Text(provider.status).font(.caption).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let providerError { Text(providerError).font(.caption).foregroundStyle(.red) }
|
||||||
|
Text("При лимите используется следующий разрешённый CLI. Неизвестные программы без адаптера не запускаются. Доступность модели и авторизация проверяются при работе.")
|
||||||
|
.font(.caption).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
Text("Перед каждым AI-запросом появится подтверждение передачи запроса и фрагментов памяти. После перезапуска поиск снова локальный.")
|
||||||
|
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||||
|
Text("Обработка файлов использует настроенный pipeline Mnemazine и может обращаться к внешним AI-сервисам. Поиск по умолчанию локальный.")
|
||||||
|
.font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
|
||||||
|
}.padding(20).modifier(ReadablePlate(cornerRadius: 16)).padding(20)
|
||||||
|
}.frame(minWidth: embedded ? 0 : 520, minHeight: embedded ? 0 : 420)
|
||||||
|
.task { await refreshProviders() }
|
||||||
|
}
|
||||||
|
func refreshProviders() async {
|
||||||
|
do {
|
||||||
|
providers = try await Backend.run(repository: store.repository, node: store.node,
|
||||||
|
args: ["scripts/mnemazine-cli-discover.mjs"]).providers ?? []
|
||||||
|
providerError = nil
|
||||||
|
} catch { providerError = error.localizedDescription }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import AppKit
|
||||||
|
|
||||||
|
enum MnemazineMark {
|
||||||
|
static func image() -> NSImage {
|
||||||
|
// Approved option 5: eight nodes and nine bonds, extended horizontally.
|
||||||
|
let image = NSImage(size: NSSize(width: 32, height: 18), flipped: false) { _ in
|
||||||
|
let nodes: [NSPoint] = [.init(x: 3, y: 13), .init(x: 3, y: 5),
|
||||||
|
.init(x: 9, y: 9), .init(x: 17, y: 13),
|
||||||
|
.init(x: 17, y: 5), .init(x: 24, y: 9),
|
||||||
|
.init(x: 29, y: 13), .init(x: 29, y: 5)]
|
||||||
|
NSColor.black.setStroke()
|
||||||
|
let links = NSBezierPath()
|
||||||
|
links.lineWidth = 1
|
||||||
|
links.lineCapStyle = .round
|
||||||
|
for (a, b) in [(0, 2), (1, 2), (2, 3), (2, 4), (3, 4),
|
||||||
|
(3, 6), (4, 5), (5, 6), (5, 7)] {
|
||||||
|
links.move(to: nodes[a]); links.line(to: nodes[b])
|
||||||
|
}
|
||||||
|
links.stroke()
|
||||||
|
NSColor.black.setFill()
|
||||||
|
for node in nodes {
|
||||||
|
let radius: CGFloat = 1.5
|
||||||
|
NSBezierPath(ovalIn: NSRect(x: node.x - radius, y: node.y - radius,
|
||||||
|
width: radius * 2, height: radius * 2)).fill()
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
image.isTemplate = true
|
||||||
|
image.accessibilityDescription = "Мнемозина: граф памяти"
|
||||||
|
return image
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
struct SpotlightCapsule: ViewModifier {
|
||||||
|
let id: String
|
||||||
|
let namespace: Namespace.ID
|
||||||
|
var circle = false
|
||||||
|
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
|
||||||
|
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||||
|
func body(content: Content) -> some View {
|
||||||
|
if reduceTransparency {
|
||||||
|
content.background(Color(nsColor: .windowBackgroundColor), in: RoundedRectangle(cornerRadius: circle ? 21 : 32))
|
||||||
|
} else if #available(macOS 26.0, *) {
|
||||||
|
if circle {
|
||||||
|
content.glassEffect(.regular.interactive(), in: .circle)
|
||||||
|
.glassEffectID(id, in: namespace)
|
||||||
|
.glassEffectTransition(reduceMotion ? .identity : .matchedGeometry)
|
||||||
|
} else {
|
||||||
|
content.glassEffect(.regular, in: .capsule)
|
||||||
|
.glassEffectID(id, in: namespace)
|
||||||
|
.glassEffectTransition(reduceMotion ? .identity : .matchedGeometry)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
content.background(.regularMaterial, in: RoundedRectangle(cornerRadius: circle ? 21 : 32))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
enum SpotlightGlassLayout {
|
||||||
|
static func externalModes(selected: SpotlightMode) -> [SpotlightMode] {
|
||||||
|
[.link, .files, .clipboard, .settings].filter { $0 != selected }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SpotlightHeaderContent: Equatable {
|
||||||
|
case input, drop, received(String)
|
||||||
|
static func resolve(targeted: Bool, mode: SpotlightMode, files: [String]) -> SpotlightHeaderContent {
|
||||||
|
if targeted { return .drop }
|
||||||
|
guard mode == .files, let first = files.first else { return .input }
|
||||||
|
return .received(files.count == 1 ? first : "\(first) и ещё \(files.count - 1)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum SpotlightMode: String, CaseIterable {
|
||||||
|
case search = "Поиск", link = "Ссылка", files = "Файлы", clipboard = "Буфер", settings = "Настройки"
|
||||||
|
var symbol: String {
|
||||||
|
switch self {
|
||||||
|
case .search: return "magnifyingglass"
|
||||||
|
case .link: return "link"
|
||||||
|
case .files: return "folder"
|
||||||
|
case .clipboard: return "doc.on.clipboard"
|
||||||
|
case .settings: return "gearshape"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var placeholder: String {
|
||||||
|
switch self {
|
||||||
|
case .search: return "Поиск в памяти"
|
||||||
|
case .link: return "Ссылка или название"
|
||||||
|
case .files: return "Добавить файлы"
|
||||||
|
case .clipboard: return "Текст из буфера"
|
||||||
|
case .settings: return "Настройки Мнемозины"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct ClipboardPreview: Equatable {
|
||||||
|
var text: String = ""
|
||||||
|
var files: [URL] = []
|
||||||
|
static func onSelection(_ mode: SpotlightMode, read: () -> ClipboardPreview) -> ClipboardPreview? {
|
||||||
|
mode == .clipboard ? read() : nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct SpotlightRequest: Equatable {
|
||||||
|
let kind: String
|
||||||
|
var query: String? = nil
|
||||||
|
var text: String? = nil
|
||||||
|
static func resolve(mode: SpotlightMode, input: String) -> SpotlightRequest? {
|
||||||
|
let input = input.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
guard !input.isEmpty else { return nil }
|
||||||
|
switch mode {
|
||||||
|
case .search:
|
||||||
|
let search = SearchRequest.parse(input)
|
||||||
|
return .init(kind: search.kind, query: search.query)
|
||||||
|
case .link, .clipboard:
|
||||||
|
guard input.utf8.count <= 8192 else { return nil }
|
||||||
|
return .init(kind: "ingest", text: input)
|
||||||
|
case .files, .settings: return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
final class StatusAppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate {
|
||||||
|
private let store = Store()
|
||||||
|
private var statusItem: NSStatusItem?
|
||||||
|
private var panel: SearchPanel?
|
||||||
|
private var windows: [String: NSWindow] = [:]
|
||||||
|
|
||||||
|
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||||
|
NSApp.setActivationPolicy(.accessory)
|
||||||
|
store.openWindow = { [weak self] id in self?.showWindow(id) }
|
||||||
|
store.panelSizeChanged = { [weak self] size in self?.resizePanel(size) }
|
||||||
|
let item = NSStatusBar.system.statusItem(withLength: 40)
|
||||||
|
item.button?.image = MnemazineMark.image()
|
||||||
|
item.button?.image?.isTemplate = true
|
||||||
|
item.button?.target = self
|
||||||
|
item.button?.action = #selector(togglePanel)
|
||||||
|
item.button?.setAccessibilityLabel("Мнемозина")
|
||||||
|
statusItem = item
|
||||||
|
DispatchQueue.main.async { [weak self] in self?.showPanel() }
|
||||||
|
}
|
||||||
|
|
||||||
|
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
|
||||||
|
showPanel()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func togglePanel() {
|
||||||
|
if panel?.isVisible == true { panel?.orderOut(nil); return }
|
||||||
|
showPanel()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func showPanel() {
|
||||||
|
let panel = panel ?? makePanel()
|
||||||
|
let screen = statusItem?.button?.window?.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? .zero
|
||||||
|
let top = screen.maxY - min(140, screen.height * 0.18)
|
||||||
|
let origin = NSPoint(x: screen.midX - panel.frame.width / 2,
|
||||||
|
y: max(screen.minY + 16, top - panel.frame.height))
|
||||||
|
panel.setFrameOrigin(origin)
|
||||||
|
let animate = !panel.isVisible && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
|
||||||
|
panel.alphaValue = animate ? 0 : 1
|
||||||
|
panel.orderFrontRegardless()
|
||||||
|
panel.makeKey()
|
||||||
|
if animate {
|
||||||
|
NSAnimationContext.runAnimationGroup { context in
|
||||||
|
context.duration = 0.18
|
||||||
|
panel.animator().alphaValue = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Task { await store.refresh() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func resizePanel(_ size: CGSize) {
|
||||||
|
guard let panel, size.width.isFinite, size.height.isFinite, size.width > 0, size.height > 0 else { return }
|
||||||
|
let screen = panel.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? .zero
|
||||||
|
let width = min(size.width, max(320, screen.width - 32))
|
||||||
|
let height = min(size.height, max(200, screen.height - 48))
|
||||||
|
guard abs(panel.frame.width - width) > 0.5 || abs(panel.frame.height - height) > 0.5 else { return }
|
||||||
|
let top = panel.frame.maxY
|
||||||
|
panel.setFrame(NSRect(x: min(max(panel.frame.midX - width / 2, screen.minX + 16), screen.maxX - width - 16),
|
||||||
|
y: max(screen.minY + 16, top - height), width: width, height: height), display: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makePanel() -> SearchPanel {
|
||||||
|
let view = NSHostingView(rootView: MenuPanel().environmentObject(store))
|
||||||
|
let panel = SearchPanel(contentRect: NSRect(x: 0, y: 0, width: 640, height: 160),
|
||||||
|
styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||||
|
panel.isOpaque = false
|
||||||
|
panel.backgroundColor = .clear
|
||||||
|
panel.hasShadow = false
|
||||||
|
panel.isReleasedWhenClosed = false
|
||||||
|
panel.hidesOnDeactivate = false
|
||||||
|
// Keep the drop target visible while the user grabs a file in Finder.
|
||||||
|
// Only Escape, the status button, or explicit navigation hides it.
|
||||||
|
panel.level = .statusBar
|
||||||
|
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
|
||||||
|
panel.contentView = view
|
||||||
|
panel.setContentSize(view.fittingSize)
|
||||||
|
self.panel = panel
|
||||||
|
return panel
|
||||||
|
}
|
||||||
|
|
||||||
|
private func showWindow(_ id: String) {
|
||||||
|
panel?.orderOut(nil)
|
||||||
|
if let window = windows[id] {
|
||||||
|
window.makeKeyAndOrderFront(nil); NSApp.activate(ignoringOtherApps: true); return
|
||||||
|
}
|
||||||
|
let content: AnyView
|
||||||
|
let title: String
|
||||||
|
let size: NSSize
|
||||||
|
switch id {
|
||||||
|
case "settings":
|
||||||
|
content = AnyView(SettingsView().environmentObject(store)); title = "Мнемозина · настройки"; size = .init(width: 560, height: 370)
|
||||||
|
case "queue":
|
||||||
|
content = AnyView(QueueView().environmentObject(store)); title = "Мнемозина · очередь"; size = .init(width: 560, height: 460)
|
||||||
|
default:
|
||||||
|
content = AnyView(ResultView().environmentObject(store)); title = "Мнемозина · результат"; size = .init(width: 760, height: 640)
|
||||||
|
}
|
||||||
|
let window = NSWindow(contentRect: NSRect(origin: .zero, size: size),
|
||||||
|
styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
|
||||||
|
window.title = title
|
||||||
|
configureGlassWindow(window, opaque: NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency)
|
||||||
|
window.delegate = self
|
||||||
|
window.contentView = NSHostingView(rootView: content)
|
||||||
|
windows[id] = window
|
||||||
|
window.center()
|
||||||
|
window.makeKeyAndOrderFront(nil)
|
||||||
|
NSApp.activate(ignoringOtherApps: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
func windowWillClose(_ notification: Notification) {
|
||||||
|
guard let window = notification.object as? NSWindow,
|
||||||
|
let id = windows.first(where: { $0.value === window })?.key else { return }
|
||||||
|
window.contentView = nil
|
||||||
|
windows.removeValue(forKey: id)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class SearchPanel: NSPanel {
|
||||||
|
override var canBecomeKey: Bool { true }
|
||||||
|
override var canBecomeMain: Bool { false }
|
||||||
|
override func cancelOperation(_ sender: Any?) { orderOut(nil) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Mnemazine
|
||||||
|
|
||||||
|
final class AccessibilityLabelTests: XCTestCase {
|
||||||
|
func testApprovedGraphMarkIsWideAndAdaptsToMenuAppearance() {
|
||||||
|
let image = MnemazineMark.image()
|
||||||
|
XCTAssertEqual(image.size.width, 32)
|
||||||
|
XCTAssertEqual(image.size.height, 18)
|
||||||
|
XCTAssertTrue(image.isTemplate)
|
||||||
|
XCTAssertEqual(image.accessibilityDescription, "Мнемозина: граф памяти")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testFileActionLabelMatchesActionAndSettingsTakePrecedence() {
|
||||||
|
XCTAssertEqual(fileActionAccessibilityLabel(configured: false, pendingCount: 0),
|
||||||
|
"Открыть настройки Мнемозины")
|
||||||
|
XCTAssertEqual(fileActionAccessibilityLabel(configured: false, pendingCount: 3),
|
||||||
|
"Открыть настройки Мнемозины")
|
||||||
|
XCTAssertEqual(fileActionAccessibilityLabel(configured: true, pendingCount: 0),
|
||||||
|
"Добавить файлы: перенеси сюда или нажми для выбора")
|
||||||
|
XCTAssertEqual(fileActionAccessibilityLabel(configured: true, pendingCount: 3),
|
||||||
|
"Обработать файлы: 3")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Mnemazine
|
||||||
|
|
||||||
|
final class BackendTests: XCTestCase {
|
||||||
|
func testTextIntakeArgumentsAndSnapshotWithoutOriginal() throws {
|
||||||
|
let input = "https://www.youtube.com/watch?v=abc&list=123"
|
||||||
|
XCTAssertEqual(Backend.arguments("submit", kind: "ingest", mode: "deep", text: input),
|
||||||
|
["scripts/mnemazine-jobs.mjs", "submit", "--kind", "ingest", "--text", input, "--mode", "deep"])
|
||||||
|
let data = Data(#"{"job":{"id":"url-job","kind":"ingest","status":"queued","input_text":"Название видео","files":[{"name":"research-request.md","snapshot":"/tmp/source.md"}]}}"#.utf8)
|
||||||
|
let job = try JSONDecoder().decode(Envelope.self, from: data).job!
|
||||||
|
XCTAssertEqual(job.title, "Название видео")
|
||||||
|
XCTAssertNil(job.files?.first?.original)
|
||||||
|
}
|
||||||
|
func testArgumentsKeepUntrustedTextAsSingleArgument() {
|
||||||
|
let query = "строка с пробелом; $(touch /tmp/no)\nещё"
|
||||||
|
XCTAssertEqual(Backend.arguments("submit", kind: "brief", query: query),
|
||||||
|
["scripts/mnemazine-jobs.mjs", "submit", "--kind", "brief", "--query", query, "--mode", "local"])
|
||||||
|
XCTAssertEqual(Backend.arguments("submit", kind: "ingest", mode: "deep", files: [URL(fileURLWithPath: "/tmp/мой файл.pdf")]).suffix(4),
|
||||||
|
["--mode", "deep", "--file", "/tmp/мой файл.pdf"])
|
||||||
|
}
|
||||||
|
func testCompletedAndFailedEnvelopes() throws {
|
||||||
|
let data = Data(#"{"jobs":[{"id":"a","kind":"brief","status":"completed","result":{"text":"ответ","sources":["/tmp/a.md",{"title":"web","url":"https://example.com"}]}},{"id":"b","kind":"ingest","status":"failed","files":[{"name":"файл.pdf","original":"/tmp/файл.pdf","snapshot":"/tmp/job/файл.pdf","sha256":"abc"}],"error":{"message":"отказ","code":3}}]}"#.utf8)
|
||||||
|
let jobs = try JSONDecoder().decode(Envelope.self, from: data).jobs!
|
||||||
|
XCTAssertEqual(jobs[0].result?.sources?.first?.target?.path, "/tmp/a.md")
|
||||||
|
XCTAssertEqual(jobs[1].error?.message, "отказ")
|
||||||
|
XCTAssertFalse(jobs[1].active)
|
||||||
|
XCTAssertEqual(jobs[1].title, "файл.pdf")
|
||||||
|
let unsafe = try JSONDecoder().decode(Source.self, from: Data(#"{"url":"file:///etc/passwd"}"#.utf8))
|
||||||
|
XCTAssertNil(unsafe.target)
|
||||||
|
let executable = try JSONDecoder().decode(Source.self, from: Data(#"{"path":"/tmp/run.command"}"#.utf8))
|
||||||
|
XCTAssertNil(executable.target)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Mnemazine
|
||||||
|
|
||||||
|
final class MarkdownTests: XCTestCase {
|
||||||
|
func testReportBlocksAndUnclosedFence() {
|
||||||
|
let blocks = MarkdownBlock.parse("# Справка\n\nАбзац **жирный**\n\n- пункт\n> цитата\n```swift\nlet x = 1")
|
||||||
|
XCTAssertEqual(blocks.map(\.kind), [.heading(1), .paragraph, .item, .quote, .code])
|
||||||
|
XCTAssertEqual(blocks.last?.text, "let x = 1")
|
||||||
|
}
|
||||||
|
func testUnsafeLinksArePlainText() {
|
||||||
|
let text = MarkdownBlock.inline("[плохой](file:///tmp/run.command) [сайт](https://example.com)")
|
||||||
|
XCTAssertEqual(text.runs.compactMap(\.link), [URL(string: "https://example.com")!])
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import Foundation
|
||||||
|
import XCTest
|
||||||
|
|
||||||
|
final class PanelPersistenceTests: XCTestCase {
|
||||||
|
func testFinderDragDoesNotDismissPanel() throws {
|
||||||
|
// Regression: an outside-click monitor dismissed the target before a
|
||||||
|
// Finder drag could reach it. Guard the presentation boundary itself.
|
||||||
|
let package = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
|
||||||
|
let source = try String(contentsOf: package.appendingPathComponent("Sources/Mnemazine/StatusAppDelegate.swift"), encoding: .utf8)
|
||||||
|
XCTAssertFalse(source.contains("addGlobalMonitorForEvents"))
|
||||||
|
XCTAssertFalse(source.contains("addLocalMonitorForEvents"))
|
||||||
|
XCTAssertTrue(source.contains("panel.hidesOnDeactivate = false"))
|
||||||
|
XCTAssertTrue(source.contains(".nonactivatingPanel"))
|
||||||
|
XCTAssertTrue(source.contains("override func cancelOperation"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Mnemazine
|
||||||
|
|
||||||
|
final class SearchRequestTests: XCTestCase {
|
||||||
|
func testExplicitBriefPrefix() {
|
||||||
|
XCTAssertEqual(SearchRequest.parse(" Сделай справку: про память "), .init(kind: "brief", query: "про память"))
|
||||||
|
XCTAssertEqual(SearchRequest.parse("СДЕЛАЙ СПРАВКУ\nисточники"), .init(kind: "brief", query: "источники"))
|
||||||
|
XCTAssertEqual(SearchRequest.parse("найди информацию"), .init(kind: "search", query: "найди информацию"))
|
||||||
|
XCTAssertEqual(SearchRequest.parse("сделай справкуXYZ"), .init(kind: "search", query: "сделай справкуXYZ"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import XCTest
|
||||||
|
@testable import Mnemazine
|
||||||
|
|
||||||
|
final class SpotlightModeTests: XCTestCase {
|
||||||
|
func testSelectedGlassControlHasOnePosition() {
|
||||||
|
XCTAssertEqual(SpotlightGlassLayout.externalModes(selected: .search), [.link, .files, .clipboard, .settings])
|
||||||
|
for selected in [SpotlightMode.link, .files, .clipboard, .settings] {
|
||||||
|
XCTAssertEqual(SpotlightGlassLayout.externalModes(selected: selected).count, 3)
|
||||||
|
XCTAssertFalse(SpotlightGlassLayout.externalModes(selected: selected).contains(selected))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func testDropPreviewReturnsToReceivedFileWithoutClipboardRead() {
|
||||||
|
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: true, mode: .clipboard, files: []), .drop)
|
||||||
|
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: false, mode: .files, files: ["paper.pdf"]), .received("paper.pdf"))
|
||||||
|
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: false, mode: .files, files: ["a.md", "b.md"]), .received("a.md и ещё 1"))
|
||||||
|
XCTAssertEqual(SpotlightHeaderContent.resolve(targeted: false, mode: .search, files: ["a.md"]), .input)
|
||||||
|
}
|
||||||
|
func testClipboardOnlyReadsOnExplicitSelection() {
|
||||||
|
var reads = 0
|
||||||
|
let read = { reads += 1; return ClipboardPreview(text: "секрет") }
|
||||||
|
for mode in [SpotlightMode.search, .link, .files, .settings] {
|
||||||
|
XCTAssertNil(ClipboardPreview.onSelection(mode, read: read))
|
||||||
|
}
|
||||||
|
XCTAssertEqual(reads, 0)
|
||||||
|
XCTAssertEqual(ClipboardPreview.onSelection(.clipboard, read: read)?.text, "секрет")
|
||||||
|
XCTAssertEqual(reads, 1)
|
||||||
|
}
|
||||||
|
func testExplicitModeDispatch() {
|
||||||
|
XCTAssertEqual(SpotlightRequest.resolve(mode: .search, input: "Сделай справку: память")?.kind, "brief")
|
||||||
|
XCTAssertEqual(SpotlightRequest.resolve(mode: .link, input: "https://example.com"), .init(kind: "ingest", text: "https://example.com"))
|
||||||
|
XCTAssertEqual(SpotlightRequest.resolve(mode: .clipboard, input: "короткий текст")?.kind, "ingest")
|
||||||
|
XCTAssertNil(SpotlightRequest.resolve(mode: .files, input: "не отправлять"))
|
||||||
|
XCTAssertNil(SpotlightRequest.resolve(mode: .settings, input: "не отправлять"))
|
||||||
|
XCTAssertNil(SpotlightRequest.resolve(mode: .clipboard, input: String(repeating: "я", count: 4097)))
|
||||||
|
XCTAssertNotNil(SpotlightRequest.resolve(mode: .clipboard, input: String(repeating: "я", count: 4096)))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
import XCTest
|
||||||
|
@testable import Mnemazine
|
||||||
|
|
||||||
|
final class WindowSurfaceTests: XCTestCase {
|
||||||
|
@MainActor
|
||||||
|
func testGlassCoversNativeTitlebarAndKeepsWindowControlsAfterResize() throws {
|
||||||
|
try XCTSkipIf(NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency,
|
||||||
|
"Glass geometry requires transparency enabled; opaque backing is tested separately.")
|
||||||
|
let window = makeWindow()
|
||||||
|
defer { window.close() }
|
||||||
|
let host = NSHostingView(rootView: VStack {
|
||||||
|
ContentProbe().frame(height: 20)
|
||||||
|
Spacer()
|
||||||
|
}.modifier(GlassWindow()))
|
||||||
|
window.contentView = host
|
||||||
|
|
||||||
|
for size in [NSSize(width: 560, height: 370), NSSize(width: 740, height: 520)] {
|
||||||
|
window.setContentSize(size)
|
||||||
|
host.layoutSubtreeIfNeeded()
|
||||||
|
let surface = try XCTUnwrap(descendants(of: host).first { view in
|
||||||
|
if #available(macOS 26.0, *), view is NSGlassEffectView { return true }
|
||||||
|
return view is NSVisualEffectView
|
||||||
|
})
|
||||||
|
let surfaceRect = surface.convert(surface.bounds, to: nil)
|
||||||
|
let hostRect = host.convert(host.bounds, to: nil)
|
||||||
|
XCTAssertEqual(surfaceRect.minY, hostRect.minY, accuracy: 1)
|
||||||
|
XCTAssertEqual(surfaceRect.maxY, hostRect.maxY, accuracy: 1)
|
||||||
|
XCTAssertEqual(surfaceRect.width, hostRect.width, accuracy: 1)
|
||||||
|
XCTAssertGreaterThan(surfaceRect.maxY, window.contentLayoutRect.maxY)
|
||||||
|
let close = try XCTUnwrap(window.standardWindowButton(.closeButton))
|
||||||
|
XCTAssertTrue(surfaceRect.contains(close.convert(close.bounds, to: nil)))
|
||||||
|
let content = try XCTUnwrap(descendants(of: host).first { $0 is ContentProbe.View })
|
||||||
|
XCTAssertLessThanOrEqual(content.convert(content.bounds, to: nil).maxY,
|
||||||
|
window.contentLayoutRect.maxY + 1, "Content must stay below native window controls")
|
||||||
|
if #available(macOS 26.0, *), let glass = surface as? NSGlassEffectView {
|
||||||
|
XCTAssertEqual(glass.cornerRadius, 16)
|
||||||
|
XCTAssertEqual(glass.style, .regular)
|
||||||
|
} else {
|
||||||
|
XCTAssertEqual(surface.layer?.cornerRadius, 16)
|
||||||
|
XCTAssertEqual(surface.layer?.masksToBounds, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
XCTAssertTrue(window.styleMask.contains([.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView]))
|
||||||
|
XCTAssertTrue(window.isMovable)
|
||||||
|
XCTAssertNotNil(window.standardWindowButton(.miniaturizeButton))
|
||||||
|
XCTAssertNotNil(window.standardWindowButton(.zoomButton))
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
func testReduceTransparencyChangesBackingWithoutRemovingNativeChrome() {
|
||||||
|
let window = makeWindow()
|
||||||
|
defer { window.close() }
|
||||||
|
configureGlassWindow(window, opaque: true)
|
||||||
|
XCTAssertTrue(window.isOpaque)
|
||||||
|
XCTAssertEqual(window.backgroundColor, .windowBackgroundColor)
|
||||||
|
XCTAssertTrue(window.styleMask.contains(.fullSizeContentView))
|
||||||
|
configureGlassWindow(window, opaque: false)
|
||||||
|
XCTAssertFalse(window.isOpaque)
|
||||||
|
XCTAssertEqual(window.backgroundColor, .clear)
|
||||||
|
XCTAssertNotNil(window.standardWindowButton(.closeButton))
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private func makeWindow() -> NSWindow {
|
||||||
|
_ = NSApplication.shared
|
||||||
|
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 560, height: 370),
|
||||||
|
styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
|
||||||
|
configureGlassWindow(window, opaque: false)
|
||||||
|
return window
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
private func descendants(of view: NSView) -> [NSView] {
|
||||||
|
view.subviews.flatMap { [$0] + descendants(of: $0) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct ContentProbe: NSViewRepresentable {
|
||||||
|
final class View: NSView {}
|
||||||
|
func makeNSView(context: Context) -> View { View() }
|
||||||
|
func updateNSView(_ view: View, context: Context) {}
|
||||||
|
}
|
||||||
@@ -9,6 +9,10 @@
|
|||||||
"Mnemazine": "bin/mnemazine"
|
"Mnemazine": "bin/mnemazine"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
"app:build": "bash scripts/build-macos-app.sh",
|
||||||
|
"app:test": "swift test --package-path macos",
|
||||||
|
"jobs": "node scripts/mnemazine-jobs.mjs",
|
||||||
|
"olympuz": "node scripts/mnemazine-olympuz.mjs",
|
||||||
"install:local": "bash install.sh",
|
"install:local": "bash install.sh",
|
||||||
"start": "bash scripts/mnemazine-desktop-protocol.sh",
|
"start": "bash scripts/mnemazine-desktop-protocol.sh",
|
||||||
"desktop": "bash scripts/mnemazine-desktop-protocol.sh",
|
"desktop": "bash scripts/mnemazine-desktop-protocol.sh",
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# Local development bundle, without distribution signing or notarization.
|
||||||
|
project_root="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
build_root="$project_root/.mnemazine/tmp/macos-build"
|
||||||
|
app_root="$project_root/.mnemazine/tmp/Mnemazine.app"
|
||||||
|
swift build --package-path "$project_root/macos" --scratch-path "$build_root" -c release
|
||||||
|
binary_root="$(swift build --package-path "$project_root/macos" --scratch-path "$build_root" -c release --show-bin-path)"
|
||||||
|
mkdir -p "$app_root/Contents/MacOS"
|
||||||
|
mkdir -p "$app_root/Contents/Resources" "$build_root/AppIcon.iconset"
|
||||||
|
icon_source="$project_root/docs/assets/pantheon/app-icon-mnemazine.png"
|
||||||
|
for size in 16 32 128 256 512; do
|
||||||
|
sips -z "$size" "$size" "$icon_source" --out "$build_root/AppIcon.iconset/icon_${size}x${size}.png" >/dev/null
|
||||||
|
retina_size=$((size * 2))
|
||||||
|
sips -z "$retina_size" "$retina_size" "$icon_source" --out "$build_root/AppIcon.iconset/icon_${size}x${size}@2x.png" >/dev/null
|
||||||
|
done
|
||||||
|
iconutil -c icns "$build_root/AppIcon.iconset" -o "$app_root/Contents/Resources/AppIcon.icns"
|
||||||
|
cp "$binary_root/Mnemazine" "$app_root/Contents/MacOS/Mnemazine"
|
||||||
|
cp "$project_root/macos/Info.plist" "$app_root/Contents/Info.plist"
|
||||||
|
/usr/libexec/PlistBuddy -c "Add :MnemazineRepository string $project_root" "$app_root/Contents/Info.plist"
|
||||||
|
if node_binary="$(command -v node)"; then
|
||||||
|
/usr/libexec/PlistBuddy -c "Add :MnemazineNode string $node_binary" "$app_root/Contents/Info.plist"
|
||||||
|
fi
|
||||||
|
codesign --force --sign - "$app_root"
|
||||||
|
printf '%s\n' "$app_root"
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { discoverProviders } from './mnemazine-cli-runtime.mjs'
|
||||||
|
try { console.log(JSON.stringify({ providers: discoverProviders() })) }
|
||||||
|
catch { console.error('Не удалось прочитать реестр CLI или состояние лимитов.'); process.exitCode = 1 }
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
import fs from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { createHash, randomUUID } from 'node:crypto'
|
||||||
|
import { loadRegistry, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
|
||||||
|
|
||||||
|
export function resolveExecutable(binary, { env = process.env, home = os.homedir() } = {}) {
|
||||||
|
if (typeof binary !== 'string' || !binary || binary.includes('\0')) return null
|
||||||
|
const override = env[`MNEMAZINE_${binary.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_BIN`]
|
||||||
|
const executable = file => {
|
||||||
|
try { fs.accessSync(file, fs.constants.X_OK); return fs.statSync(file).isFile() ? path.resolve(file) : null } catch { return null }
|
||||||
|
}
|
||||||
|
const target = override || binary
|
||||||
|
if (target.includes(path.sep)) return executable(path.resolve(target))
|
||||||
|
const dirs = [...(env.PATH || '').split(path.delimiter).filter(Boolean),
|
||||||
|
path.join(home, '.local/bin'), path.join(home, '.npm-global/bin'), path.join(home, '.claude/local'),
|
||||||
|
'/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin']
|
||||||
|
for (const dir of dirs) { const found = executable(path.join(dir, target)); if (found) return found }
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
function cooldownRoot(dir) {
|
||||||
|
return dir || process.env.MNEMAZINE_CLI_COOLDOWNS || path.join(os.homedir(), '.mnemazine', 'cli-cooldowns')
|
||||||
|
}
|
||||||
|
function providerDir(name, dir) {
|
||||||
|
return path.join(cooldownRoot(dir), createHash('sha256').update(name).digest('hex'))
|
||||||
|
}
|
||||||
|
export function readCooldown(name, { dir, now = Date.now() } = {}) {
|
||||||
|
const folder = providerDir(name, dir)
|
||||||
|
let files
|
||||||
|
try { files = fs.readdirSync(folder) } catch (error) { if (error.code === 'ENOENT') return null; throw error }
|
||||||
|
let latest = null
|
||||||
|
for (const file of files.filter(file => file.endsWith('.json'))) {
|
||||||
|
let record
|
||||||
|
try { record = JSON.parse(fs.readFileSync(path.join(folder, file), 'utf8')) }
|
||||||
|
catch (error) { if (error.code === 'ENOENT') continue; throw new Error('CLI cooldown state is unreadable') }
|
||||||
|
if (!['quota', 'rate_limit'].includes(record.reason) || !Number.isFinite(record.until)) throw new Error('Invalid CLI cooldown state')
|
||||||
|
if (record.until > now && (!latest || record.until > latest.until)) latest = record
|
||||||
|
}
|
||||||
|
return latest
|
||||||
|
}
|
||||||
|
export function recordCooldown(name, reason, { dir, now = Date.now(), retryAfterMs } = {}) {
|
||||||
|
if (!['quota', 'rate_limit'].includes(reason)) return null
|
||||||
|
const ttl = Math.min(24 * 3600000, Math.max(1000, Number.isFinite(retryAfterMs) ? retryAfterMs : reason === 'quota' ? 5 * 3600000 : 60000))
|
||||||
|
const folder = providerDir(name, dir)
|
||||||
|
fs.mkdirSync(folder, { recursive: true, mode: 0o700 })
|
||||||
|
const record = { reason, until: now + ttl }
|
||||||
|
// ponytail: immutable per-provider records prevent concurrent shards from
|
||||||
|
// overwriting a longer cooldown; readers take the maximum, no stale lock theft.
|
||||||
|
const file = path.join(folder, `${randomUUID()}.json`), tmp = `${file}.tmp`
|
||||||
|
const fd = fs.openSync(tmp, 'wx', 0o600)
|
||||||
|
try { fs.writeFileSync(fd, JSON.stringify(record)); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
||||||
|
fs.renameSync(tmp, file)
|
||||||
|
const parent = fs.openSync(folder, 'r')
|
||||||
|
try { fs.fsyncSync(parent) } finally { fs.closeSync(parent) }
|
||||||
|
for (const old of fs.readdirSync(folder).filter(value => value.endsWith('.json'))) {
|
||||||
|
try { if (JSON.parse(fs.readFileSync(path.join(folder, old), 'utf8')).until <= now) fs.unlinkSync(path.join(folder, old)) }
|
||||||
|
catch (error) { if (error.code !== 'ENOENT') throw error }
|
||||||
|
}
|
||||||
|
return record
|
||||||
|
}
|
||||||
|
|
||||||
|
export function classifyProcessFailure(result) {
|
||||||
|
if (result.status === 0) return null
|
||||||
|
if (result.status === 124) return 'timeout'
|
||||||
|
const output = `${result.stderr || ''}\n${result.stdout || ''}`
|
||||||
|
if (/insufficient_quota|quota.{0,60}(exceed|exhaust|limit)|(?:exceed|exhaust).{0,60}quota|out of credits|credit balance.{0,40}(low|exhaust)|usage limit.{0,40}(reach|exceed)|hit your.{0,30}limit/i.test(output)) return 'quota'
|
||||||
|
if (/rate.?limit|too many requests|\b429\b/i.test(output)) return 'rate_limit'
|
||||||
|
if (/unauthori[sz]ed|not logged in|authentication required|\b401\b/i.test(output)) return 'auth'
|
||||||
|
return 'process_error'
|
||||||
|
}
|
||||||
|
|
||||||
|
export function discoverProviders({ registry = loadRegistry(), env = process.env, home = os.homedir(), cooldownDir } = {}) {
|
||||||
|
const providers = Object.entries(registry).map(([name, entry]) => {
|
||||||
|
const binary = resolveExecutable(entry.invoke[0], { env, home })
|
||||||
|
return { name, installed: Boolean(binary), supported: Boolean(pickSchemaAdapter(entry)), binary,
|
||||||
|
model: entry.model, cost_tier: entry.cost_tier, data_classes: entry.data_classes,
|
||||||
|
capabilities: entry.capabilities, cooldown: readCooldown(name, { dir: cooldownDir }) }
|
||||||
|
})
|
||||||
|
for (const name of ['gemini', 'qwen', 'opencode', 'aider', 'goose', 'ollama']) {
|
||||||
|
if (registry[name]) continue
|
||||||
|
const binary = resolveExecutable(name, { env, home })
|
||||||
|
if (binary) providers.push({ name, installed: true, supported: false, binary, cooldown: null })
|
||||||
|
}
|
||||||
|
return providers
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
import { promises as fs } from 'node:fs'
|
import { promises as fs } from 'node:fs'
|
||||||
import { existsSync } from 'node:fs'
|
import { existsSync } from 'node:fs'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
import { spawn, spawnSync } from 'node:child_process'
|
import { spawn, spawnSync } from 'node:child_process'
|
||||||
import { resolveVault } from './mnemazine-paths.mjs'
|
import { resolveVault } from './mnemazine-paths.mjs'
|
||||||
|
|
||||||
@@ -20,6 +21,7 @@ function arg(name, fallback = '') {
|
|||||||
const NEEDS_UPDATE_MAX_DAYS = Number(arg('needs-update-max-days', process.env.MNEMAZINE_NEEDS_UPDATE_MAX_DAYS || '1'))
|
const NEEDS_UPDATE_MAX_DAYS = Number(arg('needs-update-max-days', process.env.MNEMAZINE_NEEDS_UPDATE_MAX_DAYS || '1'))
|
||||||
const STRICT_GRAPH = argv.includes('--strict-graph')
|
const STRICT_GRAPH = argv.includes('--strict-graph')
|
||||||
const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
|
const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
|
||||||
|
const BEFORE_ARCHIVE = argv.includes('--before-archive')
|
||||||
// Удаление протухшего маркера графа — только по этому явному флагу.
|
// Удаление протухшего маркера графа — только по этому явному флагу.
|
||||||
// Без него маркер остается на месте и ложится в warnings/failures (план П08).
|
// Без него маркер остается на месте и ложится в warnings/failures (план П08).
|
||||||
const PRUNE_GRAPH_MARKER = argv.includes('--prune-graph-marker')
|
const PRUNE_GRAPH_MARKER = argv.includes('--prune-graph-marker')
|
||||||
@@ -31,6 +33,8 @@ if (argv.includes('--help')) {
|
|||||||
Использование: node scripts/mnemazine-complete-check.mjs [флаги]
|
Использование: node scripts/mnemazine-complete-check.mjs [флаги]
|
||||||
--vault <путь> корпус (иначе MNEMAZINE_VAULT, last-run.vault или repo-local vault)
|
--vault <путь> корпус (иначе MNEMAZINE_VAULT, last-run.vault или repo-local vault)
|
||||||
--require-deep требовать deep-прогон в last-run (или MNEMAZINE_REQUIRE_DEEP=1)
|
--require-deep требовать deep-прогон в last-run (или MNEMAZINE_REQUIRE_DEEP=1)
|
||||||
|
--before-archive проверить pending_archive перед переносом: inbox ещё полон,
|
||||||
|
но coverage и остальные гейты обязательны
|
||||||
--strict-graph маркер needs_update — failure, а не warning
|
--strict-graph маркер needs_update — failure, а не warning
|
||||||
--needs-update-max-days N возраст маркера до failure (по умолчанию 1)
|
--needs-update-max-days N возраст маркера до failure (по умолчанию 1)
|
||||||
--prune-graph-marker удалить протухший маркер graphify-out/needs_update
|
--prune-graph-marker удалить протухший маркер graphify-out/needs_update
|
||||||
@@ -115,7 +119,7 @@ function isGraphSemanticFile(file) {
|
|||||||
function deepFailures(lastRun) {
|
function deepFailures(lastRun) {
|
||||||
const failures = []
|
const failures = []
|
||||||
if (!lastRun) return ['last run state missing']
|
if (!lastRun) return ['last run state missing']
|
||||||
if (!lastRun.ok) failures.push(`last run failed: ${(lastRun.failures || [lastRun.failure || 'unknown']).join('; ')}`)
|
if (!lastRun.ok && !(BEFORE_ARCHIVE && lastRun.phase === 'pending_archive' && lastRun.pre_archive_ready === true)) failures.push(`last run failed: ${(lastRun.failures || [lastRun.failure || 'unknown']).join('; ')}`)
|
||||||
if (lastRun.draft_only) failures.push('last run was draft-only')
|
if (lastRun.draft_only) failures.push('last run was draft-only')
|
||||||
if (!lastRun.deep) failures.push('last run was not deep')
|
if (!lastRun.deep) failures.push('last run was not deep')
|
||||||
if (lastRun.strict_archive_knowledge !== true) failures.push('strict archive knowledge gate was not enabled')
|
if (lastRun.strict_archive_knowledge !== true) failures.push('strict archive knowledge gate was not enabled')
|
||||||
@@ -129,16 +133,26 @@ function deepFailures(lastRun) {
|
|||||||
return failures
|
return failures
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function loadSpecCeiling({ root = ROOT, vault, ceiling = process.env.MNEMAZINE_SPEC_CEILING } = {}) {
|
||||||
|
const file = path.resolve(ceiling || path.join(root, '.mnemazine/state/spec-ceiling.json'))
|
||||||
|
const baseline = await readJson(file)
|
||||||
|
if (!baseline) return { file, error: 'spec ceiling has no baseline yet' }
|
||||||
|
if (typeof baseline.vault !== 'string' || path.resolve(baseline.vault) !== path.resolve(vault)) return { file, error: 'spec ceiling belongs to a different vault' }
|
||||||
|
return { file, error: null }
|
||||||
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const failures = []
|
const failures = []
|
||||||
const warnings = []
|
const warnings = []
|
||||||
const inbox = await activeInboxFiles()
|
const inbox = await activeInboxFiles()
|
||||||
if (inbox.error) failures.push(`inbox unreadable: ${inbox.error}`)
|
if (inbox.error) failures.push(`inbox unreadable: ${inbox.error}`)
|
||||||
const inboxFiles = inbox.files
|
const inboxFiles = inbox.files
|
||||||
if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`)
|
if (inboxFiles.length && !BEFORE_ARCHIVE) failures.push(`inbox not empty: ${inboxFiles.length}`)
|
||||||
|
|
||||||
const lastRunFile = path.join(STATE, 'last-run.json')
|
const lastRunFile = path.join(STATE, 'last-run.json')
|
||||||
const lastRun = await readJson(lastRunFile)
|
const lastRun = await readJson(lastRunFile)
|
||||||
|
if (BEFORE_ARCHIVE && (lastRun?.phase !== 'pending_archive' || lastRun?.pre_archive_ready !== true || lastRun?.archive_pending !== inboxFiles.length)) failures.push('pre-archive state does not match the current inbox')
|
||||||
|
if (!BEFORE_ARCHIVE && lastRun?.phase === 'pending_archive') failures.push('archive has not completed')
|
||||||
const VAULT = resolveVault({ cli: arg('vault'), env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
|
const VAULT = resolveVault({ cli: arg('vault'), env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
|
||||||
const gateEnv = { MNEMAZINE_VAULT: VAULT }
|
const gateEnv = { MNEMAZINE_VAULT: VAULT }
|
||||||
const coverageArgs = ['scripts/mnemazine-coverage-check.mjs', '--vault', VAULT, '--inbox', INBOX, '--json']
|
const coverageArgs = ['scripts/mnemazine-coverage-check.mjs', '--vault', VAULT, '--inbox', INBOX, '--json']
|
||||||
@@ -156,12 +170,13 @@ async function main() {
|
|||||||
|
|
||||||
// Потолок провалов спеки в продовом пути (план П06 шаг 6): гейт --spec виден
|
// Потолок провалов спеки в продовом пути (план П06 шаг 6): гейт --spec виден
|
||||||
// приемке, а не только вручную. Ненулевой код прибора потолка → в failures.
|
// приемке, а не только вручную. Ненулевой код прибора потолка → в failures.
|
||||||
const specCeilingFile = path.join(STATE, 'spec-ceiling.json')
|
const baseline = await loadSpecCeiling({ vault: VAULT })
|
||||||
if (!existsSync(specCeilingFile)) {
|
const specCeilingFile = baseline.file
|
||||||
|
if (baseline.error) {
|
||||||
// Свежая установка: потолок спеки — per-machine runtime (план П16, .mnemazine/state
|
// Свежая установка: потолок спеки — per-machine runtime (план П16, .mnemazine/state
|
||||||
// gitignored), на чистом клоне его нет и сравнивать не с чем. Это «нет данных», а не
|
// gitignored), на чистом клоне его нет и сравнивать не с чем. Это «нет данных», а не
|
||||||
// провал: ratchet без базы — no-op. doctor распознает эту строку как no-data (degraded, не fatal).
|
// провал: ratchet без базы — no-op. doctor распознает эту строку как no-data (degraded, не fatal).
|
||||||
failures.push('spec ceiling has no baseline yet')
|
failures.push(baseline.error)
|
||||||
} else {
|
} else {
|
||||||
const specCeiling = await run(process.execPath, ['scripts/mnemazine-spec-ceiling.mjs', '--check', '--vault', VAULT, '--ceiling', specCeilingFile], gateEnv)
|
const specCeiling = await run(process.execPath, ['scripts/mnemazine-spec-ceiling.mjs', '--check', '--vault', VAULT, '--ceiling', specCeilingFile], gateEnv)
|
||||||
if (!specCeiling.ok) failures.push(`spec ceiling failed: ${specCeiling.stderr || specCeiling.stdout}`)
|
if (!specCeiling.ok) failures.push(`spec ceiling failed: ${specCeiling.stderr || specCeiling.stdout}`)
|
||||||
@@ -238,7 +253,7 @@ async function main() {
|
|||||||
if (!result.ok) process.exit(1)
|
if (!result.ok) process.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch(error => {
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main().catch(error => {
|
||||||
console.error(error.message || error)
|
console.error(error.message || error)
|
||||||
process.exit(1)
|
process.exit(1)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -18,9 +18,14 @@
|
|||||||
// возвращают ровно тот зеленый, что мастер-план §8 запрещает прибору оркестрации.
|
// возвращают ровно тот зеленый, что мастер-план §8 запрещает прибору оркестрации.
|
||||||
// Покрытым считается файл, чей basename встречается в теле или frontmatter хотя бы одной ноты vault —
|
// Покрытым считается файл, чей basename встречается в теле или frontmatter хотя бы одной ноты vault —
|
||||||
// та же семантика, что у сверщика (`source:`/`sources:`), но без права ошибиться в регулярке.
|
// та же семантика, что у сверщика (`source:`/`sources:`), но без права ошибиться в регулярке.
|
||||||
|
// Для переименованных job snapshots дополнительно считается SHA-256 текущего файла:
|
||||||
|
// local-media hash засчитывается только из final verified enriched ноты (strictKnowledgeReady).
|
||||||
import { promises as fs } from 'node:fs'
|
import { promises as fs } from 'node:fs'
|
||||||
|
import { constants } from 'node:fs'
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { resolveVault } from './mnemazine-paths.mjs'
|
import { resolveVault } from './mnemazine-paths.mjs'
|
||||||
|
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
|
||||||
|
|
||||||
const argv = process.argv.slice(2)
|
const argv = process.argv.slice(2)
|
||||||
const arg = (name, fallback = '') => {
|
const arg = (name, fallback = '') => {
|
||||||
@@ -32,16 +37,23 @@ const arg = (name, fallback = '') => {
|
|||||||
/** Ноты vault одним чтением: корпус мал (< 20 МБ), а N грепов по файлу — это N спавнов и гонка. */
|
/** Ноты vault одним чтением: корпус мал (< 20 МБ), а N грепов по файлу — это N спавнов и гонка. */
|
||||||
async function readCorpus(vault) {
|
async function readCorpus(vault) {
|
||||||
const chunks = []
|
const chunks = []
|
||||||
|
const verifiedRefs = new Set()
|
||||||
async function walk(dir) {
|
async function walk(dir) {
|
||||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||||
if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||||
const p = path.join(dir, item.name)
|
const p = path.join(dir, item.name)
|
||||||
if (item.isDirectory()) await walk(p)
|
if (item.isDirectory()) await walk(p)
|
||||||
else if (item.isFile() && p.endsWith('.md')) chunks.push(await fs.readFile(p, 'utf8'))
|
else if (item.isFile() && p.endsWith('.md')) {
|
||||||
|
const text = await fs.readFile(p, 'utf8')
|
||||||
|
chunks.push(text)
|
||||||
|
if (strictKnowledgeReady(text)) {
|
||||||
|
for (const match of text.matchAll(/\blocal-media:([a-f0-9]{64}|[a-f0-9]{16})(?![a-f0-9])/gi)) verifiedRefs.add(match[1].toLowerCase())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
await walk(vault)
|
await walk(vault)
|
||||||
return chunks.join('\n')
|
return { text: chunks.join('\n'), verifiedRefs }
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -92,8 +104,26 @@ if (census.length === 0 && !argv.includes('--allow-empty')) {
|
|||||||
process.exit(2)
|
process.exit(2)
|
||||||
}
|
}
|
||||||
|
|
||||||
const corpus = (await readCorpus(VAULT)).normalize('NFC')
|
const corpus = await readCorpus(VAULT)
|
||||||
const uncovered = census.filter(f => !isCovered(corpus, f))
|
const corpusNfc = corpus.text.normalize('NFC')
|
||||||
|
const uncovered = []
|
||||||
|
for (const file of census) {
|
||||||
|
if (isCovered(corpusNfc, file)) continue
|
||||||
|
let coveredByHash = false
|
||||||
|
if (corpus.verifiedRefs.size) {
|
||||||
|
try {
|
||||||
|
const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
|
||||||
|
const hash = createHash('sha256')
|
||||||
|
try {
|
||||||
|
if (!(await handle.stat()).isFile()) throw new Error('Source is not a regular file')
|
||||||
|
for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk)
|
||||||
|
} finally { await handle.close() }
|
||||||
|
const digest = hash.digest('hex')
|
||||||
|
coveredByHash = corpus.verifiedRefs.has(digest) || corpus.verifiedRefs.has(digest.slice(0, 16))
|
||||||
|
} catch { /* Unreadable sources cannot be proven covered by content. */ }
|
||||||
|
}
|
||||||
|
if (!coveredByHash) uncovered.push(file)
|
||||||
|
}
|
||||||
const report = { ok: uncovered.length === 0, vault: VAULT, census: census.length, covered: census.length - uncovered.length, uncovered }
|
const report = { ok: uncovered.length === 0, vault: VAULT, census: census.length, covered: census.length - uncovered.length, uncovered }
|
||||||
|
|
||||||
if (argv.includes('--json')) console.log(JSON.stringify(report, null, 2))
|
if (argv.includes('--json')) console.log(JSON.stringify(report, null, 2))
|
||||||
|
|||||||
@@ -6,12 +6,28 @@ ENV_INBOX="${MNEMAZINE_INBOX:-}"
|
|||||||
ENV_VAULT="${MNEMAZINE_VAULT:-}"
|
ENV_VAULT="${MNEMAZINE_VAULT:-}"
|
||||||
ENV_DEEP="${MNEMAZINE_DEEP:-}"
|
ENV_DEEP="${MNEMAZINE_DEEP:-}"
|
||||||
ENV_REQUIRE_DEEP="${MNEMAZINE_REQUIRE_DEEP:-}"
|
ENV_REQUIRE_DEEP="${MNEMAZINE_REQUIRE_DEEP:-}"
|
||||||
|
ENV_REPORTS="${MNEMAZINE_REPORTS:-}"
|
||||||
|
ENV_STATE="${MNEMAZINE_STATE:-}"
|
||||||
|
ENV_ARCHIVE="${MNEMAZINE_ARCHIVE:-}"
|
||||||
|
ENV_CACHE="${MNEMAZINE_CACHE:-}"
|
||||||
|
ENV_EXTRACTS="${MNEMAZINE_EXTRACTS:-}"
|
||||||
|
ENV_RUN_ID="${MNEMAZINE_RUN_ID:-}"
|
||||||
|
ENV_JOB_GROUPS="${MNEMAZINE_JOB_GROUPS:-}"
|
||||||
DRY_RUN=0
|
DRY_RUN=0
|
||||||
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1
|
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1
|
||||||
|
|
||||||
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
|
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
|
||||||
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
|
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
|
||||||
|
|
||||||
|
# Explicit job paths must survive trusted owner configuration loading.
|
||||||
|
[ -z "$ENV_REPORTS" ] || export MNEMAZINE_REPORTS="$ENV_REPORTS"
|
||||||
|
[ -z "$ENV_STATE" ] || export MNEMAZINE_STATE="$ENV_STATE"
|
||||||
|
[ -z "$ENV_ARCHIVE" ] || export MNEMAZINE_ARCHIVE="$ENV_ARCHIVE"
|
||||||
|
[ -z "$ENV_CACHE" ] || export MNEMAZINE_CACHE="$ENV_CACHE"
|
||||||
|
[ -z "$ENV_EXTRACTS" ] || export MNEMAZINE_EXTRACTS="$ENV_EXTRACTS"
|
||||||
|
[ -z "$ENV_RUN_ID" ] || export MNEMAZINE_RUN_ID="$ENV_RUN_ID"
|
||||||
|
[ -z "$ENV_JOB_GROUPS" ] || export MNEMAZINE_JOB_GROUPS="$ENV_JOB_GROUPS"
|
||||||
|
|
||||||
CONFIG_VAULT=""
|
CONFIG_VAULT=""
|
||||||
if [ -f "$REPO/.mnemazine/config.json" ] && command -v node >/dev/null 2>&1; then
|
if [ -f "$REPO/.mnemazine/config.json" ] && command -v node >/dev/null 2>&1; then
|
||||||
CONFIG_VAULT="$(node -e 'const fs=require("fs"); const cfg=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); process.stdout.write(typeof cfg.vault==="string" ? cfg.vault : "")' "$REPO/.mnemazine/config.json" 2>/dev/null || true)"
|
CONFIG_VAULT="$(node -e 'const fs=require("fs"); const cfg=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); process.stdout.write(typeof cfg.vault==="string" ? cfg.vault : "")' "$REPO/.mnemazine/config.json" 2>/dev/null || true)"
|
||||||
@@ -73,6 +89,16 @@ if [ "$DRY_RUN" = "1" ]; then
|
|||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Hold one canonical-vault lock across run AND complete. Child runs verify
|
||||||
|
# inherited ownership (nonce, process start and ancestry) before reentering.
|
||||||
|
if [ "${MNEMAZINE_DRAFT_ONLY:-0}" = "1" ]; then
|
||||||
|
echo "strict protocol vs draft-only: MNEMAZINE_REQUIRE_DEEP=1 и MNEMAZINE_DRAFT_ONLY=1 несовместимы" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
if ! node "$REPO/scripts/mnemazine-vault-lock.mjs" --check "$MNEMAZINE_VAULT"; then
|
||||||
|
exec node "$REPO/scripts/mnemazine-vault-lock.mjs" --vault "$MNEMAZINE_VAULT" -- bash "${BASH_SOURCE[0]}" "$@"
|
||||||
|
fi
|
||||||
|
|
||||||
ran=0
|
ran=0
|
||||||
|
|
||||||
run_inbox "$BASE_INBOX"
|
run_inbox "$BASE_INBOX"
|
||||||
|
|||||||
@@ -0,0 +1,362 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// ponytail: one local queue/worker; all clients must use the same root.
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { randomUUID, createHash } from 'node:crypto'
|
||||||
|
import { spawn, spawnSync } from 'node:child_process'
|
||||||
|
import { parseArgs } from 'node:util'
|
||||||
|
|
||||||
|
const script = fileURLToPath(import.meta.url)
|
||||||
|
const repo = path.resolve(path.dirname(script), '..')
|
||||||
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
|
||||||
|
const now = () => new Date().toISOString()
|
||||||
|
const alive = pid => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
|
||||||
|
function syncDir(directory) {
|
||||||
|
const fd = fs.openSync(directory, 'r')
|
||||||
|
try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
||||||
|
}
|
||||||
|
function atomic(file, value) {
|
||||||
|
const tmp = `${file}.${randomUUID()}.tmp`
|
||||||
|
const fd = fs.openSync(tmp, 'wx', 0o600)
|
||||||
|
try { fs.writeFileSync(fd, JSON.stringify(value)); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
||||||
|
fs.renameSync(tmp, file)
|
||||||
|
syncDir(path.dirname(file))
|
||||||
|
}
|
||||||
|
function identity(pid) {
|
||||||
|
return spawnSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout?.trim() || ''
|
||||||
|
}
|
||||||
|
function sameProcess(owner) { return owner?.pid > 0 && alive(owner.pid) && identity(owner.pid) === owner.started }
|
||||||
|
function ownedGroup(owner) {
|
||||||
|
if (!Number.isSafeInteger(owner?.pid) || owner.pid <= 1 || !owner.started) return false
|
||||||
|
const result = spawnSync('ps', ['-axo', 'pid=,pgid=,lstart='], { encoding: 'utf8' })
|
||||||
|
if (result.status !== 0) throw new Error('Cannot inspect process groups safely')
|
||||||
|
const members = result.stdout.split('\n').map(line => line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/))
|
||||||
|
.filter(match => match && Number(match[2]) === owner.pid)
|
||||||
|
.map(match => ({ pid: Number(match[1]), started: match[3].trim() }))
|
||||||
|
if (!members.length) return false
|
||||||
|
const leader = members.find(member => member.pid === owner.pid)
|
||||||
|
if (leader) return leader.started === owner.started
|
||||||
|
// A dead leader cannot prove group ownership across PID reuse after a crash.
|
||||||
|
throw new Error(`Ambiguous live process group ${owner.pid}: leader exited; queue paused until the group exits`)
|
||||||
|
}
|
||||||
|
async function lock(file, wait = true) {
|
||||||
|
for (let i = 0; i < (wait ? 600 : 1); i++) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(file, { mode: 0o700 })
|
||||||
|
atomic(path.join(file, 'owner.json'), { pid: process.pid, started: identity(process.pid) })
|
||||||
|
return () => fs.rmSync(file, { recursive: true, force: true })
|
||||||
|
} catch (e) {
|
||||||
|
if (e.code !== 'EEXIST') throw e
|
||||||
|
let owner
|
||||||
|
try { owner = JSON.parse(fs.readFileSync(path.join(file, 'owner.json'), 'utf8')) } catch {}
|
||||||
|
// Never reclaim an owner that may still be publishing its lock record.
|
||||||
|
let stale = false
|
||||||
|
try { stale = owner ? !sameProcess(owner) : Date.now() - fs.statSync(file).mtimeMs > 30000 } catch (err) { if (err.code !== 'ENOENT') throw err; i--; continue }
|
||||||
|
if (stale) {
|
||||||
|
const reaper = path.join(file, '.reaper')
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(reaper)
|
||||||
|
atomic(path.join(reaper, 'owner.json'), { pid: process.pid, started: identity(process.pid) })
|
||||||
|
let current
|
||||||
|
try { current = JSON.parse(fs.readFileSync(path.join(file, 'owner.json'), 'utf8')) } catch {}
|
||||||
|
if (current && sameProcess(current)) fs.rmSync(reaper, { recursive: true })
|
||||||
|
else fs.renameSync(file, `${file}.stale-${randomUUID()}`)
|
||||||
|
} catch (err) {
|
||||||
|
if (!['ENOENT', 'EEXIST'].includes(err.code)) throw err
|
||||||
|
if (err.code === 'EEXIST') {
|
||||||
|
let reaperOwner
|
||||||
|
try { reaperOwner = JSON.parse(fs.readFileSync(path.join(reaper, 'owner.json'), 'utf8')) } catch {}
|
||||||
|
try {
|
||||||
|
if (reaperOwner ? !sameProcess(reaperOwner) : Date.now() - fs.statSync(reaper).mtimeMs > 30000) fs.renameSync(reaper, `${reaper}.stale-${randomUUID()}`)
|
||||||
|
} catch (failure) { if (failure.code !== 'ENOENT') throw failure }
|
||||||
|
await sleep(50)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
i--; continue
|
||||||
|
}
|
||||||
|
if (!wait) return null
|
||||||
|
await sleep(50)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new Error('Queue is busy; retry later')
|
||||||
|
}
|
||||||
|
function validateId(id) {
|
||||||
|
if (!/^[0-9a-f-]{36}$/.test(id || '')) throw new Error('Invalid job id')
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
export class JobQueue {
|
||||||
|
constructor(root = path.join(repo, '.mnemazine/state/jobs')) {
|
||||||
|
this.root = path.resolve(root)
|
||||||
|
fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
|
||||||
|
}
|
||||||
|
dir(id) { return path.join(this.root, validateId(id)) }
|
||||||
|
read(id) { return JSON.parse(fs.readFileSync(path.join(this.dir(id), 'job.json'), 'utf8')) }
|
||||||
|
list() {
|
||||||
|
return fs.readdirSync(this.root).filter(x => /^[0-9a-f-]{36}$/.test(x) && fs.existsSync(path.join(this.root, x, 'job.json')))
|
||||||
|
.map(id => this.read(id)).sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id))
|
||||||
|
}
|
||||||
|
save(job, event) {
|
||||||
|
job.updated_at = now()
|
||||||
|
// State and event history commit together: no torn JSONL/state dual write.
|
||||||
|
job.events = [...(job.events || []), { at: job.updated_at, event, status: job.status }]
|
||||||
|
atomic(path.join(this.dir(job.id), 'job.json'), job)
|
||||||
|
return job
|
||||||
|
}
|
||||||
|
async transaction(fn) {
|
||||||
|
const release = await lock(path.join(this.root, '.state-lock'))
|
||||||
|
try { return fn() } finally { release() }
|
||||||
|
}
|
||||||
|
async submit({ kind, query, files = [], text, mode, project, provenance }) {
|
||||||
|
if (!['ingest', 'search', 'brief'].includes(kind)) throw new Error('kind must be ingest, search or brief')
|
||||||
|
mode ||= 'local'
|
||||||
|
if (!['local', 'deep'].includes(mode)) throw new Error('mode must be local or deep')
|
||||||
|
if (kind === 'ingest' && mode === 'local') throw new Error('Strict ingest requires deep mode; local ingest is not supported')
|
||||||
|
const hasText = text !== undefined
|
||||||
|
if (kind === 'ingest' ? (hasText === Boolean(files.length) || query !== undefined) : (!query?.trim() || files.length || hasText)) throw new Error('ingest requires either files or text; search/brief require a query and no intake inputs')
|
||||||
|
let input_text, input_kind, source_url
|
||||||
|
if (hasText) {
|
||||||
|
if (typeof text !== 'string' || !text.trim() || Buffer.byteLength(text, 'utf8') > 8192 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(text)) throw new Error('Text must contain 1–8192 UTF-8 bytes without control characters')
|
||||||
|
input_text = text.trim()
|
||||||
|
input_kind = 'title'
|
||||||
|
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(input_text)) {
|
||||||
|
let url
|
||||||
|
try { url = new URL(input_text) } catch { throw new Error('Invalid URL') }
|
||||||
|
if (!/^https?:\/\//i.test(input_text) || !['http:', 'https:'].includes(url.protocol) || !url.hostname || url.username || url.password || /\s/.test(input_text)) throw new Error('Only http/https URLs without credentials are supported')
|
||||||
|
input_kind = 'url'
|
||||||
|
source_url = url.href
|
||||||
|
} else if (/^(?:\/\/|www\.)/i.test(input_text)) throw new Error('Use a complete http/https URL')
|
||||||
|
}
|
||||||
|
if (query && (query.length > 16000 || query.includes('\0'))) throw new Error('Invalid query')
|
||||||
|
if (project && !/^[\p{L}\p{N}_.-]{1,128}$/u.test(project)) throw new Error('Invalid project id')
|
||||||
|
if (provenance && (typeof provenance !== 'object' || Array.isArray(provenance) || JSON.stringify(provenance).length > 8192)) throw new Error('Invalid provenance')
|
||||||
|
// Snapshot before publication: worker never sees partially copied inputs.
|
||||||
|
const id = randomUUID(), dir = this.dir(id)
|
||||||
|
fs.mkdirSync(path.join(dir, 'sources'), { recursive: true, mode: 0o700 })
|
||||||
|
syncDir(this.root)
|
||||||
|
const copied = []
|
||||||
|
if (hasText) {
|
||||||
|
// Existing enrichment treats text as research seed; this is no factual note.
|
||||||
|
const request = `# Запрос на исследование\n\nТип входа: ${input_kind === 'url' ? 'ссылка' : 'название или тема'}.\n\nИсходный ввод пользователя:\n${input_text.split('\n').map(line => `> ${line}`).join('\n')}\n${source_url ? `\nИсточник: ${source_url}\n` : ''}\nЭто запрос на исследование, а не готовое знание и не подтверждение фактов. Сначала установите первичный источник и точный предмет запроса. Изучите доступный материал, проверьте утверждения по источникам и сохраните только подтверждённые выводы со ссылками. Если источник недоступен или название неоднозначно, явно сообщите ограничение; не выдумывайте содержание, автора, расшифровку видео или результаты.\n`
|
||||||
|
const hash = createHash('sha256').update(request).digest('hex')
|
||||||
|
const name = `${hash.slice(0, 16)}-research-request.md`
|
||||||
|
const snapshot = path.join(dir, 'sources', name)
|
||||||
|
const fd = fs.openSync(snapshot, 'wx', 0o600)
|
||||||
|
try { fs.writeFileSync(fd, request); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
|
||||||
|
copied.push({ snapshot, name, sha256: hash })
|
||||||
|
}
|
||||||
|
for (const source of files) {
|
||||||
|
const original = path.resolve(source)
|
||||||
|
const fd = fs.openSync(original, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK)
|
||||||
|
let data
|
||||||
|
try {
|
||||||
|
const stat = fs.fstatSync(fd)
|
||||||
|
if (!stat.isFile()) throw new Error('Input must be a regular file')
|
||||||
|
if (stat.size > 512 * 1024 * 1024) throw new Error('File exceeds the current 512 MiB intake limit')
|
||||||
|
data = fs.readFileSync(fd)
|
||||||
|
} finally { fs.closeSync(fd) }
|
||||||
|
const hash = createHash('sha256').update(data).digest('hex')
|
||||||
|
if (copied.some(f => f.sha256 === hash)) continue
|
||||||
|
const name = `${hash.slice(0, 16)}-${path.basename(original).replace(/^\.+/, '') || 'file'}`
|
||||||
|
const snapshot = path.join(dir, 'sources', name)
|
||||||
|
const out = fs.openSync(snapshot, 'wx', 0o600)
|
||||||
|
try { fs.writeFileSync(out, data); fs.fsyncSync(out) } finally { fs.closeSync(out) }
|
||||||
|
copied.push({ original, snapshot, name, sha256: hash })
|
||||||
|
}
|
||||||
|
syncDir(path.join(dir, 'sources'))
|
||||||
|
return this.transaction(() => {
|
||||||
|
const fingerprint = kind === 'ingest' ? createHash('sha256').update(JSON.stringify({ ...(hasText ? { input_text } : { hashes: copied.map(f => f.sha256).sort() }), project, provenance })).digest('hex') : null
|
||||||
|
const previous = fingerprint && this.list().find(j => j.fingerprint === fingerprint && ['queued', 'running', 'completed'].includes(j.status))
|
||||||
|
if (previous) { fs.rmSync(dir, { recursive: true }); return { ...previous, deduplicated: true } }
|
||||||
|
return this.save({ id, kind, query, mode, project, provenance, input_text, input_kind, files: copied, fingerprint, status: 'queued', created_at: now(), attempts: 0 }, 'submitted')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
async change(id, action) {
|
||||||
|
return this.transaction(() => {
|
||||||
|
const job = this.read(id)
|
||||||
|
if (action === 'cancel' && ['queued', 'running'].includes(job.status)) {
|
||||||
|
job.cancel_requested = true
|
||||||
|
if (job.status === 'queued') job.status = 'cancelled'
|
||||||
|
return this.save(job, 'cancel_requested')
|
||||||
|
}
|
||||||
|
if (action === 'retry') {
|
||||||
|
if (!['failed', 'cancelled'].includes(job.status)) throw new Error('Only failed/cancelled jobs can be retried')
|
||||||
|
for (const blocked of this.list().filter(j => j.recovery_blocked || j.id === id)) recordedGroups(this.dir(blocked.id)).concat(blocked.child || []).forEach(ownedGroup)
|
||||||
|
job.status = 'queued'; delete job.error; delete job.result; delete job.cancel_requested
|
||||||
|
delete job.recovery_blocked
|
||||||
|
return this.save(job, 'retried')
|
||||||
|
}
|
||||||
|
return job
|
||||||
|
})
|
||||||
|
}
|
||||||
|
async work({ once = false, execute = executeJob } = {}) {
|
||||||
|
const release = await lock(path.join(this.root, '.worker-lock'), false)
|
||||||
|
if (!release) return { worker: 'already_running' }
|
||||||
|
let stopping = false, activeChild
|
||||||
|
const stop = () => { stopping = true; if (activeChild) terminate(activeChild) }
|
||||||
|
process.on('SIGTERM', stop); process.on('SIGINT', stop)
|
||||||
|
try {
|
||||||
|
// A killed worker may leave its separate child process group alive.
|
||||||
|
for (const job of this.list().filter(j => j.status === 'running' || j.recovery_blocked)) {
|
||||||
|
let groups
|
||||||
|
try {
|
||||||
|
groups = recordedGroups(this.dir(job.id)).concat(job.child || []).filter(ownedGroup)
|
||||||
|
for (const group of groups) terminate(group)
|
||||||
|
if (groups.length) await sleep(1000)
|
||||||
|
for (const group of groups) if (ownedGroup(group)) terminate(group, 'SIGKILL')
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
await this.transaction(() => { const fresh = this.read(job.id); fresh.status = 'failed'; fresh.error = error.message; fresh.recovery_blocked = true; this.save(fresh, 'recovery_blocked') })
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
await this.transaction(() => {
|
||||||
|
const fresh = this.read(job.id)
|
||||||
|
fresh.status = job.recovery_blocked ? 'failed' : (fresh.cancel_requested ? 'cancelled' : 'queued')
|
||||||
|
delete fresh.recovery_blocked
|
||||||
|
delete fresh.child
|
||||||
|
this.save(fresh, 'worker_recovered')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
const job = await this.transaction(() => {
|
||||||
|
const next = this.list().find(j => j.status === 'queued')
|
||||||
|
if (!next) return null
|
||||||
|
next.status = 'running'; next.attempts++
|
||||||
|
return this.save(next, 'started')
|
||||||
|
})
|
||||||
|
if (!job) { if (once) break; await sleep(750); continue }
|
||||||
|
let result, error
|
||||||
|
try {
|
||||||
|
result = await execute(job, this.dir(job.id), async child => {
|
||||||
|
activeChild = child
|
||||||
|
await this.transaction(() => { const j = this.read(job.id); j.child = child; this.save(j, 'child_started') })
|
||||||
|
}, () => stopping || this.read(job.id).cancel_requested)
|
||||||
|
} catch (e) { error = e.message }
|
||||||
|
activeChild = null
|
||||||
|
await this.transaction(() => {
|
||||||
|
const fresh = this.read(job.id)
|
||||||
|
if (error?.includes('Ambiguous live process group')) fresh.recovery_blocked = true
|
||||||
|
fresh.status = fresh.recovery_blocked ? 'failed' : (fresh.cancel_requested ? 'cancelled' : (error ? 'failed' : 'completed'))
|
||||||
|
if (error) fresh.error = error
|
||||||
|
if (result) fresh.result = result
|
||||||
|
if (!fresh.recovery_blocked) delete fresh.child
|
||||||
|
this.save(fresh, fresh.status)
|
||||||
|
})
|
||||||
|
if (this.read(job.id).recovery_blocked) throw new Error(this.read(job.id).error)
|
||||||
|
} while (!once && !stopping)
|
||||||
|
return { worker: 'stopped' }
|
||||||
|
} finally { process.off('SIGTERM', stop); process.off('SIGINT', stop); release() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function terminate(child, signal = 'SIGTERM') {
|
||||||
|
try { process.kill(-child.pid, signal) } catch (e) { if (e.code !== 'ESRCH') throw e }
|
||||||
|
}
|
||||||
|
function recordedGroups(dir) {
|
||||||
|
try {
|
||||||
|
return fs.readFileSync(path.join(dir, 'process-groups.jsonl'), 'utf8').split('\n').slice(0, -1).filter(Boolean).map(line => JSON.parse(line))
|
||||||
|
} catch (e) { if (e.code === 'ENOENT') return []; throw e }
|
||||||
|
}
|
||||||
|
export function pipelineFailure(dir, outcome) {
|
||||||
|
const details = []
|
||||||
|
try {
|
||||||
|
const state = JSON.parse(fs.readFileSync(path.join(dir, 'state/last-run.json'), 'utf8'))
|
||||||
|
details.push(...(Array.isArray(state.failures) ? state.failures : [state.failure]).filter(value => typeof value === 'string').map(value => value.slice(0, 500)))
|
||||||
|
const extracts = path.join(dir, 'cache/extracted')
|
||||||
|
for (const file of fs.readdirSync(extracts).filter(name => name.endsWith('.json')).slice(0, 20)) {
|
||||||
|
const record = JSON.parse(fs.readFileSync(path.join(extracts, file), 'utf8'))
|
||||||
|
if (record.status !== 'needs_manual_context' || typeof record.text_path !== 'string' || path.basename(record.text_path) !== record.text_path) continue
|
||||||
|
const fd = fs.openSync(path.join(extracts, record.text_path), 'r')
|
||||||
|
let text
|
||||||
|
try { const buffer = Buffer.alloc(16384); text = buffer.subarray(0, fs.readSync(fd, buffer)).toString('utf8') }
|
||||||
|
finally { fs.closeSync(fd) }
|
||||||
|
const length = text.replace(/^#{1,6}\s+/gm, '').replace(/\s+/g, ' ').trim().slice(0, 2000).length
|
||||||
|
details.unshift(length > 0 && length < 80
|
||||||
|
? `Файл прочитан, но текст слишком короткий: ${length} символов; нужно не менее 80. Добавьте содержательный контекст.`
|
||||||
|
: 'Недостаточно читаемого текста для обработки. Добавьте текстовый контекст или проверьте качество исходного файла.')
|
||||||
|
}
|
||||||
|
} catch { /* The pipeline can fail before state or extracts exist. Keep exit diagnostics. */ }
|
||||||
|
return `${[...new Set(details)].join(' ')}${details.length ? ' ' : ''}Pipeline exited ${outcome.code ?? outcome.signal}; see ${path.join(dir, 'error.log')}`
|
||||||
|
}
|
||||||
|
async function executeJob(job, dir, recordChild, cancelled) {
|
||||||
|
const env = { ...process.env, MNEMAZINE_ROOT: repo, MNEMAZINE_DEEP: job.mode === 'deep' ? '1' : '0', MNEMAZINE_SEARCH_VERIFY: job.mode === 'deep' ? '1' : '0', MNEMAZINE_SEARCH_LOG: path.join(dir, 'queries.jsonl'), MNEMAZINE_JOB_GROUPS: path.join(dir, 'process-groups.jsonl') }
|
||||||
|
let command = process.execPath, args
|
||||||
|
if (job.kind === 'ingest') {
|
||||||
|
for (const sub of ['inbox', 'state', 'reports', 'archive', 'cache/extracted']) fs.mkdirSync(path.join(dir, sub), { recursive: true })
|
||||||
|
for (const file of job.files) {
|
||||||
|
if (createHash('sha256').update(fs.readFileSync(file.snapshot)).digest('hex') !== file.sha256) throw new Error('Source snapshot integrity check failed')
|
||||||
|
fs.copyFileSync(file.snapshot, path.join(dir, 'inbox', file.name))
|
||||||
|
}
|
||||||
|
Object.assign(env, {
|
||||||
|
MNEMAZINE_INBOX: path.join(dir, 'inbox'), MNEMAZINE_STATE: path.join(dir, 'state'),
|
||||||
|
MNEMAZINE_REPORTS: path.join(dir, 'reports'), MNEMAZINE_ARCHIVE: path.join(dir, 'archive'),
|
||||||
|
MNEMAZINE_CACHE: path.join(dir, 'cache/hashes.json'), MNEMAZINE_EXTRACTS: path.join(dir, 'cache/extracted'),
|
||||||
|
MNEMAZINE_REQUIRE_DEEP: '1', MNEMAZINE_RUN_ID: job.id,
|
||||||
|
})
|
||||||
|
command = 'bash'; args = [path.join(repo, 'scripts/mnemazine-desktop-protocol.sh')]
|
||||||
|
} else {
|
||||||
|
args = [path.join(repo, 'scripts/mnemazine-kb-search.mjs'), `--topic=${job.query}`, '--result-json']
|
||||||
|
if (job.mode === 'deep') args.push('--deep', '--verify')
|
||||||
|
}
|
||||||
|
const outputPath = path.join(dir, 'output.log'), errorPath = path.join(dir, 'error.log')
|
||||||
|
const output = fs.openSync(outputPath, 'w', 0o600), errors = fs.openSync(errorPath, 'w', 0o600)
|
||||||
|
let child
|
||||||
|
try { child = spawn(command, args, { cwd: repo, env, detached: true, stdio: ['ignore', output, errors] }) }
|
||||||
|
finally { fs.closeSync(output); fs.closeSync(errors) }
|
||||||
|
const completion = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', (code, signal) => resolve({ code, signal })) })
|
||||||
|
if (child.pid) await recordChild({ pid: child.pid, started: identity(child.pid) })
|
||||||
|
let killedAt = 0
|
||||||
|
let monitorError
|
||||||
|
const killedGroups = new Map()
|
||||||
|
const cancelGroups = () => {
|
||||||
|
for (const group of recordedGroups(dir).filter(ownedGroup)) {
|
||||||
|
if (!killedGroups.has(group.pid)) { killedGroups.set(group.pid, group); terminate(group) }
|
||||||
|
}
|
||||||
|
if (!killedAt) { killedAt = Date.now(); terminate(child) }
|
||||||
|
else if (Date.now() - killedAt > 2000) terminate(child, 'SIGKILL')
|
||||||
|
}
|
||||||
|
const timer = setInterval(() => {
|
||||||
|
try { if (child.pid && cancelled()) cancelGroups() }
|
||||||
|
catch (e) { monitorError = e; killedAt ||= Date.now(); if (child.pid) terminate(child) }
|
||||||
|
}, 100)
|
||||||
|
let outcome
|
||||||
|
try {
|
||||||
|
outcome = await completion
|
||||||
|
if (child.pid && cancelled() && !monitorError) cancelGroups()
|
||||||
|
if (killedAt) {
|
||||||
|
await sleep(Math.max(0, 2000 - (Date.now() - killedAt)))
|
||||||
|
terminate(child, 'SIGKILL')
|
||||||
|
for (const group of killedGroups.values()) if (ownedGroup(group)) terminate(group, 'SIGKILL')
|
||||||
|
}
|
||||||
|
} finally { clearInterval(timer) }
|
||||||
|
if (monitorError) throw monitorError
|
||||||
|
if (outcome.code !== 0) throw new Error(pipelineFailure(dir, outcome))
|
||||||
|
const result = job.kind === 'ingest' ? { text: 'Обработка копий завершена. Оригиналы сохранены.' } : JSON.parse(fs.readFileSync(outputPath, 'utf8'))
|
||||||
|
if (typeof result.text !== 'string') throw new Error('Search returned no report text')
|
||||||
|
const { text } = result
|
||||||
|
const report_path = path.join(dir, 'result.md')
|
||||||
|
fs.writeFileSync(report_path, text, { mode: 0o600 })
|
||||||
|
return { ...result, report_path }
|
||||||
|
}
|
||||||
|
function startWorker(root) {
|
||||||
|
const child = spawn(process.execPath, [script, 'work', '--root', root], { cwd: repo, detached: true, stdio: 'ignore' })
|
||||||
|
child.unref()
|
||||||
|
}
|
||||||
|
async function main() {
|
||||||
|
const { positionals, values } = parseArgs({ allowPositionals: true, options: {
|
||||||
|
root: { type: 'string' }, kind: { type: 'string' }, id: { type: 'string' }, file: { type: 'string', multiple: true },
|
||||||
|
query: { type: 'string' }, text: { type: 'string' }, mode: { type: 'string' }, project: { type: 'string' }, provenance: { type: 'string' },
|
||||||
|
'no-start': { type: 'boolean' }, once: { type: 'boolean' },
|
||||||
|
} })
|
||||||
|
const [action] = positionals
|
||||||
|
if (positionals.length !== 1 || !['submit', 'list', 'status', 'cancel', 'retry', 'work'].includes(action)) throw new Error('Usage: mnemazine-jobs.mjs submit|list|status|cancel|retry|work [options]')
|
||||||
|
const queue = new JobQueue(values.root)
|
||||||
|
let result
|
||||||
|
if (action === 'submit') result = { job: await queue.submit({ ...values, files: values.file, provenance: values.provenance ? JSON.parse(values.provenance) : undefined }) }
|
||||||
|
if (action === 'list') result = { jobs: queue.list() }
|
||||||
|
if (action === 'status') result = { job: queue.read(values.id) }
|
||||||
|
if (['cancel', 'retry'].includes(action)) result = { job: await queue.change(values.id, action) }
|
||||||
|
if (action === 'work') result = await queue.work({ once: values.once })
|
||||||
|
if (!values['no-start'] && (['submit', 'retry'].includes(action) || (['list', 'status'].includes(action) && queue.list().some(j => ['queued', 'running'].includes(j.status))))) startWorker(queue.root)
|
||||||
|
process.stdout.write(JSON.stringify(result) + '\n')
|
||||||
|
}
|
||||||
|
if (process.argv[1] && path.resolve(process.argv[1]) === script) main().catch(e => { console.error(e.message); process.exitCode = 1 })
|
||||||
@@ -15,8 +15,10 @@
|
|||||||
// engages the LLM swarm. Report written to reports/ as Markdown; path printed.
|
// engages the LLM swarm. Report written to reports/ as Markdown; path printed.
|
||||||
import { promises as fs } from 'node:fs'
|
import { promises as fs } from 'node:fs'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
import { resolveVault } from './mnemazine-paths.mjs'
|
import { resolveVault } from './mnemazine-paths.mjs'
|
||||||
import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||||
|
import { classifyFile, loadTaxonomy, parseFrontmatter } from './mnemazine-machine-class-gate.mjs'
|
||||||
|
|
||||||
const argv = process.argv.slice(2)
|
const argv = process.argv.slice(2)
|
||||||
const SELFTEST = argv.includes('--selftest')
|
const SELFTEST = argv.includes('--selftest')
|
||||||
@@ -29,6 +31,7 @@ function arg(name, fb = '') {
|
|||||||
const DEEP = argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
|
const DEEP = argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
|
||||||
const STDOUT = argv.includes('--stdout')
|
const STDOUT = argv.includes('--stdout')
|
||||||
const JSON_OUT = argv.includes('--json')
|
const JSON_OUT = argv.includes('--json')
|
||||||
|
const RESULT_JSON = argv.includes('--result-json')
|
||||||
|
|
||||||
if (argv.includes('--help')) {
|
if (argv.includes('--help')) {
|
||||||
console.log(`mnemazine-kb-search.mjs — тематический поиск по корпусу знаний.
|
console.log(`mnemazine-kb-search.mjs — тематический поиск по корпусу знаний.
|
||||||
@@ -41,8 +44,10 @@ if (argv.includes('--help')) {
|
|||||||
каталог внутри корпуса — отказ с кодом 2
|
каталог внутри корпуса — отказ с кодом 2
|
||||||
--stdout отчет в stdout, файл не создается
|
--stdout отчет в stdout, файл не создается
|
||||||
--json машинная выдача в stdout: results[] с note/score/subject/snippets
|
--json машинная выдача в stdout: results[] с note/score/subject/snippets
|
||||||
|
--result-json готовая справка и источники в stdout: {text,sources,stats}
|
||||||
--deep LLM-рой: планирование запроса, шард-агенты, синтез
|
--deep LLM-рой: планирование запроса, шард-агенты, синтез
|
||||||
--verify отбраковка необоснованных находок (только с --deep)
|
--verify совместимость: проверка включена всегда с --deep
|
||||||
|
--project ID фильтр projects (не механизм авторизации)
|
||||||
--concurrency N параллелизм роя (по умолчанию 4)
|
--concurrency N параллелизм роя (по умолчанию 4)
|
||||||
--max-notes N потолок кандидатов для роя (по умолчанию 60)
|
--max-notes N потолок кандидатов для роя (по умолчанию 60)
|
||||||
--shard-size N заметок на агента (по умолчанию 6)
|
--shard-size N заметок на агента (по умолчанию 6)
|
||||||
@@ -59,10 +64,9 @@ const MAX_NOTES = Number(arg('max-notes', '60')) // candidate cap fed to the
|
|||||||
const SHARD_SIZE = Number(arg('shard-size', '6')) // notes per agent
|
const SHARD_SIZE = Number(arg('shard-size', '6')) // notes per agent
|
||||||
const MAX_SHARDS = Number(arg('max-shards', process.env.MNEMAZINE_SEARCH_MAX_SHARDS || '12')) // deep cost cap: hard limit on agents spawned
|
const MAX_SHARDS = Number(arg('max-shards', process.env.MNEMAZINE_SEARCH_MAX_SHARDS || '12')) // deep cost cap: hard limit on agents spawned
|
||||||
const EXCERPT = 2500 // chars of each note shown to an agent
|
const EXCERPT = 2500 // chars of each note shown to an agent
|
||||||
// 2B perspective-diverse verify: opt-in (extra K agents). Default OFF to keep
|
// Verification is mandatory for deep findings. The budget bounds accepted
|
||||||
// the token budget tight — enable when groundedness matters. One call per
|
// findings too: unreviewed findings never leak around the verifier.
|
||||||
// top-K finding, judging 3 lenses at once (grounded/relevant/actionable).
|
const VERIFY = DEEP || argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY === '1'
|
||||||
const VERIFY = argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY === '1'
|
|
||||||
const MAX_VERIFY = Number(arg('max-verify', '5')) // top-K findings to verify
|
const MAX_VERIFY = Number(arg('max-verify', '5')) // top-K findings to verify
|
||||||
|
|
||||||
// --- helpers -----------------------------------------------------------------
|
// --- helpers -----------------------------------------------------------------
|
||||||
@@ -78,7 +82,7 @@ async function walk(dir, out = []) {
|
|||||||
const full = path.join(dir, e.name)
|
const full = path.join(dir, e.name)
|
||||||
if (isServicePath(full)) continue
|
if (isServicePath(full)) continue
|
||||||
if (e.isDirectory()) await walk(full, out)
|
if (e.isDirectory()) await walk(full, out)
|
||||||
else if (e.name.endsWith('.md')) out.push(full)
|
else if (e.isFile() && e.name.endsWith('.md')) out.push(full)
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
@@ -126,6 +130,30 @@ function snippets(text, terms, max = 3) {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ponytail: bounded windows cover the whole note without a second index.
|
||||||
|
// A persistent chunk index can replace this when the corpus latency warrants it.
|
||||||
|
export function evidenceExcerpt(text, topic) {
|
||||||
|
const terms = uniq(tokens(topic))
|
||||||
|
const windows = []
|
||||||
|
for (let start = 0; start < text.length; start += 800) {
|
||||||
|
const body = text.slice(start, start + 1000)
|
||||||
|
const found = new Set(tokens(body))
|
||||||
|
windows.push({ start, body, score: terms.filter(t => found.has(t)).length })
|
||||||
|
}
|
||||||
|
return windows.sort((a, b) => b.score - a.score || a.start - b.start)
|
||||||
|
.slice(0, 2).sort((a, b) => a.start - b.start)
|
||||||
|
.map(w => `[символы ${w.start + 1}–${w.start + w.body.length}]\n${w.body}`)
|
||||||
|
.join('\n\n').slice(0, EXCERPT)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cloudReadable(file, taxonomy) {
|
||||||
|
const classification = classifyFile(file, taxonomy)
|
||||||
|
if (classification.undetermined || !['public', 'infra', 'text'].includes(classification.klass)) return false
|
||||||
|
// Directory ancestry can raise sensitivity even when frontmatter omits the
|
||||||
|
// section or the note lives in a nested folder inside a private section.
|
||||||
|
return !path.resolve(file).split(path.sep).some(segment => ['personal', 'pd'].includes(taxonomy.by_section[segment]))
|
||||||
|
}
|
||||||
|
|
||||||
function frontmatterSubject(text) {
|
function frontmatterSubject(text) {
|
||||||
if (!text.startsWith('---')) return null
|
if (!text.startsWith('---')) return null
|
||||||
const end = text.indexOf('\n---', 3)
|
const end = text.indexOf('\n---', 3)
|
||||||
@@ -142,7 +170,7 @@ function frontmatterSubject(text) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function logQuery(entry) {
|
async function logQuery(entry) {
|
||||||
const file = path.resolve('.mnemazine', 'state', 'kb-search-log.jsonl')
|
const file = path.resolve(process.env.MNEMAZINE_SEARCH_LOG || path.join('.mnemazine', 'state', 'kb-search-log.jsonl'))
|
||||||
await fs.mkdir(path.dirname(file), { recursive: true })
|
await fs.mkdir(path.dirname(file), { recursive: true })
|
||||||
await fs.appendFile(file, `${JSON.stringify(entry)}\n`, 'utf8')
|
await fs.appendFile(file, `${JSON.stringify(entry)}\n`, 'utf8')
|
||||||
}
|
}
|
||||||
@@ -261,7 +289,7 @@ function assignFacet(note, facets) {
|
|||||||
async function extractShard(topic, shard, facet) {
|
async function extractShard(topic, shard, facet) {
|
||||||
if (DEEP && llmAvailable(PROVIDER)) {
|
if (DEEP && llmAvailable(PROVIDER)) {
|
||||||
const blob = shard.map(n =>
|
const blob = shard.map(n =>
|
||||||
fenceUntrusted('NOTE', `### ${n.rel}\n${n.text.slice(0, EXCERPT)}`)).join('\n\n')
|
fenceUntrusted('NOTE', `### ${n.rel}\n${evidenceExcerpt(n.text, topic)}`)).join('\n\n')
|
||||||
const focus = facet ? `\nФокус-ось этого шарда: «${facet}» — приоритет находкам по этой оси (но не пропускай иное важное по теме).` : ''
|
const focus = facet ? `\nФокус-ось этого шарда: «${facet}» — приоритет находкам по этой оси (но не пропускай иное важное по теме).` : ''
|
||||||
const prompt = `Ты агент-исследователь. Тема: "${topic}".${focus}
|
const prompt = `Ты агент-исследователь. Тема: "${topic}".${focus}
|
||||||
Из заметок ниже выбери ТОЛЬКО релевантное теме. Для каждой находки: note (путь заметки), source (URL/ссылка из заметки, если есть), insight (1-2 предложения по-русски — что важного для темы), relevance (1-5). Ничего не выдумывай сверх заметок.
|
Из заметок ниже выбери ТОЛЬКО релевантное теме. Для каждой находки: note (путь заметки), source (URL/ссылка из заметки, если есть), insight (1-2 предложения по-русски — что важного для темы), relevance (1-5). Ничего не выдумывай сверх заметок.
|
||||||
@@ -269,7 +297,8 @@ async function extractShard(topic, shard, facet) {
|
|||||||
${blob}`
|
${blob}`
|
||||||
try {
|
try {
|
||||||
const out = await llmJson(prompt, FINDINGS_SCHEMA, { provider: PROVIDER, tools: [] })
|
const out = await llmJson(prompt, FINDINGS_SCHEMA, { provider: PROVIDER, tools: [] })
|
||||||
return (out.findings || []).filter(f => f.insight && f.relevance >= 2)
|
return (out.findings || []).filter(f => f.insight && f.relevance >= 2 && shard.some(n => n.rel === f.note))
|
||||||
|
.map(f => ({ ...f, source: shard.find(n => n.rel === f.note).text.includes(f.source || '\0') && /^https?:\/\//.test(f.source || '') ? f.source : '' }))
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`[kb-search] shard agent failed: ${e.message}; local fallback`)
|
console.error(`[kb-search] shard agent failed: ${e.message}; local fallback`)
|
||||||
}
|
}
|
||||||
@@ -286,10 +315,9 @@ ${blob}`
|
|||||||
// One agent per finding, judging 3 lenses at once (grounded/relevant/actionable)
|
// One agent per finding, judging 3 lenses at once (grounded/relevant/actionable)
|
||||||
// against the note's own text. Bounded (K calls). Drops ungrounded findings —
|
// against the note's own text. Bounded (K calls). Drops ungrounded findings —
|
||||||
// the anti-hallucination gate (§6 claim->content). Opt-in via VERIFY.
|
// the anti-hallucination gate (§6 claim->content). Opt-in via VERIFY.
|
||||||
async function verifyFindings(topic, findings, textByNote) {
|
export async function verifyFindings(topic, findings, textByNote, verify = llmJson, enabled = VERIFY && DEEP && llmAvailable(PROVIDER)) {
|
||||||
if (!VERIFY || !DEEP || !llmAvailable(PROVIDER) || !findings.length) return { kept: findings, dropped: 0 }
|
if (!enabled || !findings.length) return { kept: findings, dropped: 0 }
|
||||||
const top = findings.slice(0, MAX_VERIFY)
|
const top = findings.slice(0, MAX_VERIFY)
|
||||||
const rest = findings.slice(MAX_VERIFY)
|
|
||||||
const verdicts = []
|
const verdicts = []
|
||||||
await mapLimit(top, CONCURRENCY, async (f, idx) => {
|
await mapLimit(top, CONCURRENCY, async (f, idx) => {
|
||||||
const note = textByNote.get(f.note) || ''
|
const note = textByNote.get(f.note) || ''
|
||||||
@@ -297,12 +325,12 @@ async function verifyFindings(topic, findings, textByNote) {
|
|||||||
"${f.insight}"
|
"${f.insight}"
|
||||||
Оцени по 3 осям относительно текста заметки ниже: grounded (находка реально опирается на текст, не выдумана), relevant (по теме), actionable (полезна на практике). Верни булевы + reason.
|
Оцени по 3 осям относительно текста заметки ниже: grounded (находка реально опирается на текст, не выдумана), relevant (по теме), actionable (полезна на практике). Верни булевы + reason.
|
||||||
|
|
||||||
${fenceUntrusted('NOTE', note.slice(0, EXCERPT))}`
|
${fenceUntrusted('NOTE', evidenceExcerpt(note, `${topic} ${f.insight}`))}`
|
||||||
try { verdicts[idx] = await llmJson(prompt, VERDICT_SCHEMA, { provider: PROVIDER, tools: [] }) }
|
try { verdicts[idx] = note ? await verify(prompt, VERDICT_SCHEMA, { provider: PROVIDER, tools: [], dataClass: 'text' }) : null }
|
||||||
catch (e) { console.error(`[kb-search] verify failed for ${f.note}: ${e.message}; keeping finding`); verdicts[idx] = { grounded: true, relevant: true, actionable: true } }
|
catch (e) { console.error(`[kb-search] verify failed for ${f.note}: ${e.message}; finding withheld`); verdicts[idx] = null }
|
||||||
})
|
})
|
||||||
const kept = top.filter((_, i) => verdicts[i]?.grounded !== false).concat(rest)
|
const kept = top.filter((_, i) => verdicts[i]?.grounded === true && verdicts[i]?.relevant === true)
|
||||||
return { kept, dropped: top.length - (kept.length - rest.length) }
|
return { kept, dropped: findings.length - kept.length }
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- orchestrator: synthesize findings into a report -------------------------
|
// --- orchestrator: synthesize findings into a report -------------------------
|
||||||
@@ -313,7 +341,7 @@ async function synthesize(topic, findings, facets = []) {
|
|||||||
const prompt = `Ты оркестратор. Собери из находок агентов справку по теме "${topic}" на РУССКОМ, стиль humanizer — живо, ясно, по делу, без воды и канцелярита. Дедуплицируй, сгруппируй по под-темам (themes), отметь связи (connections), противоречия (contradictions), пробелы знаний (gaps) и следующие шаги (next). Не выдумывай сверх находок.${axes}
|
const prompt = `Ты оркестратор. Собери из находок агентов справку по теме "${topic}" на РУССКОМ, стиль humanizer — живо, ясно, по делу, без воды и канцелярита. Дедуплицируй, сгруппируй по под-темам (themes), отметь связи (connections), противоречия (contradictions), пробелы знаний (gaps) и следующие шаги (next). Не выдумывай сверх находок.${axes}
|
||||||
|
|
||||||
Находки:
|
Находки:
|
||||||
${blob}`
|
${fenceUntrusted('FINDINGS', blob)}`
|
||||||
try { return await llmJson(prompt, SYNTH_SCHEMA, { provider: PROVIDER }) }
|
try { return await llmJson(prompt, SYNTH_SCHEMA, { provider: PROVIDER }) }
|
||||||
catch (e) { console.error(`[kb-search] synthesis failed: ${e.message}; local assembly`) }
|
catch (e) { console.error(`[kb-search] synthesis failed: ${e.message}; local assembly`) }
|
||||||
}
|
}
|
||||||
@@ -342,7 +370,7 @@ function renderReport(topic, report, meta) {
|
|||||||
L.push(`> Поиск по базе знаний · ${meta.stamp} · просмотрено ${meta.scanned} заметок, отобрано ${meta.candidates}, находок ${meta.findings} · режим: ${meta.deep ? 'рой агентов (deep)' : 'локальный'}`, '')
|
L.push(`> Поиск по базе знаний · ${meta.stamp} · просмотрено ${meta.scanned} заметок, отобрано ${meta.candidates}, находок ${meta.findings} · режим: ${meta.deep ? 'рой агентов (deep)' : 'локальный'}`, '')
|
||||||
if (meta.facets?.length) L.push(`> Оси разбора: ${meta.facets.join(' · ')}`, '')
|
if (meta.facets?.length) L.push(`> Оси разбора: ${meta.facets.join(' · ')}`, '')
|
||||||
if (meta.droppedNotes) L.push(`> ⚠️ Лимит стоимости: ${meta.droppedNotes} заметок-кандидатов не разобраны (--max-shards). Подними лимит для полного охвата.`, '')
|
if (meta.droppedNotes) L.push(`> ⚠️ Лимит стоимости: ${meta.droppedNotes} заметок-кандидатов не разобраны (--max-shards). Подними лимит для полного охвата.`, '')
|
||||||
if (meta.droppedByVerify) L.push(`> 🔎 Verify: ${meta.droppedByVerify} находок отброшено как необоснованные.`, '')
|
if (meta.droppedByVerify) L.push(`> Проверка: не включено ${meta.droppedByVerify} находок (нет подтверждения, ошибка проверки или предел проверок).`, '')
|
||||||
L.push('## Главное', '', report.summary || '—', '')
|
L.push('## Главное', '', report.summary || '—', '')
|
||||||
if (report.themes?.length) {
|
if (report.themes?.length) {
|
||||||
L.push('## По под-темам', '')
|
L.push('## По под-темам', '')
|
||||||
@@ -361,17 +389,27 @@ function renderReport(topic, report, meta) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- main --------------------------------------------------------------------
|
// --- main --------------------------------------------------------------------
|
||||||
async function run(topic, vault, outDir, { stdout = false, json = false } = {}) {
|
async function run(topic, vault, outDir, { stdout = false, json = false, resultJson = false } = {}) {
|
||||||
const stamp = new Date().toISOString()
|
const stamp = new Date().toISOString()
|
||||||
const { terms, facets } = await plan(topic)
|
const { terms, facets } = await plan(topic)
|
||||||
// RECON
|
// RECON
|
||||||
const files = await walk(vault)
|
const files = await walk(vault)
|
||||||
const scored = []
|
const scored = []
|
||||||
|
const taxonomy = DEEP ? loadTaxonomy() : null
|
||||||
|
let withheld = 0
|
||||||
|
const project = arg('project')
|
||||||
for (const f of files) {
|
for (const f of files) {
|
||||||
const text = await fs.readFile(f, 'utf8').catch(() => '')
|
const text = await fs.readFile(f, 'utf8').catch(() => '')
|
||||||
if (!text) continue
|
if (!text) continue
|
||||||
|
if (project && !parseFrontmatter(text).fields?.projects?.includes(project)) continue
|
||||||
|
if (DEEP) {
|
||||||
|
// Cloud research only sees ordinary/public notes. A missing class must
|
||||||
|
// not inherit the LLM bridge's default infra class.
|
||||||
|
if (!cloudReadable(f, taxonomy)) { withheld++; continue }
|
||||||
|
}
|
||||||
const rel = path.relative(vault, f)
|
const rel = path.relative(vault, f)
|
||||||
const score = scoreNote(text, rel, terms)
|
// Expanded synonyms are alternatives, never extra mandatory query words.
|
||||||
|
const score = Math.max(scoreNote(text, rel, tokens(topic)), ...terms.map(term => scoreNote(text, rel, [term])))
|
||||||
if (score > 0) scored.push({ rel, text, score, subject: frontmatterSubject(text), url: text.match(/https?:\/\/\S+/)?.[0] || '' })
|
if (score > 0) scored.push({ rel, text, score, subject: frontmatterSubject(text), url: text.match(/https?:\/\/\S+/)?.[0] || '' })
|
||||||
}
|
}
|
||||||
scored.sort((a, b) => b.score - a.score)
|
scored.sort((a, b) => b.score - a.score)
|
||||||
@@ -384,7 +422,7 @@ async function run(topic, vault, outDir, { stdout = false, json = false } = {})
|
|||||||
snippets: snippets(n.text, terms)
|
snippets: snippets(n.text, terms)
|
||||||
}))
|
}))
|
||||||
await logQuery({ ts: stamp, topic, mode: 'json', results: results.length })
|
await logQuery({ ts: stamp, topic, mode: 'json', results: results.length })
|
||||||
process.stdout.write(`${JSON.stringify({ topic, scanned: files.length, results }, null, 2)}\n`)
|
process.stdout.write(`${JSON.stringify({ topic, scanned: files.length, withheld, results }, null, 2)}\n`)
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
// FAN-OUT — shard within facet groups so each shard carries one focus axis
|
// FAN-OUT — shard within facet groups so each shard carries one focus axis
|
||||||
@@ -416,12 +454,22 @@ async function run(topic, vault, outDir, { stdout = false, json = false } = {})
|
|||||||
catch (e) { console.error(`[kb-search] shard failed: ${e.message}`) }
|
catch (e) { console.error(`[kb-search] shard failed: ${e.message}`) }
|
||||||
})
|
})
|
||||||
findings.sort((a, b) => (b.relevance || 0) - (a.relevance || 0))
|
findings.sort((a, b) => (b.relevance || 0) - (a.relevance || 0))
|
||||||
// VERIFY (2B, opt-in): drop ungrounded top findings before synthesis.
|
// VERIFY: withhold unchecked findings before synthesis.
|
||||||
const textByNote = new Map(candidates.map(c => [c.rel, c.text]))
|
const textByNote = new Map(candidates.map(c => [c.rel, c.text]))
|
||||||
const { kept, dropped: droppedByVerify } = await verifyFindings(topic, findings, textByNote)
|
const { kept, dropped: droppedByVerify } = await verifyFindings(topic, findings, textByNote)
|
||||||
// FAN-IN
|
// FAN-IN
|
||||||
const report = await synthesize(topic, kept, facets)
|
const report = await synthesize(topic, kept, facets)
|
||||||
const md = renderReport(topic, report, { stamp, scanned: files.length, candidates: candidates.length, findings: kept.length, deep: DEEP && llmAvailable(PROVIDER), droppedNotes, droppedByVerify, facets: facets.map(f => f.label) })
|
let md = renderReport(topic, report, { stamp, scanned: files.length, candidates: candidates.length, findings: kept.length, deep: DEEP && llmAvailable(PROVIDER), droppedNotes, droppedByVerify, facets: facets.map(f => f.label) })
|
||||||
|
if (withheld) md += `\n\nИз облачной обработки исключено заметок по классу данных: ${withheld}. Для локального поиска выключи deep.\n`
|
||||||
|
if (kept.length) md += '\n\n## Источники ответа\n\n' + [...new Set(kept.map(f => f.note))].map(note => {
|
||||||
|
const target = path.join(vault, note)
|
||||||
|
return `- [${note.replace(/[\[\]]/g, '')}](<${target.replace(/>/g, '%3E')}>)`
|
||||||
|
}).join('\n') + '\n'
|
||||||
|
if (resultJson) {
|
||||||
|
const sources = [...new Set(kept.map(f => f.note))].map(note => ({ title: note, path: path.join(vault, note) }))
|
||||||
|
process.stdout.write(JSON.stringify({ text: md, sources, stats: { scanned: files.length, findings: kept.length, withheld, droppedByVerify, droppedNotes } }) + '\n')
|
||||||
|
return null
|
||||||
|
}
|
||||||
await logQuery({ ts: stamp, topic, mode: DEEP && llmAvailable(PROVIDER) ? 'deep' : 'local', results: kept.length })
|
await logQuery({ ts: stamp, topic, mode: DEEP && llmAvailable(PROVIDER) ? 'deep' : 'local', results: kept.length })
|
||||||
if (stdout) {
|
if (stdout) {
|
||||||
process.stdout.write(md.endsWith('\n') ? md : `${md}\n`)
|
process.stdout.write(md.endsWith('\n') ? md : `${md}\n`)
|
||||||
@@ -451,6 +499,7 @@ async function selftest() {
|
|||||||
console.log('selftest ok')
|
console.log('selftest ok')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
if (SELFTEST) {
|
if (SELFTEST) {
|
||||||
selftest().catch(e => { console.error(e.message); process.exit(1) })
|
selftest().catch(e => { console.error(e.message); process.exit(1) })
|
||||||
} else {
|
} else {
|
||||||
@@ -461,11 +510,12 @@ if (SELFTEST) {
|
|||||||
// fail-closed: каталог отчета внутри корпуса превращает просмотр в правку
|
// fail-closed: каталог отчета внутри корпуса превращает просмотр в правку
|
||||||
// корпуса — отказ держит код, а не привычку (план П08). С --stdout файла нет.
|
// корпуса — отказ держит код, а не привычку (план П08). С --stdout файла нет.
|
||||||
const relOut = path.relative(vault, outDir)
|
const relOut = path.relative(vault, outDir)
|
||||||
if (!STDOUT && !JSON_OUT && (relOut === '' || (!relOut.startsWith('..') && !path.isAbsolute(relOut)))) {
|
if (!STDOUT && !JSON_OUT && !RESULT_JSON && (relOut === '' || (!relOut.startsWith('..') && !path.isAbsolute(relOut)))) {
|
||||||
console.error(`[kb-search] отказ: каталог отчета внутри корпуса (out=${outDir}, vault=${vault}). Укажи --out вне корпуса или --stdout.`)
|
console.error(`[kb-search] отказ: каталог отчета внутри корпуса (out=${outDir}, vault=${vault}). Укажи --out вне корпуса или --stdout.`)
|
||||||
process.exit(2)
|
process.exit(2)
|
||||||
}
|
}
|
||||||
run(topic, vault, outDir, { stdout: STDOUT, json: JSON_OUT })
|
run(topic, vault, outDir, { stdout: STDOUT, json: JSON_OUT, resultJson: RESULT_JSON })
|
||||||
.then(p => { if (p) console.log(p) })
|
.then(p => { if (p) console.log(p) })
|
||||||
.catch(e => { console.error(`[kb-search] ${e.message}`); process.exit(1) })
|
.catch(e => { console.error(`[kb-search] ${e.message}`); process.exit(1) })
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|||||||
+74
-66
@@ -14,10 +14,11 @@
|
|||||||
//
|
//
|
||||||
// Default pipeline never calls an LLM — only the opt-in --deep path does.
|
// Default pipeline never calls an LLM — only the opt-in --deep path does.
|
||||||
import { spawnSync, spawn } from 'node:child_process'
|
import { spawnSync, spawn } from 'node:child_process'
|
||||||
import { existsSync, promises as fs } from 'node:fs'
|
import { appendFileSync, promises as fs } from 'node:fs'
|
||||||
import os from 'node:os'
|
import os from 'node:os'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { loadRegistry, orderCandidates, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
|
import { loadRegistry, orderCandidates, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
|
||||||
|
import { resolveExecutable, readCooldown, recordCooldown, classifyProcessFailure } from './mnemazine-cli-runtime.mjs'
|
||||||
|
|
||||||
const PROGRESS_EVERY_MS = Number(process.env.MNEMAZINE_LLM_PROGRESS_EVERY_MS || '30000')
|
const PROGRESS_EVERY_MS = Number(process.env.MNEMAZINE_LLM_PROGRESS_EVERY_MS || '30000')
|
||||||
const PROGRESS = process.env.MNEMAZINE_LLM_PROGRESS !== '0'
|
const PROGRESS = process.env.MNEMAZINE_LLM_PROGRESS !== '0'
|
||||||
@@ -27,7 +28,6 @@ const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
|
|||||||
// this machine). A CLI without stdin_prompt gets the prompt in argv; over this we
|
// this machine). A CLI without stdin_prompt gets the prompt in argv; over this we
|
||||||
// fail with a named cause and move down the chain, never silently truncate.
|
// fail with a named cause and move down the chain, never silently truncate.
|
||||||
const ARG_MAX = Number(process.env.MNEMAZINE_ARG_MAX || '1048576')
|
const ARG_MAX = Number(process.env.MNEMAZINE_ARG_MAX || '1048576')
|
||||||
const HOME = os.homedir()
|
|
||||||
const WEB_TOOL_RE = /^(WebSearch|WebFetch|mcp__firecrawl|mcp__tavily)$/i
|
const WEB_TOOL_RE = /^(WebSearch|WebFetch|mcp__firecrawl|mcp__tavily)$/i
|
||||||
|
|
||||||
function progress(label, message) {
|
function progress(label, message) {
|
||||||
@@ -48,6 +48,22 @@ function runProc(bin, args, { input, timeoutMs, cwd, label } = {}) {
|
|||||||
// убит руками. Родитель по-прежнему дожидается ребенка: unref не зовется.
|
// убит руками. Родитель по-прежнему дожидается ребенка: unref не зовется.
|
||||||
try { child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: true }) }
|
try { child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: true }) }
|
||||||
catch (e) { return resolve({ status: 1, stdout: '', stderr: String(e.message) }) }
|
catch (e) { return resolve({ status: 1, stdout: '', stderr: String(e.message) }) }
|
||||||
|
// The durable job owns cancellation of every detached LLM group, including
|
||||||
|
// CLI wrappers that outlive the pipeline process. PID start time prevents
|
||||||
|
// killing an unrelated process after a job/worker restart.
|
||||||
|
if (child.pid && process.env.MNEMAZINE_JOB_GROUPS) {
|
||||||
|
try {
|
||||||
|
const started = spawnSync('ps', ['-p', String(child.pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout?.trim()
|
||||||
|
if (!started) throw new Error('cannot record LLM process identity')
|
||||||
|
appendFileSync(process.env.MNEMAZINE_JOB_GROUPS, JSON.stringify({ pid: child.pid, started }) + '\n', { mode: 0o600 })
|
||||||
|
} catch (error) {
|
||||||
|
try { process.kill(-child.pid, 'SIGKILL') } catch { /* child already exited */ }
|
||||||
|
child.on('error', () => {})
|
||||||
|
child.stdin.on('error', () => {})
|
||||||
|
child.stdin.end()
|
||||||
|
return resolve({ status: 1, stdout: '', stderr: `job process tracking failed: ${error.message}` })
|
||||||
|
}
|
||||||
|
}
|
||||||
let out = '', err = '', killed = false, grace = null
|
let out = '', err = '', killed = false, grace = null
|
||||||
const started = Date.now()
|
const started = Date.now()
|
||||||
progress(label, `start timeout=${timeoutMs || 0}ms`)
|
progress(label, `start timeout=${timeoutMs || 0}ms`)
|
||||||
@@ -106,41 +122,17 @@ function providerChain(dataClass, capabilities) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- binary resolution (generic, per invoke[0]) -------------------------------
|
// --- binary resolution (generic, per invoke[0]) -------------------------------
|
||||||
// The binary is invoke[0], resolved via env override (MNEMAZINE_<NAME>_BIN),
|
// Resolve executable files from PATH/common install directories; never
|
||||||
// then the login shell (however the user installed it), then a small table of
|
// interpolate a registry value into shell code or invoke auth probes.
|
||||||
// known install locations, then a bare PATH lookup at spawn. resolveClaudeBin's
|
|
||||||
// knowledge survives as the `claude` entry of EXTRA_CANDIDATES — data, not a
|
|
||||||
// name branch.
|
|
||||||
const EXTRA_CANDIDATES = {
|
|
||||||
claude: [
|
|
||||||
path.join(HOME, '.claude/local/claude'),
|
|
||||||
'/opt/homebrew/bin/claude',
|
|
||||||
'/usr/local/bin/claude',
|
|
||||||
path.join(HOME, '.local/bin/claude'),
|
|
||||||
path.join(HOME, '.npm-global/bin/claude'),
|
|
||||||
'/Applications/Claude.app/Contents/Resources/claude'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
const _binCache = {}
|
|
||||||
function envBinKey(binName) {
|
function envBinKey(binName) {
|
||||||
return `MNEMAZINE_${binName.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_BIN`
|
return `MNEMAZINE_${binName.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_BIN`
|
||||||
}
|
}
|
||||||
function resolveBin(binName) {
|
function resolveBin(binName) {
|
||||||
if (_binCache[binName] !== undefined) return _binCache[binName]
|
return resolveExecutable(binName)
|
||||||
const override = process.env[envBinKey(binName)]
|
|
||||||
if (override) return (_binCache[binName] = override)
|
|
||||||
const shell = process.env.SHELL || '/bin/zsh'
|
|
||||||
const viaShell = spawnSync(shell, ['-lic', `command -v ${binName}`], { encoding: 'utf8' }).stdout || ''
|
|
||||||
const hit = viaShell.trim().split('\n').pop()
|
|
||||||
if (hit && existsSync(hit)) return (_binCache[binName] = hit)
|
|
||||||
for (const c of (EXTRA_CANDIDATES[binName] || [])) if (existsSync(c)) return (_binCache[binName] = c)
|
|
||||||
return (_binCache[binName] = binName) // last resort: bare PATH lookup at spawn time
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function binExists(bin) {
|
function binExists(bin) {
|
||||||
if (bin.includes('/')) return existsSync(bin)
|
return Boolean(bin && resolveExecutable(bin))
|
||||||
const which = spawnSync(process.env.SHELL || '/bin/zsh', ['-lic', `command -v ${bin}`], { encoding: 'utf8' })
|
|
||||||
return which.status === 0 && Boolean(which.stdout.trim())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function requireBin(provider, entry) {
|
function requireBin(provider, entry) {
|
||||||
@@ -176,7 +168,7 @@ export function providerCostTier(provider) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function needsWebTools(opts = {}) {
|
function needsWebTools(opts = {}) {
|
||||||
return (opts.tools || []).some(tool => WEB_TOOL_RE.test(tool))
|
return (opts.capabilities || []).includes('web_search') || (opts.tools || []).some(tool => WEB_TOOL_RE.test(tool))
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureWebCapable(provider, entry, opts) {
|
function ensureWebCapable(provider, entry, opts) {
|
||||||
@@ -190,8 +182,9 @@ function ensureWebCapable(provider, entry, opts) {
|
|||||||
// the general rule that replaced the old per-provider web-tools literal.
|
// the general rule that replaced the old per-provider web-tools literal.
|
||||||
function fallbackProviders(provider, opts = {}) {
|
function fallbackProviders(provider, opts = {}) {
|
||||||
if (process.env.MNEMAZINE_LLM_FALLBACK === '0') return []
|
if (process.env.MNEMAZINE_LLM_FALLBACK === '0') return []
|
||||||
const caps = needsWebTools(opts) ? ['web_search'] : []
|
const caps = [...(opts.capabilities || []), ...(needsWebTools(opts) ? ['web_search'] : [])]
|
||||||
return providerChain(opts.dataClass || 'infra', caps).filter(name => name !== provider && llmAvailable(name))
|
return orderCandidates(registry(), { dataClass: opts.dataClass || 'infra', capabilities: caps, tier: opts.tier }).candidates
|
||||||
|
.map(entry => entry.name).filter(name => name !== provider && llmAvailable(name))
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- untrusted input fence (unchanged; primary prompt-injection defense) -------
|
// --- untrusted input fence (unchanged; primary prompt-injection defense) -------
|
||||||
@@ -259,11 +252,12 @@ function assertSchema(value, schema, where = '$') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function procError(label, res) {
|
function procError(label, res) {
|
||||||
const stderr = String(res.stderr || '').trim()
|
const reason = classifyProcessFailure(res)
|
||||||
if (stderr) return `${label} failed (status ${res.status}): ${stderr.slice(-400)}`
|
const error = new Error(`${label} failed (${reason}; status ${res.status})`)
|
||||||
const stdout = String(res.stdout || '').trim()
|
error.reason = reason
|
||||||
if (stdout) return `${label} failed (status ${res.status}): ${stdout.slice(-400)}`
|
const retry = `${res.stderr || ''}\n${res.stdout || ''}`.match(/\bretry-after\s*:\s*(\d+)\b/i)
|
||||||
return `${label} failed (status ${res.status}): empty stderr/stdout`
|
if (retry) error.retryAfterMs = Number(retry[1]) * 1000
|
||||||
|
return error
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prompt goes on stdin when the CLI declares stdin_prompt; otherwise as the last
|
// Prompt goes on stdin when the CLI declares stdin_prompt; otherwise as the last
|
||||||
@@ -305,7 +299,7 @@ async function inlineSchemaJson(provider, entry, prompt, schema, opts) {
|
|||||||
args = [...args, '--json-schema', JSON.stringify(strictOutputSchema(schema))]
|
args = [...args, '--json-schema', JSON.stringify(strictOutputSchema(schema))]
|
||||||
const { args: finalArgs, input } = deliverPrompt(entry, args, prompt)
|
const { args: finalArgs, input } = deliverPrompt(entry, args, prompt)
|
||||||
const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json` })
|
const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json` })
|
||||||
if (res.status !== 0) throw new Error(procError(`${provider} json`, res))
|
if (res.status !== 0) throw procError(`${provider} json`, res)
|
||||||
return extractJson(unwrap(res.stdout))
|
return extractJson(unwrap(res.stdout))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -321,7 +315,7 @@ async function fileSchemaJson(provider, entry, prompt, schema, opts) {
|
|||||||
args = insertCwd(args, cwd)
|
args = insertCwd(args, cwd)
|
||||||
args = [...args, '--output-schema', schemaFile, '-o', outFile, '-'] // prompt via stdin
|
args = [...args, '--output-schema', schemaFile, '-o', outFile, '-'] // prompt via stdin
|
||||||
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json${needsWebTools(opts) ? ':search' : ''}` })
|
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json${needsWebTools(opts) ? ':search' : ''}` })
|
||||||
if (res.status !== 0) throw new Error(procError(`${provider} exec`, res))
|
if (res.status !== 0) throw procError(`${provider} exec`, res)
|
||||||
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
|
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
|
||||||
if (!raw.trim()) throw new Error(`${provider} returned empty output`)
|
if (!raw.trim()) throw new Error(`${provider} returned empty output`)
|
||||||
try { return JSON.parse(raw) } catch (err) { throw new Error(`${provider} returned non-JSON: ${err.message}; head: ${raw.slice(0, 200)}`) }
|
try { return JSON.parse(raw) } catch (err) { throw new Error(`${provider} returned non-JSON: ${err.message}; head: ${raw.slice(0, 200)}`) }
|
||||||
@@ -335,7 +329,7 @@ async function inPromptJson(provider, entry, prompt, schema, opts) {
|
|||||||
const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(strictOutputSchema(schema))}`
|
const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(strictOutputSchema(schema))}`
|
||||||
const { args: finalArgs, input } = deliverPrompt(entry, entry.invoke.slice(1), full)
|
const { args: finalArgs, input } = deliverPrompt(entry, entry.invoke.slice(1), full)
|
||||||
const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json` })
|
const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-json` })
|
||||||
if (res.status !== 0) throw new Error(procError(`${provider} json`, res))
|
if (res.status !== 0) throw procError(`${provider} json`, res)
|
||||||
const output = extractJson(unwrap(res.stdout))
|
const output = extractJson(unwrap(res.stdout))
|
||||||
assertSchema(output, strictOutputSchema(schema))
|
assertSchema(output, strictOutputSchema(schema))
|
||||||
return output
|
return output
|
||||||
@@ -354,24 +348,7 @@ async function jsonOnce(provider, prompt, schema, opts) {
|
|||||||
// degrade gracefully). Provider via opts.provider or MNEMAZINE_LLM; on failure
|
// degrade gracefully). Provider via opts.provider or MNEMAZINE_LLM; on failure
|
||||||
// walks the capability-filtered fallback chain.
|
// walks the capability-filtered fallback chain.
|
||||||
export async function llmJson(prompt, schema, opts = {}) {
|
export async function llmJson(prompt, schema, opts = {}) {
|
||||||
const provider = activeProvider(opts)
|
return dispatch(opts, (candidate, callOpts) => jsonOnce(candidate, prompt, schema, callOpts))
|
||||||
const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
|
|
||||||
let lastError
|
|
||||||
for (const candidate of chain) {
|
|
||||||
try {
|
|
||||||
const result = await jsonOnce(candidate, prompt, schema, opts)
|
|
||||||
// Surface the ACTUAL executor next to the result (not the requested one).
|
|
||||||
// A silent fallback is now observable: the caller can print provider_used
|
|
||||||
// and see that `deadcli` was answered by `claude`.
|
|
||||||
opts.provider_used = candidate
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
catch (error) {
|
|
||||||
lastError = error
|
|
||||||
progress(opts.label || 'json', `fallback ${candidate}: ${String(error.message || error).slice(0, 160)}`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw lastError || new Error('no provider available for llmJson')
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- plain-text path (no schema; vision/extraction fallback) ------------------
|
// --- plain-text path (no schema; vision/extraction fallback) ------------------
|
||||||
@@ -385,7 +362,7 @@ async function textOnce(provider, prompt, opts) {
|
|||||||
args = insertCwd(args, opts.cwd || process.cwd())
|
args = insertCwd(args, opts.cwd || process.cwd())
|
||||||
args = [...args, '-']
|
args = [...args, '-']
|
||||||
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-text${needsWebTools(opts) ? ':search' : ''}` })
|
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-text${needsWebTools(opts) ? ':search' : ''}` })
|
||||||
if (res.status !== 0) throw new Error(procError(`${provider} exec`, res))
|
if (res.status !== 0) throw procError(`${provider} exec`, res)
|
||||||
return String(res.stdout || '').trim()
|
return String(res.stdout || '').trim()
|
||||||
}
|
}
|
||||||
// Flat-invoke CLI (claude inline / kimi in-prompt): tools via --allowedTools
|
// Flat-invoke CLI (claude inline / kimi in-prompt): tools via --allowedTools
|
||||||
@@ -394,24 +371,55 @@ async function textOnce(provider, prompt, opts) {
|
|||||||
if (adapter === 'json_schema_inline') args = withAllowedTools(args, opts)
|
if (adapter === 'json_schema_inline') args = withAllowedTools(args, opts)
|
||||||
const { args: finalArgs, input } = deliverPrompt(entry, args, prompt)
|
const { args: finalArgs, input } = deliverPrompt(entry, args, prompt)
|
||||||
const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-text` })
|
const res = await runProc(bin, finalArgs, { input, timeoutMs: opts.timeoutMs || TIMEOUT_MS, label: opts.label || `${provider}-text` })
|
||||||
if (res.status !== 0) throw new Error(procError(`${provider} text`, res))
|
if (res.status !== 0) throw procError(`${provider} text`, res)
|
||||||
return unwrap(res.stdout).trim()
|
return unwrap(res.stdout).trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function llmText(prompt, opts = {}) {
|
export async function llmText(prompt, opts = {}) {
|
||||||
|
return dispatch(opts, (candidate, callOpts) => textOnce(candidate, prompt, callOpts))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function dispatch(opts, invoke) {
|
||||||
const provider = activeProvider(opts)
|
const provider = activeProvider(opts)
|
||||||
|
const dataClass = opts.dataClass || 'infra'
|
||||||
|
const admission = orderCandidates(registry(), { dataClass }).candidates.map(entry => entry.name)
|
||||||
|
opts.attempts = []
|
||||||
|
delete opts.provider_used
|
||||||
|
// A forbidden explicit/owner-pinned primary is a policy error, never a
|
||||||
|
// reason to move private material to a more permissive cloud provider.
|
||||||
|
if (!admission.includes(provider)) {
|
||||||
|
opts.attempts.push({ provider, status: 'denied', reason: 'privacy' })
|
||||||
|
throw new Error(`Provider ${provider} is not admitted for data class ${dataClass}`)
|
||||||
|
}
|
||||||
|
const caps = [...(opts.capabilities || []), ...(needsWebTools(opts) ? ['web_search'] : [])]
|
||||||
|
const allowed = orderCandidates(registry(), { dataClass, capabilities: caps, tier: opts.tier }).candidates
|
||||||
|
.filter(entry => pickSchemaAdapter(entry)).map(entry => entry.name)
|
||||||
const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
|
const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
|
||||||
|
const requestedBudget = Number(opts.totalTimeoutMs ?? process.env.MNEMAZINE_LLM_CHAIN_TIMEOUT_MS ?? TIMEOUT_MS)
|
||||||
|
const deadline = Date.now() + Math.max(1, Math.min(Number.isFinite(requestedBudget) ? requestedBudget : 420000, 1800000))
|
||||||
let lastError
|
let lastError
|
||||||
for (const candidate of chain) {
|
for (const candidate of chain) {
|
||||||
|
if (!allowed.includes(candidate)) { opts.attempts.push({ provider: candidate, status: 'skipped', reason: 'capability_or_tier' }); continue }
|
||||||
|
const cooling = readCooldown(candidate)
|
||||||
|
if (cooling) { opts.attempts.push({ provider: candidate, status: 'skipped', reason: cooling.reason, until: cooling.until }); continue }
|
||||||
|
const remaining = deadline - Date.now()
|
||||||
|
if (remaining <= 0) { lastError = new Error('CLI chain time budget exhausted'); break }
|
||||||
try {
|
try {
|
||||||
const result = await textOnce(candidate, prompt, opts)
|
const perCall = Number(opts.timeoutMs || TIMEOUT_MS)
|
||||||
opts.provider_used = candidate // actual executor, so a fallback is never silent
|
const result = await invoke(candidate, { ...opts, timeoutMs: Math.max(1, Math.min(Number.isFinite(perCall) ? perCall : remaining, remaining)) })
|
||||||
|
opts.attempts.push({ provider: candidate, status: 'completed' })
|
||||||
|
opts.provider_used = candidate
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
catch (error) {
|
catch (error) {
|
||||||
lastError = error
|
const reason = error.reason || 'invalid_output_or_unavailable'
|
||||||
progress(opts.label || 'text', `fallback ${candidate}: ${String(error.message || error).slice(0, 160)}`)
|
// Provider stderr and malformed output may echo the original document.
|
||||||
|
// Return only a category across the bridge, including on final failure.
|
||||||
|
lastError = Object.assign(new Error(`CLI ${candidate} failed: ${reason}`), { reason })
|
||||||
|
const cooling = recordCooldown(candidate, reason, { retryAfterMs: error.retryAfterMs })
|
||||||
|
opts.attempts.push({ provider: candidate, status: 'failed', reason, ...(cooling ? { until: cooling.until } : {}) })
|
||||||
|
progress(opts.label || 'llm', `fallback ${candidate}: ${reason}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw lastError || new Error('no provider available for llmText')
|
throw lastError || new Error('No admitted CLI available: missing capability or active cooldown')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
// Coordinator-only bridge. The god sandbox must not expose this CLI or the jobs root.
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { parseArgs } from 'node:util';
|
||||||
|
|
||||||
|
const jobsCLI = fileURLToPath(new URL('./mnemazine-jobs.mjs', import.meta.url));
|
||||||
|
const MAX_BYTES = 256 * 1024;
|
||||||
|
const token = /^[a-z0-9][a-z0-9_-]{0,127}$/i;
|
||||||
|
|
||||||
|
function core(root, args) {
|
||||||
|
try {
|
||||||
|
return JSON.parse(execFileSync(process.execPath, [jobsCLI, ...args, '--root', root], {
|
||||||
|
encoding: 'utf8', maxBuffer: 8 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
}));
|
||||||
|
} catch {
|
||||||
|
// Core stderr may contain vault paths or source text; only coordinator diagnostics may expose it.
|
||||||
|
throw new Error('JOBS_ERROR: операция очереди не выполнена; проверьте журнал координатора');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function view(job) {
|
||||||
|
return { job: {
|
||||||
|
id: job.id, kind: job.kind, status: job.status, provenance: job.provenance,
|
||||||
|
created_at: job.created_at, updated_at: job.updated_at,
|
||||||
|
// Ingest logs can mention unrelated vault material. Return a receipt, never those logs.
|
||||||
|
result: job.status === 'completed' ? { accepted: true } : null,
|
||||||
|
citations: [], error: job.error ? 'Обработка не завершена; подробности у координатора' : null,
|
||||||
|
} };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function runAdapter(argv) {
|
||||||
|
const { values: v, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
|
||||||
|
root: { type: 'string' }, god: { type: 'string' }, run: { type: 'string' },
|
||||||
|
project: { type: 'string' }, worktree: { type: 'string' }, file: { type: 'string' },
|
||||||
|
id: { type: 'string' }, query: { type: 'string' }, mode: { type: 'string' }, 'no-start': { type: 'boolean' },
|
||||||
|
} });
|
||||||
|
const [command] = positionals;
|
||||||
|
if (positionals.length !== 1 || !['submit', 'status', 'cancel', 'retry', 'search', 'brief'].includes(command)) {
|
||||||
|
throw new Error('Ожидается submit, status, cancel, retry, search или brief');
|
||||||
|
}
|
||||||
|
if (!v.root || !isAbsolute(v.root)) throw new Error('--root должен быть абсолютным путём очереди координатора');
|
||||||
|
for (const key of ['god', 'run', 'project']) {
|
||||||
|
if (!token.test(v[key] ?? '')) throw new Error(`Некорректный --${key}`);
|
||||||
|
}
|
||||||
|
const provenance = { client: 'olympuz', god: v.god, run: v.run, project: v.project };
|
||||||
|
if (command === 'search' || command === 'brief') {
|
||||||
|
throw new Error('PROJECT_SCOPE_UNAVAILABLE: поиск для богов закрыт до проверки доступа к корпусу проекта');
|
||||||
|
}
|
||||||
|
if (command !== 'submit') {
|
||||||
|
if (!v.id) throw new Error('Требуется --id');
|
||||||
|
const { job } = core(v.root, ['status', '--id', v.id, '--no-start']);
|
||||||
|
if (job.kind !== 'ingest' || Object.entries(provenance).some(([key, value]) => job.provenance?.[key] !== value)) {
|
||||||
|
throw new Error('JOB_SCOPE_MISMATCH: задача не принадлежит этому запуску бога');
|
||||||
|
}
|
||||||
|
return view(command === 'status' ? job : core(v.root, [command, '--id', v.id, ...(v['no-start'] ? ['--no-start'] : [])]).job);
|
||||||
|
}
|
||||||
|
if (!v.worktree || !isAbsolute(v.worktree) || !v.file || !isAbsolute(v.file)) {
|
||||||
|
throw new Error('Требуются абсолютные --worktree и --file');
|
||||||
|
}
|
||||||
|
if (v.mode !== 'deep') throw new Error('Требуется --mode deep: intake использует внешний конвейер; разрешение задаёт координатор');
|
||||||
|
const worktree = realpathSync(v.worktree);
|
||||||
|
const research = join(worktree, 'research');
|
||||||
|
const source = join(realpathSync(dirname(v.file)), basename(v.file));
|
||||||
|
const name = basename(source);
|
||||||
|
if (!/^agent-research--[a-z0-9][a-z0-9-]*--[a-z0-9][a-z0-9-]*\.md$/.test(name)
|
||||||
|
|| !name.startsWith(`agent-research--${v.project}--`)
|
||||||
|
|| dirname(source) !== research || lstatSync(research).isSymbolicLink()) {
|
||||||
|
throw new Error('SOURCE_SCOPE_MISMATCH: нужен agent-research--PROJECT--SLUG.md в worktree/research');
|
||||||
|
}
|
||||||
|
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||||
|
let content;
|
||||||
|
try {
|
||||||
|
const stat = fstatSync(fd);
|
||||||
|
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_BYTES || realpathSync(research) !== research) {
|
||||||
|
throw new Error('Источник должен быть обычным файлом без ссылок, не больше 256 KiB');
|
||||||
|
}
|
||||||
|
const buffer = Buffer.alloc(MAX_BYTES + 1);
|
||||||
|
let bytes = 0;
|
||||||
|
while (bytes < buffer.length) {
|
||||||
|
const read = readSync(fd, buffer, bytes, buffer.length - bytes, null);
|
||||||
|
if (!read) break;
|
||||||
|
bytes += read;
|
||||||
|
}
|
||||||
|
if (bytes > MAX_BYTES) throw new Error('Источник превышает 256 KiB');
|
||||||
|
content = buffer.subarray(0, bytes);
|
||||||
|
} finally { closeSync(fd); }
|
||||||
|
// ponytail: a private temporary snapshot closes the god-file mutation window; core owns persistence.
|
||||||
|
const stage = mkdtempSync(join(tmpdir(), 'mnemazine-olympuz-'));
|
||||||
|
try {
|
||||||
|
const snapshot = join(stage, name);
|
||||||
|
// Delivery time lives in job.created_at; stable source bytes preserve core deduplication on retries.
|
||||||
|
const stamp = `<!-- olympuz: god=${v.god} run=${v.run} project=${v.project} -->\n`;
|
||||||
|
writeFileSync(snapshot, Buffer.concat([Buffer.from(stamp), content]), { mode: 0o600 });
|
||||||
|
const { job } = core(v.root, ['submit', '--kind', 'ingest', '--mode', 'deep', '--file', snapshot,
|
||||||
|
'--project', v.project, '--provenance', JSON.stringify(provenance), ...(v['no-start'] ? ['--no-start'] : [])]);
|
||||||
|
return view(job);
|
||||||
|
} finally { rmSync(stage, { recursive: true, force: true }); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
try { console.log(JSON.stringify(runAdapter(process.argv.slice(2)))); }
|
||||||
|
catch (error) { console.error(JSON.stringify({ error: error.message })); process.exitCode = 1; }
|
||||||
|
}
|
||||||
@@ -200,6 +200,7 @@ async function demoSmoke() {
|
|||||||
// Список копирования ручной, и врезка Метиды его не пополнила - гейт краснел на исправном коде.
|
// Список копирования ручной, и врезка Метиды его не пополнила - гейт краснел на исправном коде.
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-metiz.mjs'), path.join(scripts, 'mnemazine-metiz.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-metiz.mjs'), path.join(scripts, 'mnemazine-metiz.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs'))
|
||||||
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-runtime.mjs'), path.join(scripts, 'mnemazine-cli-runtime.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-probe.mjs'), path.join(scripts, 'mnemazine-cli-probe.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-probe.mjs'), path.join(scripts, 'mnemazine-cli-probe.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
|
||||||
@@ -208,7 +209,7 @@ async function demoSmoke() {
|
|||||||
await fs.copyFile(path.join(ROOT, 'config/project-categories.json'), path.join(config, 'project-categories.json'))
|
await fs.copyFile(path.join(ROOT, 'config/project-categories.json'), path.join(config, 'project-categories.json'))
|
||||||
await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8')
|
await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8')
|
||||||
|
|
||||||
await must('demo intake smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
|
const mixedRun = await run(process.execPath, ['scripts/mnemazine-run.mjs'], {
|
||||||
env: {
|
env: {
|
||||||
MNEMAZINE_ROOT: temp,
|
MNEMAZINE_ROOT: temp,
|
||||||
MNEMAZINE_INBOX: inbox,
|
MNEMAZINE_INBOX: inbox,
|
||||||
@@ -220,10 +221,18 @@ async function demoSmoke() {
|
|||||||
MNEMAZINE_FINISH: '0'
|
MNEMAZINE_FINISH: '0'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
if (mixedRun.code === 0) throw new Error('demo smoke failed: mixed batch with unextractable input passed')
|
||||||
|
if (!existsSync(path.join(inbox, 'example-guide.md')) || !existsSync(path.join(inbox, 'empty-source.bin'))) throw new Error('demo smoke failed: failed batch archived an input')
|
||||||
|
if ((await listFiles(path.join(temp, '.mnemazine/archive'))).length) throw new Error('demo smoke failed: failed batch must archive nothing')
|
||||||
|
// Isolate the rejected fixture; only the now-complete batch may archive.
|
||||||
|
await fs.rename(path.join(inbox, 'empty-source.bin'), path.join(temp, 'empty-source.bin'))
|
||||||
|
await must('demo validated-source archive smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
|
||||||
|
env: { MNEMAZINE_ROOT: temp, MNEMAZINE_INBOX: inbox, MNEMAZINE_VAULT: vault, MNEMAZINE_FINISH: '0' }
|
||||||
|
})
|
||||||
|
|
||||||
const inboxFiles = await fs.readdir(inbox)
|
const inboxFiles = await fs.readdir(inbox)
|
||||||
if (inboxFiles.length !== 1 || inboxFiles[0] !== 'empty-source.bin') {
|
if (inboxFiles.length !== 0) {
|
||||||
throw new Error(`demo smoke failed: expected only unextractable source in inbox (${inboxFiles.join(', ')})`)
|
throw new Error(`demo smoke failed: expected validated inbox to be empty (${inboxFiles.join(', ')})`)
|
||||||
}
|
}
|
||||||
|
|
||||||
const notes = (await listFiles(vault))
|
const notes = (await listFiles(vault))
|
||||||
@@ -259,8 +268,8 @@ async function demoSmoke() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
const cachedInboxFiles = await fs.readdir(inbox)
|
const cachedInboxFiles = await fs.readdir(inbox)
|
||||||
if (cachedInboxFiles.length !== 1 || cachedInboxFiles[0] !== 'empty-source.bin') {
|
if (cachedInboxFiles.length !== 0) {
|
||||||
throw new Error(`demo cached smoke failed: expected only unextractable source in inbox (${cachedInboxFiles.join(', ')})`)
|
throw new Error(`demo cached smoke failed: expected validated inbox to be empty (${cachedInboxFiles.join(', ')})`)
|
||||||
}
|
}
|
||||||
const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive'))
|
const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive'))
|
||||||
if (archivedAfterCachedRun.length !== 2) throw new Error(`demo cached smoke failed: expected 2 archived finalized sources, got ${archivedAfterCachedRun.length}`)
|
if (archivedAfterCachedRun.length !== 2) throw new Error(`demo cached smoke failed: expected 2 archived finalized sources, got ${archivedAfterCachedRun.length}`)
|
||||||
@@ -286,6 +295,7 @@ async function strictArchiveGateSmoke() {
|
|||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), path.join(scripts, 'mnemazine-humanize-gate.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), path.join(scripts, 'mnemazine-humanize-gate.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-human-layer-gate.mjs'), path.join(scripts, 'mnemazine-human-layer-gate.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-human-layer-gate.mjs'), path.join(scripts, 'mnemazine-human-layer-gate.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs'))
|
||||||
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-runtime.mjs'), path.join(scripts, 'mnemazine-cli-runtime.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-probe.mjs'), path.join(scripts, 'mnemazine-cli-probe.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-probe.mjs'), path.join(scripts, 'mnemazine-cli-probe.mjs'))
|
||||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
|
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
|
||||||
@@ -390,7 +400,35 @@ Local source refs:
|
|||||||
|
|
||||||
- Держать эту ноту как smoke fixture для strict archive gate.
|
- Держать эту ноту как smoke fixture для strict archive gate.
|
||||||
`)
|
`)
|
||||||
await must('strict archive gate smoke:good', process.execPath, ['scripts/mnemazine-run.mjs'], {
|
const noCompletion = await run(process.execPath, ['scripts/mnemazine-run.mjs'], {
|
||||||
|
env: { MNEMAZINE_ROOT: goodTemp, MNEMAZINE_INBOX: good.inbox, MNEMAZINE_VAULT: good.vault,
|
||||||
|
MNEMAZINE_DEEP: '1', MNEMAZINE_REQUIRE_DEEP: '1', MNEMAZINE_SYNTHESIZE: '0', MNEMAZINE_FINISH: '0' }
|
||||||
|
})
|
||||||
|
if (noCompletion.code === 0 || !existsSync(good.sourceFile)) throw new Error('strict archive gate smoke failed: cached knowledge without completion must retain source')
|
||||||
|
if (!`${noCompletion.stdout}\n${noCompletion.stderr}`.includes('completion failed before archive')) throw new Error('strict archive gate smoke failed: expected explicit missing-completion rejection')
|
||||||
|
// Strict cached intake still requires real completion gates with FINISH=0.
|
||||||
|
// Supply measured fixture baseline and truthful fixture reports, never a PASS shim.
|
||||||
|
for (const name of ['complete-check', 'coverage-check', 'spec-ceiling', 'report-quality-gate']) {
|
||||||
|
await fs.copyFile(path.join(ROOT, `scripts/mnemazine-${name}.mjs`), path.join(goodTemp, `scripts/mnemazine-${name}.mjs`))
|
||||||
|
}
|
||||||
|
const goodState = path.join(goodTemp, '.mnemazine/state')
|
||||||
|
const goodReports = path.join(goodTemp, 'reports')
|
||||||
|
await fs.mkdir(goodState, { recursive: true })
|
||||||
|
await fs.mkdir(goodReports, { recursive: true })
|
||||||
|
await fs.mkdir(path.join(good.vault, '99 Система'), { recursive: true })
|
||||||
|
await fs.writeFile(path.join(good.vault, '99 Система/_ПРОЕКТЫ.md'), '# Проекты тестовой базы\n\n## Мнемозина\n\nЛокальная проверка конвейера.\n', 'utf8')
|
||||||
|
await must('strict fixture measured baseline', process.execPath, [path.join(goodTemp, 'scripts/mnemazine-spec-ceiling.mjs'), '--update', '--vault', good.vault], {
|
||||||
|
env: { MNEMAZINE_ROOT: goodTemp, MNEMAZINE_VAULT: good.vault }
|
||||||
|
})
|
||||||
|
await fs.writeFile(path.join(goodReports, 'visual-knowledge-report.html'), `<!doctype html><html lang="ru"><body>
|
||||||
|
<h1>Отчет Mnemazine</h1><h2>Новые и обновленные знания</h2>
|
||||||
|
<p>Синтез: тестовый материал описывает преобразование документов в текст и сохраняет ссылки на происхождение. Эта фикстура проверяет порядок завершения локального конвейера и не представляет результат нового внешнего исследования.</p>
|
||||||
|
<h2>Источники</h2><a href="https://github.com/microsoft/markitdown">Репозиторий</a><a href="https://github.com/microsoft/markitdown/issues">Обсуждения</a><a href="https://github.com/microsoft/markitdown/releases">Выпуски</a>
|
||||||
|
<h2>Применение</h2><p>Проверить сохранность источника до успешного завершения всех обязательных проверок.</p>
|
||||||
|
<h2>Проверка</h2><p>Используется заранее подготовленная локальная тестовая запись. Сетевые запросы и обращения к модели в этой проверке не выполняются.</p>
|
||||||
|
<h2>Следующее действие</h2><p>После успешной проверки перенести только покрытый тестовый источник в архив.</p></body></html>`, 'utf8')
|
||||||
|
await fs.writeFile(path.join(goodState, 'last-action-brief.md'), '# Короткий отчет Mnemazine\n\n## Статус\n\nПодготовлена локальная фикстура проверки очередности архивирования.\n\n## Следующие действия\n\nЗавершить проверки и сохранить источник при любом отказе.\n', 'utf8')
|
||||||
|
await must('strict archive gate smoke:real-completion', process.execPath, ['scripts/mnemazine-run.mjs'], {
|
||||||
env: {
|
env: {
|
||||||
MNEMAZINE_ROOT: goodTemp,
|
MNEMAZINE_ROOT: goodTemp,
|
||||||
MNEMAZINE_INBOX: good.inbox,
|
MNEMAZINE_INBOX: good.inbox,
|
||||||
@@ -694,7 +732,8 @@ async function completeGateSmoke() {
|
|||||||
}, null, 2), 'utf8')
|
}, null, 2), 'utf8')
|
||||||
// Потолок спеки для демо-корпуса (план П06 шаг 8): единственная демо-нота спеке
|
// Потолок спеки для демо-корпуса (план П06 шаг 8): единственная демо-нота спеке
|
||||||
// не отвечает, потолок честно равен 1 — spec-ceiling --check из complete-check
|
// не отвечает, потолок честно равен 1 — spec-ceiling --check из complete-check
|
||||||
// держится, а не краснеет. Пишется во временный MNEMAZINE_STATE, не в репозиторий.
|
// держится, а не краснеет. Runtime state изолирован; путь fixture baseline
|
||||||
|
// передается явно, чтобы не выбирать baseline другого (живого) корпуса.
|
||||||
await fs.writeFile(path.join(state, 'spec-ceiling.json'), JSON.stringify({
|
await fs.writeFile(path.join(state, 'spec-ceiling.json'), JSON.stringify({
|
||||||
vault: path.join(ROOT, 'demo/vault'),
|
vault: path.join(ROOT, 'demo/vault'),
|
||||||
ceiling: 1
|
ceiling: 1
|
||||||
@@ -704,7 +743,8 @@ async function completeGateSmoke() {
|
|||||||
MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'),
|
MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'),
|
||||||
MNEMAZINE_INBOX: inbox,
|
MNEMAZINE_INBOX: inbox,
|
||||||
MNEMAZINE_REPORTS: reports,
|
MNEMAZINE_REPORTS: reports,
|
||||||
MNEMAZINE_STATE: state
|
MNEMAZINE_STATE: state,
|
||||||
|
MNEMAZINE_SPEC_CEILING: path.join(state, 'spec-ceiling.json')
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -924,6 +964,13 @@ async function searchEvalSmoke() {
|
|||||||
// (LLM judge) is opt-in via `npm run search:eval -- --deep`, not in the gate.
|
// (LLM judge) is opt-in via `npm run search:eval -- --deep`, not in the gate.
|
||||||
await must('kb-search selftest', process.execPath, ['scripts/mnemazine-kb-search.mjs', '--selftest'])
|
await must('kb-search selftest', process.execPath, ['scripts/mnemazine-kb-search.mjs', '--selftest'])
|
||||||
await must('kb-search eval (Tier A)', process.execPath, ['tests/search-eval.mjs'])
|
await must('kb-search eval (Tier A)', process.execPath, ['tests/search-eval.mjs'])
|
||||||
|
await must('kb-search evidence regressions', process.execPath, ['tests/test-search-evidence.mjs'])
|
||||||
|
await must('durable jobs', process.execPath, ['tests/test-jobs.mjs'])
|
||||||
|
await must('CLI failover', process.execPath, ['tests/test-cli-failover.mjs'])
|
||||||
|
await must('prearchive validation', process.execPath, ['tests/test-prearchive-validation.mjs'])
|
||||||
|
await must('coverage hash', process.execPath, ['tests/test-coverage-hash.mjs'])
|
||||||
|
await must('shared vault lock', process.execPath, ['tests/test-vault-lock.mjs'])
|
||||||
|
await must('Olympuz jobs adapter', process.execPath, ['tests/test-olympuz-adapter.mjs'])
|
||||||
}
|
}
|
||||||
|
|
||||||
async function repoMetadataCheck() {
|
async function repoMetadataCheck() {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { llmAvailable, llmText } from './mnemazine-llm.mjs'
|
|||||||
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
|
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
|
||||||
import { resolveVault } from './mnemazine-paths.mjs'
|
import { resolveVault } from './mnemazine-paths.mjs'
|
||||||
import { requireEngines } from './mnemazine-local-engines.mjs'
|
import { requireEngines } from './mnemazine-local-engines.mjs'
|
||||||
|
import { acquireVaultLock } from './mnemazine-vault-lock.mjs'
|
||||||
|
|
||||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||||
|
|
||||||
@@ -690,8 +691,8 @@ function finishGateOk(key, entry) {
|
|||||||
|
|
||||||
// result.ok больше не литерал: прогон зеленый только если ноль файлов упало И
|
// result.ok больше не литерал: прогон зеленый только если ноль файлов упало И
|
||||||
// каждый обязательный элемент finish.* в легальном состоянии. Коды гейтов,
|
// каждый обязательный элемент finish.* в легальном состоянии. Коды гейтов,
|
||||||
// собранные finishRun, наконец читаются — до архива они решали, после архива
|
// собранные finishRun, должны пройти до переноса оригиналов в архив.
|
||||||
// теперь не «советуют», а считаются. finish === null (черновая ветка/FINISH=0):
|
// finish === null (черновая ветка/FINISH=0):
|
||||||
// решает только failed.
|
// решает только failed.
|
||||||
function computeRunOk(failed, finish) {
|
function computeRunOk(failed, finish) {
|
||||||
if (Number(failed || 0) !== 0) return false
|
if (Number(failed || 0) !== 0) return false
|
||||||
@@ -703,6 +704,14 @@ function computeRunOk(failed, finish) {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function archiveAfterValidation({ failed, finish, validate, items, archive = archiveFile }) {
|
||||||
|
if (!computeRunOk(failed, finish)) throw new Error('final validation failed before archive')
|
||||||
|
await validate()
|
||||||
|
const archived = []
|
||||||
|
for (const item of items) archived.push(await archive(item.file, item.hash))
|
||||||
|
return archived
|
||||||
|
}
|
||||||
|
|
||||||
async function finishRun(runStartedAt) {
|
async function finishRun(runStartedAt) {
|
||||||
const result = {}
|
const result = {}
|
||||||
result.tool_queue = runLocalNodeScript('mnemazine-tool-decision-queue.mjs', ['--changed-since', runStartedAt, '--session', new Date().toISOString().slice(0, 10)])
|
result.tool_queue = runLocalNodeScript('mnemazine-tool-decision-queue.mjs', ['--changed-since', runStartedAt, '--session', new Date().toISOString().slice(0, 10)])
|
||||||
@@ -953,9 +962,21 @@ async function main() {
|
|||||||
}, human.status || 1)
|
}, human.status || 1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const archived = []
|
|
||||||
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
|
|
||||||
const finish = FINISH ? await finishRun(runStartedAt) : { skipped: true }
|
const finish = FINISH ? await finishRun(runStartedAt) : { skipped: true }
|
||||||
|
const pending = { ok: false, phase: 'pending_archive', pre_archive_ready: computeRunOk(failed, finish), archive_pending: toArchive.length, archived: 0, inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt }
|
||||||
|
await writeRunState(pending)
|
||||||
|
let archived
|
||||||
|
try {
|
||||||
|
archived = await archiveAfterValidation({ failed, finish, items: toArchive, validate: async () => {
|
||||||
|
if (!FINISH && !REQUIRE_DEEP) return
|
||||||
|
const check = runLocalNodeScript('mnemazine-complete-check.mjs', ['--before-archive', ...(REQUIRE_DEEP ? ['--require-deep'] : [])])
|
||||||
|
if (!check.ok) throw new Error(`completion failed before archive: ${check.stderr || check.stdout || check.reason || 'unknown error'}`)
|
||||||
|
} })
|
||||||
|
} catch (error) {
|
||||||
|
await writeRunState({ ...pending, pre_archive_ready: false, failure: error.message, finished_at: new Date().toISOString() })
|
||||||
|
console.error(error.message)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
const result = { ok: computeRunOk(failed, finish), inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
|
const result = { ok: computeRunOk(failed, finish), inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
|
||||||
await writeRunState(result)
|
await writeRunState(result)
|
||||||
console.log(JSON.stringify(result, null, 2))
|
console.log(JSON.stringify(result, null, 2))
|
||||||
@@ -965,8 +986,11 @@ async function main() {
|
|||||||
// а не импортируется. Импорт нужен пробе runLocalNodeScript (harness на две строки)
|
// а не импортируется. Импорт нужен пробе runLocalNodeScript (harness на две строки)
|
||||||
// и любому будущему потребителю экспортов — он не должен гонять пайплайн.
|
// и любому будущему потребителю экспортов — он не должен гонять пайплайн.
|
||||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
main().catch(err => {
|
Promise.resolve().then(async () => {
|
||||||
|
const release = acquireVaultLock(VAULT)
|
||||||
|
try { await main() } finally { release() }
|
||||||
|
}).catch(err => {
|
||||||
console.error(err)
|
console.error(err)
|
||||||
process.exit(1)
|
process.exit(err.code === 'MNEMAZINE_VAULT_BUSY' ? 75 : 1)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -721,7 +721,7 @@ ${sourceLines.join('\n')}
|
|||||||
- ${template.next}
|
- ${template.next}
|
||||||
- Тема: ${clusterTitleRu(cluster.id)} — черновик собран, но требует проверки перед применением.
|
- Тема: ${clusterTitleRu(cluster.id)} — черновик собран, но требует проверки перед применением.
|
||||||
|
|
||||||
## Достоверность
|
## Проверка
|
||||||
|
|
||||||
- **Автоматический fact-check не запускался.** Это unverified synthesis cluster (\`status: draft\`). URL из extraction или topic hints - указатели, не подтверждение конкретного claim.
|
- **Автоматический fact-check не запускался.** Это unverified synthesis cluster (\`status: draft\`). URL из extraction или topic hints - указатели, не подтверждение конкретного claim.
|
||||||
- Повышать до \`status: final\` только после проверки человеком или verify gate по primary sources.
|
- Повышать до \`status: final\` только после проверки человеком или verify gate по primary sources.
|
||||||
@@ -1019,7 +1019,7 @@ ${addedFacts}
|
|||||||
- ${compact(atom.next, 240) || 'Применить в ближайшей задаче по теме кластера.'}
|
- ${compact(atom.next, 240) || 'Применить в ближайшей задаче по теме кластера.'}
|
||||||
- Тема: ${clusterTitleRu(cluster.id)} — смотреть сюда, когда всплывет этот вопрос.
|
- Тема: ${clusterTitleRu(cluster.id)} — смотреть сюда, когда всплывет этот вопрос.
|
||||||
|
|
||||||
## Достоверность
|
## Проверка
|
||||||
|
|
||||||
- Статус проверки: **${v.status}**${v.note ? ` (${v.note})` : ''}.
|
- Статус проверки: **${v.status}**${v.note ? ` (${v.note})` : ''}.
|
||||||
${isVerified
|
${isVerified
|
||||||
@@ -1054,6 +1054,10 @@ if (argv.includes('--selftest')) {
|
|||||||
for (const line of junk) if (!looksLikeCode(line)) throw new Error(`selftest: junk passed the filter: ${line}`)
|
for (const line of junk) if (!looksLikeCode(line)) throw new Error(`selftest: junk passed the filter: ${line}`)
|
||||||
for (const line of prose) if (looksLikeCode(line)) throw new Error(`selftest: prose rejected by the filter: ${line}`)
|
for (const line of prose) if (looksLikeCode(line)) throw new Error(`selftest: prose rejected by the filter: ${line}`)
|
||||||
if (readmePoints(junk.concat(prose).join('\n'), 6).length !== prose.length) throw new Error('selftest: readmePoints kept the wrong lines')
|
if (readmePoints(junk.concat(prose).join('\n'), 6).length !== prose.length) throw new Error('selftest: readmePoints kept the wrong lines')
|
||||||
|
const fixtureCluster = { id: 'misc', records: [{ text: prose.join('\n'), source_ref: 'local-media:fixture' }] }
|
||||||
|
const draft = makeAtomNote(fixtureCluster, { title: 'Проверка заметки', what: prose[0], sources: [] }, { status: 'unknown' })
|
||||||
|
if (!/^## Проверка$/m.test(draft) || !/^## Проверка$/m.test(makeNote(fixtureCluster))) throw new Error('selftest: producer must use the human-layer verification section')
|
||||||
|
if (!draft.includes('verification_status: "unknown"') || !draft.includes('status: "draft"') || draft.includes('Утверждение сверено с указанными источниками')) throw new Error('selftest: section rename must not upgrade unverified facts')
|
||||||
console.log(JSON.stringify({ ok: true, selftest: 'source-scrape junk filter' }))
|
console.log(JSON.stringify({ ok: true, selftest: 'source-scrape junk filter' }))
|
||||||
process.exit(0)
|
process.exit(0)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { realpathSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, rmdirSync } from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { randomUUID } from 'node:crypto'
|
||||||
|
import { spawn, spawnSync } from 'node:child_process'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const ENV = 'MNEMAZINE_VAULT_LOCK'
|
||||||
|
function identity(pid) {
|
||||||
|
const result = spawnSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8' })
|
||||||
|
return result.status === 0 ? result.stdout.trim() : ''
|
||||||
|
}
|
||||||
|
function descendant(pid) {
|
||||||
|
let current = process.pid
|
||||||
|
for (let depth = 0; current > 1 && depth < 128; depth++) {
|
||||||
|
if (current === pid) return true
|
||||||
|
const result = spawnSync('ps', ['-p', String(current), '-o', 'ppid='], { encoding: 'utf8' })
|
||||||
|
current = Number(result.stdout?.trim())
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
function location(vault) {
|
||||||
|
return path.join(realpathSync(vault), '.mnemazine-pipeline-lock')
|
||||||
|
}
|
||||||
|
export function ownsVaultLock(vault) {
|
||||||
|
try {
|
||||||
|
const owner = JSON.parse(readFileSync(path.join(location(vault), 'owner.json'), 'utf8'))
|
||||||
|
return owner.nonce === process.env[ENV] && Number.isInteger(owner.pid) &&
|
||||||
|
owner.start && identity(owner.pid) === owner.start && descendant(owner.pid)
|
||||||
|
} catch { return false }
|
||||||
|
}
|
||||||
|
export function acquireVaultLock(vault) {
|
||||||
|
if (ownsVaultLock(vault)) return () => {}
|
||||||
|
const dir = location(vault)
|
||||||
|
const owner = { pid: process.pid, start: identity(process.pid), nonce: randomUUID() }
|
||||||
|
if (!owner.start) throw new Error('Cannot determine pipeline process identity')
|
||||||
|
try { mkdirSync(dir, { mode: 0o700 }) } catch (error) {
|
||||||
|
if (error.code !== 'EEXIST') throw error
|
||||||
|
// ponytail: never steal stale locks; manual recovery avoids ABA races.
|
||||||
|
const busy = new Error(`Vault pipeline busy or interrupted: ${dir}. Retry after the running pipeline; inspect a stale lock before manual recovery.`)
|
||||||
|
busy.code = 'MNEMAZINE_VAULT_BUSY'
|
||||||
|
throw busy
|
||||||
|
}
|
||||||
|
try { writeFileSync(path.join(dir, 'owner.json'), JSON.stringify(owner), { flag: 'wx', mode: 0o600 }) }
|
||||||
|
catch (error) { try { rmdirSync(dir) } catch {} ; throw error }
|
||||||
|
const previous = process.env[ENV]
|
||||||
|
process.env[ENV] = owner.nonce
|
||||||
|
let released = false
|
||||||
|
const release = () => {
|
||||||
|
if (released) return
|
||||||
|
released = true
|
||||||
|
process.removeListener('exit', release)
|
||||||
|
try {
|
||||||
|
if (JSON.parse(readFileSync(path.join(dir, 'owner.json'), 'utf8')).nonce === owner.nonce) {
|
||||||
|
unlinkSync(path.join(dir, 'owner.json'))
|
||||||
|
rmdirSync(dir)
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
if (previous === undefined) delete process.env[ENV]
|
||||||
|
else process.env[ENV] = previous
|
||||||
|
}
|
||||||
|
// Cancellation can leave grandchildren draining: retain the lock for inspection.
|
||||||
|
release.abandon = () => { released = true; process.removeListener('exit', release) }
|
||||||
|
process.once('exit', release)
|
||||||
|
return release
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
const args = process.argv.slice(2)
|
||||||
|
const vault = args[1]
|
||||||
|
if (args[0] === '--check') process.exit(ownsVaultLock(vault) ? 0 : 1)
|
||||||
|
try {
|
||||||
|
if (args[0] !== '--vault' || args[2] !== '--' || !args[3]) throw new Error('Usage: --vault PATH -- COMMAND [ARGS]')
|
||||||
|
const release = acquireVaultLock(vault)
|
||||||
|
const child = spawn(args[3], args.slice(4), { stdio: 'inherit', env: process.env })
|
||||||
|
// Keep ownership until the child exits, including while cancellation drains it.
|
||||||
|
const signals = ['SIGTERM', 'SIGINT', 'SIGHUP']
|
||||||
|
const handlers = signals.map(signal => () => { release.abandon?.(); child.kill(signal) })
|
||||||
|
signals.forEach((signal, i) => process.on(signal, handlers[i]))
|
||||||
|
const finish = code => {
|
||||||
|
signals.forEach((signal, i) => process.removeListener(signal, handlers[i]))
|
||||||
|
release()
|
||||||
|
process.exitCode = code
|
||||||
|
}
|
||||||
|
child.once('error', error => { console.error(error.message); finish(1) })
|
||||||
|
child.once('exit', (code, signal) => finish(code ?? (signal === 'SIGINT' ? 130 : 143)))
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error.message)
|
||||||
|
process.exitCode = error.code === 'MNEMAZINE_VAULT_BUSY' ? 75 : 1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { discoverProviders, resolveExecutable, readCooldown, recordCooldown, classifyProcessFailure } from '../scripts/mnemazine-cli-runtime.mjs'
|
||||||
|
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-cli-failover-'))
|
||||||
|
const previous = { ...process.env }
|
||||||
|
try {
|
||||||
|
process.env.MNEMAZINE_LLM = 'claude'
|
||||||
|
process.env.MNEMAZINE_LLM_PROGRESS = '0'
|
||||||
|
process.env.MNEMAZINE_CLI_COOLDOWNS = path.join(tmp, 'cooldowns')
|
||||||
|
process.env.FIXTURE_CALLS = path.join(tmp, 'calls')
|
||||||
|
delete process.env.MNEMAZINE_CLI_REGISTRY_LOCAL
|
||||||
|
delete process.env.MNEMAZINE_JOB_GROUPS
|
||||||
|
delete process.env.MNEMAZINE_LLM_FALLBACK
|
||||||
|
const mock = `#!${process.execPath}
|
||||||
|
const fs = require('node:fs'), path = require('node:path');
|
||||||
|
const name = path.basename(process.argv[1]);
|
||||||
|
fs.appendFileSync(process.env.FIXTURE_CALLS, name+'\\n');
|
||||||
|
if(name==='claude' && process.env.FIXTURE_MODE==='timeout') { setInterval(()=>{},1000); }
|
||||||
|
else if(name==='claude' && process.env.FIXTURE_MODE==='quota') { console.error('quota exceeded; private-token-fixture');process.exitCode=1; }
|
||||||
|
else if(name==='claude' && process.env.FIXTURE_MODE==='bad') { console.log('not json'); }
|
||||||
|
else { const value=JSON.stringify({ok:true}); const i=process.argv.indexOf('-o'); if(i>=0)fs.writeFileSync(process.argv[i+1],value); else console.log(value); }
|
||||||
|
`
|
||||||
|
for (const name of ['claude', 'codex', 'kimi']) {
|
||||||
|
const file = path.join(tmp, name); fs.writeFileSync(file, mock, { mode: 0o700 })
|
||||||
|
process.env[`MNEMAZINE_${name.toUpperCase()}_BIN`] = file
|
||||||
|
}
|
||||||
|
const { llmJson, llmText } = await import('../scripts/mnemazine-llm.mjs')
|
||||||
|
const schema = { type: 'object', additionalProperties: false, required: ['ok'], properties: { ok: { type: 'boolean' } } }
|
||||||
|
process.env.FIXTURE_MODE = 'quota'
|
||||||
|
const first = { provider: 'claude', dataClass: 'text' }
|
||||||
|
assert.deepEqual(await llmJson('fixture only', schema, first), { ok: true })
|
||||||
|
assert.equal(first.provider_used, 'kimi')
|
||||||
|
assert.equal(first.attempts[0].reason, 'quota')
|
||||||
|
assert(readCooldown('claude'))
|
||||||
|
const second = { provider: 'claude', dataClass: 'text' }
|
||||||
|
await llmJson('fixture only', schema, second)
|
||||||
|
assert.equal(second.attempts[0].status, 'skipped')
|
||||||
|
assert.equal(fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8').split('\n').filter(x => x === 'claude').length, 1)
|
||||||
|
const before = fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8')
|
||||||
|
for (const call of [() => llmJson('private fixture', schema, { provider: 'kimi', dataClass: 'pd' }),
|
||||||
|
() => llmText('private fixture', { provider: 'codex', dataClass: 'personal' })]) await assert.rejects(call, /not admitted/)
|
||||||
|
assert.equal(fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8'), before, 'denied primary cannot dispatch even a fallback')
|
||||||
|
const web = { provider: 'kimi', dataClass: 'text', capabilities: ['web_search'] }
|
||||||
|
await llmJson('fixture only', schema, web)
|
||||||
|
assert.equal(web.provider_used, 'codex')
|
||||||
|
assert.equal(web.attempts[0].reason, 'capability_or_tier')
|
||||||
|
process.env.MNEMAZINE_CLI_COOLDOWNS = path.join(tmp, 'nonquota')
|
||||||
|
process.env.FIXTURE_MODE = 'bad'
|
||||||
|
const malformed = { provider: 'claude', dataClass: 'text' }
|
||||||
|
await llmJson('fixture', schema, malformed)
|
||||||
|
assert.equal(malformed.provider_used, 'kimi', 'non-quota fallback remains supported')
|
||||||
|
assert.equal(readCooldown('claude'), null)
|
||||||
|
process.env.FIXTURE_MODE = 'timeout'
|
||||||
|
const timing = { provider: 'claude', dataClass: 'text', totalTimeoutMs: 80 }
|
||||||
|
const start = Date.now()
|
||||||
|
await assert.rejects(() => llmJson('fixture', schema, timing))
|
||||||
|
assert(Date.now() - start < 3000)
|
||||||
|
assert.equal(timing.attempts.length, 1, 'budget prevents another provider call')
|
||||||
|
assert.equal(classifyProcessFailure({ status: 0, stdout: 'quota exceeded' }), null)
|
||||||
|
assert.equal(classifyProcessFailure({ status: 1, stderr: 'insufficient permissions' }), 'process_error')
|
||||||
|
assert.equal(classifyProcessFailure({ status: 1, stderr: 'HTTP 429 too many requests' }), 'rate_limit')
|
||||||
|
const dir = path.join(tmp, 'durable')
|
||||||
|
recordCooldown('example', 'quota', { dir, now: 1000 })
|
||||||
|
recordCooldown('example', 'rate_limit', { dir, now: 2000 })
|
||||||
|
assert.equal(readCooldown('example', { dir, now: 3000 }).reason, 'quota', 'shorter concurrent record cannot downgrade cooldown')
|
||||||
|
assert.equal(readCooldown('example', { dir, now: 100000000 }), null)
|
||||||
|
const weird = path.join(tmp, 'binary with spaces;$(touch unsafe)')
|
||||||
|
fs.writeFileSync(weird, mock, { mode: 0o700 })
|
||||||
|
assert.equal(resolveExecutable(weird), weird)
|
||||||
|
assert.equal(resolveExecutable('$(touch should-not-exist)', { env: { PATH: tmp }, home: tmp }), null)
|
||||||
|
fs.writeFileSync(path.join(tmp, 'gemini'), mock, { mode: 0o700 })
|
||||||
|
const listed = discoverProviders({ env: { ...process.env, PATH: tmp }, home: tmp })
|
||||||
|
assert(listed.some(item => item.name === 'gemini' && item.installed && !item.supported))
|
||||||
|
assert(!JSON.stringify(listed).includes('private-token-fixture'))
|
||||||
|
assert.equal(fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8').includes('gemini'), false, 'discovery executes no CLI')
|
||||||
|
console.log('CLI failover: admission, quota, shared cooldown, capabilities, deadline, safe discovery passed')
|
||||||
|
} finally {
|
||||||
|
for (const key of Object.keys(process.env)) if (!(key in previous)) delete process.env[key]
|
||||||
|
Object.assign(process.env, previous)
|
||||||
|
fs.rmSync(tmp, { recursive: true, force: true })
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { createHash } from 'node:crypto'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const script = fileURLToPath(new URL('../scripts/mnemazine-coverage-check.mjs', import.meta.url))
|
||||||
|
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-coverage-hash-'))
|
||||||
|
try {
|
||||||
|
const vault = path.join(temp, 'vault'), inbox = path.join(temp, 'inbox')
|
||||||
|
fs.mkdirSync(vault); fs.mkdirSync(inbox)
|
||||||
|
const source = path.join(inbox, 'renamed-source.txt')
|
||||||
|
const data = 'Fixture source content for independently calculated SHA-256 coverage.'
|
||||||
|
fs.writeFileSync(source, data)
|
||||||
|
const hash = createHash('sha256').update(data).digest('hex')
|
||||||
|
const note = `---\nstatus: "final"\nverified: подтвержден\nverification_status: "verified"\nenrichment: "external-research"\n---\n# Проверенная фикстура\n\n## Источники\n\nlocal-media:${hash.slice(0, 16)}\n\nПубличные источники:\n- https://example.com/source\n\n## Расширение знания\n\nФакты, добавленные до атомизации:\n- Первый проверенный факт фикстуры.\n- Второй проверенный факт фикстуры.\n`
|
||||||
|
const file = path.join(vault, 'knowledge.md')
|
||||||
|
const check = () => spawnSync(process.execPath, [script, '--vault', vault, '--inbox', inbox, '--json'], { encoding: 'utf8', timeout: 5000 })
|
||||||
|
fs.writeFileSync(file, note)
|
||||||
|
assert.equal(check().status, 0, 'renamed source covered by matching verified SHA-256 source_ref')
|
||||||
|
fs.writeFileSync(source, `${data} changed`)
|
||||||
|
assert.equal(check().status, 1, 'different bytes must not match old hash')
|
||||||
|
fs.writeFileSync(source, data)
|
||||||
|
fs.writeFileSync(file, note.replace('status: "final"', 'status: "draft"'))
|
||||||
|
assert.equal(check().status, 1, 'draft with correct source hash does not prove coverage')
|
||||||
|
fs.writeFileSync(file, note.replace('verified: подтвержден', 'verified: не-проверялось'))
|
||||||
|
assert.equal(check().status, 1, 'unverified source hash must not count')
|
||||||
|
fs.writeFileSync(file, 'Source: renamed-source.txt')
|
||||||
|
assert.equal(check().status, 0, 'existing basename contract remains intact')
|
||||||
|
console.log('coverage hash passed: renamed verified source, changed bytes, draft/unverified rejection, basename compatibility')
|
||||||
|
} finally { fs.rmSync(temp, { recursive: true, force: true }) }
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { spawn, spawnSync } from 'node:child_process'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { JobQueue, pipelineFailure } from '../scripts/mnemazine-jobs.mjs'
|
||||||
|
|
||||||
|
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-jobs-test-'))
|
||||||
|
try {
|
||||||
|
const queue = new JobQueue(path.join(tmp, 'queue'))
|
||||||
|
const textQueue = new JobQueue(path.join(tmp, 'text-queue'))
|
||||||
|
const textInputs = ['https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'https://example.com/article', 'HTTPS://EXAMPLE.COM/article', 'Мнемозина']
|
||||||
|
for (const input of textInputs) {
|
||||||
|
const submitted = await textQueue.submit({ kind: 'ingest', mode: 'deep', text: ` ${input} ` })
|
||||||
|
assert.equal(submitted.input_text, input)
|
||||||
|
assert.equal(submitted.input_kind, /^https:/i.test(input) ? 'url' : 'title')
|
||||||
|
assert.equal((await textQueue.submit({ kind: 'ingest', mode: 'deep', text: input })).id, submitted.id)
|
||||||
|
assert.notEqual((await textQueue.submit({ kind: 'ingest', mode: 'deep', text: input, project: 'other' })).id, submitted.id)
|
||||||
|
assert.equal(submitted.files.length, 1)
|
||||||
|
assert.equal(submitted.files[0].original, undefined)
|
||||||
|
const snapshot = fs.readFileSync(submitted.files[0].snapshot, 'utf8')
|
||||||
|
assert(snapshot.includes(input))
|
||||||
|
if (submitted.input_kind === 'url') assert(snapshot.includes(`Источник: ${new URL(input).href}`))
|
||||||
|
assert.match(snapshot, /Это запрос на исследование, а не готовое знание/)
|
||||||
|
assert(snapshot.length > 80)
|
||||||
|
assert.equal(path.dirname(submitted.files[0].snapshot), path.join(textQueue.root, submitted.id, 'sources'))
|
||||||
|
}
|
||||||
|
for (const input of ['', ' ', 'file:///tmp/private', 'javascript:alert(1)', 'ftp://example.com/file', 'https://user:password@example.com', 'https://', 'https:example.com', 'www.example.com', 'x'.repeat(8193), 'test\u0000']) {
|
||||||
|
await assert.rejects(textQueue.submit({ kind: 'ingest', mode: 'deep', text: input }))
|
||||||
|
}
|
||||||
|
await assert.rejects(textQueue.submit({ kind: 'ingest', mode: 'deep', text: 'Название', files: ['/unused'] }), /either files or text/)
|
||||||
|
await assert.rejects(textQueue.submit({ kind: 'search', query: 'поиск', text: 'Название' }), /no intake inputs/)
|
||||||
|
const original = path.join(tmp, 'source.md')
|
||||||
|
fs.writeFileSync(original, '# Исходный материал\nПамять агентов.')
|
||||||
|
await assert.rejects(queue.submit({ kind: 'ingest', files: [original] }), /deep/)
|
||||||
|
const job = await queue.submit({ kind: 'ingest', mode: 'deep', files: [original, original] })
|
||||||
|
assert.equal(job.files.length, 1)
|
||||||
|
assert.equal((await queue.submit({ kind: 'ingest', mode: 'deep', files: [original] })).id, job.id)
|
||||||
|
fs.writeFileSync(original, 'Изменённый оригинал')
|
||||||
|
assert.match(fs.readFileSync(job.files[0].snapshot, 'utf8'), /Память/)
|
||||||
|
await queue.change(job.id, 'cancel')
|
||||||
|
assert.equal(queue.read(job.id).status, 'cancelled')
|
||||||
|
await queue.change(job.id, 'retry')
|
||||||
|
await queue.work({ once: true, execute: async () => { throw new Error('fixture failure') } })
|
||||||
|
assert.equal(queue.read(job.id).status, 'failed')
|
||||||
|
await queue.change(job.id, 'retry')
|
||||||
|
await queue.work({ once: true, execute: async () => ({ text: 'fixture completed' }) })
|
||||||
|
assert.equal(queue.read(job.id).status, 'completed')
|
||||||
|
assert.equal(fs.readFileSync(original, 'utf8'), 'Изменённый оригинал')
|
||||||
|
const pending = await queue.submit({ kind: 'search', query: 'память' })
|
||||||
|
await queue.transaction(() => { const j = queue.read(pending.id); j.status = 'running'; queue.save(j, 'fixture_crash') })
|
||||||
|
fs.mkdirSync(path.join(queue.root, '.worker-lock'))
|
||||||
|
fs.writeFileSync(path.join(queue.root, '.worker-lock/owner.json'), JSON.stringify({ pid: 99999999, started: 'dead' }))
|
||||||
|
await queue.work({ once: true, execute: async () => ({ text: 'recovered' }) })
|
||||||
|
assert.equal(queue.read(pending.id).status, 'completed')
|
||||||
|
assert(queue.read(pending.id).events.some(e => e.event === 'worker_recovered'))
|
||||||
|
const orphanJob = await queue.submit({ kind: 'search', query: 'orphan fixture' })
|
||||||
|
const orphan = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true, stdio: 'ignore' })
|
||||||
|
const exited = new Promise(resolve => orphan.once('exit', resolve))
|
||||||
|
try {
|
||||||
|
const startedAt = spawnSync('ps', ['-p', String(orphan.pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout.trim()
|
||||||
|
fs.writeFileSync(path.join(queue.dir(orphanJob.id), 'process-groups.jsonl'), JSON.stringify({ pid: orphan.pid, started: startedAt }) + '\n')
|
||||||
|
await queue.transaction(() => { const j = queue.read(orphanJob.id); j.status = 'running'; queue.save(j, 'fixture_orphan') })
|
||||||
|
await queue.work({ once: true, execute: async () => ({ text: 'orphan recovered' }) })
|
||||||
|
await exited
|
||||||
|
assert.equal(queue.read(orphanJob.id).status, 'completed')
|
||||||
|
assert.throws(() => process.kill(orphan.pid, 0), { code: 'ESRCH' })
|
||||||
|
} finally { try { process.kill(-orphan.pid, 'SIGKILL') } catch {} }
|
||||||
|
const leaderlessJob = await queue.submit({ kind: 'search', query: 'leaderless fixture' })
|
||||||
|
const orphanPidFile = path.join(tmp, 'orphan-pid')
|
||||||
|
const wrapper = spawn(process.execPath, ['-e', `const {spawn}=require('node:child_process');const fs=require('node:fs');const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});fs.writeFileSync(${JSON.stringify(orphanPidFile)},String(child.pid));setTimeout(()=>process.exit(0),500)`], { detached: true, stdio: 'ignore' })
|
||||||
|
const wrapperExited = new Promise(resolve => wrapper.once('exit', resolve))
|
||||||
|
try {
|
||||||
|
const startedAt = spawnSync('ps', ['-p', String(wrapper.pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout.trim()
|
||||||
|
fs.writeFileSync(path.join(queue.dir(leaderlessJob.id), 'process-groups.jsonl'), JSON.stringify({ pid: wrapper.pid, started: startedAt }) + '\n')
|
||||||
|
await wrapperExited
|
||||||
|
const grandchildPid = Number(fs.readFileSync(orphanPidFile, 'utf8'))
|
||||||
|
process.kill(grandchildPid, 0)
|
||||||
|
await queue.transaction(() => { const j = queue.read(leaderlessJob.id); j.status = 'running'; queue.save(j, 'fixture_leader_exited') })
|
||||||
|
let executed = false
|
||||||
|
await assert.rejects(queue.work({ once: true, execute: async () => { executed = true; return { text: 'unsafe' } } }), /Ambiguous live process group/)
|
||||||
|
assert.equal(executed, false)
|
||||||
|
assert.equal(queue.read(leaderlessJob.id).status, 'failed')
|
||||||
|
assert.equal(queue.read(leaderlessJob.id).recovery_blocked, true)
|
||||||
|
assert.match(queue.read(leaderlessJob.id).error, /leader exited/)
|
||||||
|
process.kill(grandchildPid, 0)
|
||||||
|
await assert.rejects(queue.change(leaderlessJob.id, 'retry'), /Ambiguous live process group/)
|
||||||
|
const waiting = await queue.submit({ kind: 'search', query: 'must remain queued behind orphan' })
|
||||||
|
await assert.rejects(queue.work({ once: true, execute: async () => { executed = true } }), /Ambiguous live process group/)
|
||||||
|
assert.equal(executed, false)
|
||||||
|
assert.equal(queue.read(waiting.id).status, 'queued')
|
||||||
|
await queue.change(waiting.id, 'cancel')
|
||||||
|
} finally { try { process.kill(-wrapper.pid, 'SIGKILL') } catch {} }
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 200))
|
||||||
|
// Fixture cleanup also removes the intentionally ambiguous historical record.
|
||||||
|
fs.writeFileSync(path.join(queue.dir(leaderlessJob.id), 'process-groups.jsonl'), '')
|
||||||
|
await queue.change(leaderlessJob.id, 'retry')
|
||||||
|
await queue.work({ once: true, execute: async () => ({ text: 'explicit retry after orphan exits' }) })
|
||||||
|
const unrelatedJob = await queue.submit({ kind: 'search', query: 'reused leader must not be killed' })
|
||||||
|
const unrelated = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)'], { detached: true, stdio: 'ignore' })
|
||||||
|
try {
|
||||||
|
fs.writeFileSync(path.join(queue.dir(unrelatedJob.id), 'process-groups.jsonl'), JSON.stringify({ pid: unrelated.pid, started: 'Thu Jan 1 00:00:00 1970' }) + '\n')
|
||||||
|
await queue.transaction(() => { const j = queue.read(unrelatedJob.id); j.status = 'running'; queue.save(j, 'fixture_reused_pid') })
|
||||||
|
await queue.work({ once: true, execute: async () => ({ text: 'old group already gone' }) })
|
||||||
|
process.kill(unrelated.pid, 0)
|
||||||
|
} finally { try { process.kill(-unrelated.pid, 'SIGKILL') } catch {} }
|
||||||
|
const concurrent = await queue.submit({ kind: 'search', query: 'one worker' })
|
||||||
|
let entered
|
||||||
|
const started = new Promise(resolve => { entered = resolve })
|
||||||
|
let finish
|
||||||
|
const finishing = new Promise(resolve => { finish = resolve })
|
||||||
|
const first = queue.work({ once: true, execute: async () => { entered(); await finishing; return { text: 'done' } } })
|
||||||
|
await started
|
||||||
|
assert.equal((await new JobQueue(queue.root).work({ once: true })).worker, 'already_running')
|
||||||
|
await queue.change(concurrent.id, 'cancel')
|
||||||
|
finish(); await first
|
||||||
|
assert.equal(queue.read(concurrent.id).status, 'cancelled')
|
||||||
|
await assert.rejects(queue.change('../escape', 'cancel'), /Invalid job id/)
|
||||||
|
const link = path.join(tmp, 'symlink.md'); fs.symlinkSync(original, link)
|
||||||
|
await assert.rejects(queue.submit({ kind: 'ingest', mode: 'deep', files: [link] }))
|
||||||
|
const oversized = path.join(tmp, 'oversized.mp4')
|
||||||
|
fs.closeSync(fs.openSync(oversized, 'w')); fs.truncateSync(oversized, 512 * 1024 * 1024 + 1)
|
||||||
|
await assert.rejects(queue.submit({ kind: 'ingest', mode: 'deep', files: [oversized] }), /512 MiB/)
|
||||||
|
const fifo = path.join(tmp, 'input.fifo')
|
||||||
|
assert.equal(spawnSync('mkfifo', [fifo]).status, 0)
|
||||||
|
const fifoSubmit = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-jobs.mjs'), 'submit', '--root', path.join(tmp, 'fifo-queue'), '--kind', 'ingest', '--mode', 'deep', '--file', fifo, '--no-start'], { encoding: 'utf8', timeout: 2000 })
|
||||||
|
assert.equal(fifoSubmit.status, 1, 'FIFO must fail promptly instead of blocking open')
|
||||||
|
assert.match(fifoSubmit.stderr, /regular file/)
|
||||||
|
|
||||||
|
// Real CLI + real local search against a tiny fixture. No LLM, inbox or live vault.
|
||||||
|
const vault = path.join(tmp, 'vault'); fs.mkdirSync(vault)
|
||||||
|
fs.writeFileSync(path.join(vault, 'memory.md'), '# Память\nПамять агентов хранит источники.')
|
||||||
|
const cliRoot = path.join(tmp, 'cli-queue')
|
||||||
|
const cli = args => {
|
||||||
|
const out = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-jobs.mjs'), ...args, '--root', cliRoot], {
|
||||||
|
encoding: 'utf8', env: { ...process.env, MNEMAZINE_VAULT: vault, MNEMAZINE_DEEP: '1', MNEMAZINE_SEARCH_LOG: path.join(tmp, 'queries.jsonl') },
|
||||||
|
})
|
||||||
|
assert.equal(out.status, 0, out.stderr)
|
||||||
|
return JSON.parse(out.stdout)
|
||||||
|
}
|
||||||
|
const search = cli(['submit', '--kind', 'search', '--query', 'память', '--no-start']).job
|
||||||
|
cli(['work', '--once'])
|
||||||
|
const found = cli(['status', '--id', search.id]).job
|
||||||
|
assert.equal(found.status, 'completed')
|
||||||
|
assert.match(found.result.text, /memory.md/)
|
||||||
|
assert.match(found.result.text, /локальн/)
|
||||||
|
assert(found.result.sources.some(source => source.path === path.join(vault, 'memory.md')))
|
||||||
|
const titleIntake = cli(['submit', '--kind', 'ingest', '--mode', 'deep', '--text', 'Название для исследования', '--no-start']).job
|
||||||
|
assert.equal(titleIntake.input_text, 'Название для исследования')
|
||||||
|
assert.equal(titleIntake.status, 'queued')
|
||||||
|
|
||||||
|
// Trusted config cannot redirect isolated paths; fake npm records invocation env.
|
||||||
|
const fixtureRepo = path.join(tmp, 'protocol'); fs.mkdirSync(path.join(fixtureRepo, '.mnemazine'), { recursive: true })
|
||||||
|
fs.mkdirSync(path.join(fixtureRepo, 'scripts'))
|
||||||
|
fs.copyFileSync(path.join(repo, 'scripts/mnemazine-vault-lock.mjs'), path.join(fixtureRepo, 'scripts/mnemazine-vault-lock.mjs'))
|
||||||
|
const inbox = path.join(tmp, 'job-inbox'); fs.mkdirSync(inbox); fs.writeFileSync(path.join(inbox, 'a.md'), 'fixture')
|
||||||
|
fs.writeFileSync(path.join(fixtureRepo, '.mnemazine/config.local.sh'), 'export MNEMAZINE_INBOX=/wrong\nexport MNEMAZINE_STATE=/wrong\nexport MNEMAZINE_REPORTS=/wrong\nexport MNEMAZINE_ARCHIVE=/wrong\nexport MNEMAZINE_CACHE=/wrong\nexport MNEMAZINE_EXTRACTS=/wrong\nexport MNEMAZINE_RUN_ID=wrong\n')
|
||||||
|
const bin = path.join(tmp, 'bin'); fs.mkdirSync(bin)
|
||||||
|
fs.writeFileSync(path.join(bin, 'npm'), '#!/bin/sh\nnode -e \'const fs=require("fs");fs.appendFileSync(process.env.PROBE,JSON.stringify(Object.fromEntries(Object.entries(process.env).filter(([k])=>k.startsWith("MNEMAZINE_"))))+"\\n")\'\n', { mode: 0o700 })
|
||||||
|
const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, MNEMAZINE_ROOT: fixtureRepo, MNEMAZINE_VAULT: vault, MNEMAZINE_INBOX: inbox, PROBE: path.join(tmp, 'probe.jsonl') }
|
||||||
|
for (const key of ['STATE', 'REPORTS', 'ARCHIVE', 'CACHE', 'EXTRACTS', 'RUN_ID']) env[`MNEMAZINE_${key}`] = path.join(tmp, key)
|
||||||
|
const protocol = spawnSync('bash', [path.join(repo, 'scripts/mnemazine-desktop-protocol.sh')], { env, encoding: 'utf8' })
|
||||||
|
assert.equal(protocol.status, 0, protocol.stderr)
|
||||||
|
const records = fs.readFileSync(env.PROBE, 'utf8').trim().split('\n').map(JSON.parse)
|
||||||
|
assert.equal(records.length, 2)
|
||||||
|
for (const record of records) for (const key of ['INBOX', 'STATE', 'REPORTS', 'ARCHIVE', 'CACHE', 'EXTRACTS', 'RUN_ID']) assert.equal(record[`MNEMAZINE_${key}`], env[`MNEMAZINE_${key}`])
|
||||||
|
// Hidden job ancestors are valid inboxes. Short text fails the content gate,
|
||||||
|
// not scanning. Disable synthesis explicitly: this probe must never use LLMs.
|
||||||
|
for (const [name, content, processed] of [
|
||||||
|
['short', '# Короткая проверка\nПроверяем перенос файла в приложение.', 0],
|
||||||
|
['long', '# Проверка очереди\nПамять агента должна сохранять исходный материал, связывать заметки с проверяемыми источниками и возвращать справку с понятными ссылками на документы.', 1],
|
||||||
|
['url-seed', fs.readFileSync(textQueue.list().find(job => job.input_kind === 'url').files[0].snapshot, 'utf8'), 1],
|
||||||
|
['title-seed', fs.readFileSync(textQueue.list().find(job => job.input_kind === 'title').files[0].snapshot, 'utf8'), 1],
|
||||||
|
]) {
|
||||||
|
const root = path.join(tmp, '.hidden-jobs', name)
|
||||||
|
fs.mkdirSync(path.join(root, 'inbox'), { recursive: true })
|
||||||
|
fs.writeFileSync(path.join(root, 'inbox', 'fixture.md'), content)
|
||||||
|
const probe = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-run.mjs'), '--require-deep'], {
|
||||||
|
encoding: 'utf8', timeout: 10000, cwd: tmp,
|
||||||
|
env: { ...process.env, MNEMAZINE_ROOT: repo, MNEMAZINE_VAULT: vault,
|
||||||
|
MNEMAZINE_INBOX: path.join(root, 'inbox'), MNEMAZINE_STATE: path.join(root, 'state'),
|
||||||
|
MNEMAZINE_REPORTS: path.join(root, 'reports'), MNEMAZINE_ARCHIVE: path.join(root, 'archive'),
|
||||||
|
MNEMAZINE_CACHE: path.join(root, 'cache/hashes.json'), MNEMAZINE_EXTRACTS: path.join(root, 'cache/extracted'),
|
||||||
|
MNEMAZINE_DEEP: '0', MNEMAZINE_SYNTHESIZE: '0', MNEMAZINE_FINISH: '0', MNEMAZINE_DRAFT_ONLY: '0',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
assert.equal(probe.status, processed ? 2 : 1, probe.stderr) // No synthesized notes: quality gate must also fail.
|
||||||
|
const state = JSON.parse(fs.readFileSync(path.join(root, 'state/last-run.json'), 'utf8'))
|
||||||
|
assert.equal(state.inbox, 1)
|
||||||
|
assert.equal(state.processed, processed)
|
||||||
|
assert.equal(state.failed, 1 - processed)
|
||||||
|
assert.equal(state.synthesize.skipped, true)
|
||||||
|
const diagnosis = pipelineFailure(root, { code: probe.status })
|
||||||
|
if (!processed) assert.match(diagnosis, /Файл прочитан, но текст слишком короткий.*не менее 80/)
|
||||||
|
else assert.match(diagnosis, /run vault quality failed/)
|
||||||
|
assert(fs.existsSync(path.join(root, 'inbox/fixture.md')), 'fixture source must not be archived')
|
||||||
|
}
|
||||||
|
console.log('jobs tests passed: copy/dedup, retry/cancel, recovery, worker exclusion, local search, protocol isolation')
|
||||||
|
} finally { fs.rmSync(tmp, { recursive: true, force: true }) }
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { setTimeout } from 'node:timers/promises';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { runAdapter } from '../scripts/mnemazine-olympuz.mjs';
|
||||||
|
|
||||||
|
const root = mkdtempSync(join(tmpdir(), 'mnemazine-olympuz-test-'));
|
||||||
|
const cli = fileURLToPath(new URL('../scripts/mnemazine-jobs.mjs', import.meta.url));
|
||||||
|
const state = join(root, 'shared-state');
|
||||||
|
const worktree = join(root, 'god-worktree');
|
||||||
|
const research = join(worktree, 'research');
|
||||||
|
const base = ['--root', state, '--god', 'athena', '--run', 'run-1', '--project', 'example', '--mode', 'deep'];
|
||||||
|
const core = (...args) => JSON.parse(execFileSync(process.execPath, [cli, ...args, '--root', state, '--no-start'], { encoding: 'utf8' }));
|
||||||
|
try {
|
||||||
|
mkdirSync(research, { recursive: true });
|
||||||
|
const file = join(research, 'agent-research--example--public-source.md');
|
||||||
|
const content = '# Public fixture\nWater freezes at 0 °C under standard pressure.\n';
|
||||||
|
writeFileSync(file, content);
|
||||||
|
const { job } = runAdapter(['submit', ...base, '--worktree', worktree, '--file', file, '--no-start']);
|
||||||
|
assert.equal(job.kind, 'ingest');
|
||||||
|
assert.equal(job.status, 'queued');
|
||||||
|
assert.deepEqual(job.provenance, { client: 'olympuz', god: 'athena', run: 'run-1', project: 'example' });
|
||||||
|
assert.equal(readFileSync(file, 'utf8'), content, 'god source survives queue acceptance');
|
||||||
|
await setTimeout(20);
|
||||||
|
const redelivered = runAdapter(['submit', ...base, '--worktree', worktree, '--file', file, '--no-start']).job;
|
||||||
|
assert.equal(redelivered.id, job.id, 'unchanged delivery after clock tick reuses the same job');
|
||||||
|
assert.equal(redelivered.created_at, job.created_at, 'redelivery keeps original queue timestamp');
|
||||||
|
assert.equal(core('list').jobs.length, 1, 'redelivery adds no second job');
|
||||||
|
assert.throws(() => runAdapter(['submit', ...base.filter((x, i) => i < base.length - 2), '--worktree', worktree, '--file', file, '--no-start']), /--mode deep/);
|
||||||
|
assert.equal(core('status', '--id', job.id).job.id, job.id, 'desktop/core sees Olympuz job');
|
||||||
|
assert(core('list').jobs.some(item => item.id === job.id));
|
||||||
|
const desktop = core('submit', '--kind', 'search', '--query', 'public fixture', '--no-start').job;
|
||||||
|
assert.throws(() => runAdapter(['status', ...base, '--id', desktop.id]), /JOB_SCOPE_MISMATCH/);
|
||||||
|
assert.throws(() => runAdapter(['status', ...base.map(x => x === 'run-1' ? 'run-2' : x), '--id', job.id]), /JOB_SCOPE_MISMATCH/);
|
||||||
|
assert.equal(runAdapter(['cancel', ...base, '--id', job.id]).job.status, 'cancelled');
|
||||||
|
assert.equal(core('status', '--id', job.id).job.status, 'cancelled');
|
||||||
|
const retry = runAdapter(['retry', ...base, '--id', job.id, '--no-start']).job;
|
||||||
|
assert.equal(retry.status, 'queued');
|
||||||
|
assert.deepEqual(retry.provenance, job.provenance);
|
||||||
|
for (const command of ['search', 'brief']) {
|
||||||
|
assert.throws(() => runAdapter([command, ...base, '--query', 'private information']), /PROJECT_SCOPE_UNAVAILABLE/);
|
||||||
|
}
|
||||||
|
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', file, '--vault', root]), /Unknown option/);
|
||||||
|
const link = join(research, 'agent-research--example--link.md');
|
||||||
|
symlinkSync(file, link);
|
||||||
|
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', link, '--no-start']));
|
||||||
|
const hardlink = join(research, 'agent-research--example--hardlink.md');
|
||||||
|
linkSync(file, hardlink);
|
||||||
|
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', hardlink, '--no-start']), /обычным файлом/);
|
||||||
|
rmSync(hardlink);
|
||||||
|
const wrongProject = join(research, 'agent-research--another--source.md');
|
||||||
|
writeFileSync(wrongProject, content);
|
||||||
|
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', wrongProject, '--no-start']), /SOURCE_SCOPE_MISMATCH/);
|
||||||
|
const oversized = join(research, 'agent-research--example--oversized.md');
|
||||||
|
writeFileSync(oversized, Buffer.alloc(256 * 1024 + 1));
|
||||||
|
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', oversized, '--no-start']), /256 KiB/);
|
||||||
|
assert(existsSync(file));
|
||||||
|
console.log('PASS Olympuz/shared jobs: provenance, visibility, cancellation/retry, scope and hostile files');
|
||||||
|
} finally { rmSync(root, { recursive: true, force: true }); }
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { spawnSync } from 'node:child_process'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
|
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||||
|
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-prearchive-'))
|
||||||
|
try {
|
||||||
|
const vault = path.join(tmp, 'vault'); fs.mkdirSync(vault)
|
||||||
|
process.env.MNEMAZINE_VAULT = vault
|
||||||
|
const { archiveAfterValidation } = await import('../scripts/mnemazine-run.mjs')
|
||||||
|
const { loadSpecCeiling } = await import('../scripts/mnemazine-complete-check.mjs')
|
||||||
|
const source = path.join(tmp, 'source.md'), archived = path.join(tmp, 'archived.md')
|
||||||
|
fs.writeFileSync(source, 'Original fixture must survive failed validation.')
|
||||||
|
const events = []
|
||||||
|
const archive = async file => { events.push('archive'); fs.renameSync(file, archived); return archived }
|
||||||
|
const items = [{ file: source, hash: 'fixture' }]
|
||||||
|
await assert.rejects(archiveAfterValidation({ failed: 0, finish: { human_layer: { ok: false, code: 1 } }, items, archive, validate: async () => events.push('complete') }), /final validation failed/)
|
||||||
|
assert(fs.existsSync(source))
|
||||||
|
assert.deepEqual(events, [])
|
||||||
|
await assert.rejects(archiveAfterValidation({ failed: 0, finish: { human_layer: { ok: true } }, items, archive, validate: async () => { events.push('complete'); throw new Error('spec ceiling failed') } }), /spec ceiling failed/)
|
||||||
|
assert(fs.existsSync(source))
|
||||||
|
assert.deepEqual(events, ['complete'])
|
||||||
|
events.length = 0
|
||||||
|
await archiveAfterValidation({ failed: 0, finish: { human_layer: { ok: true } }, items, archive, validate: async () => events.push('complete') })
|
||||||
|
assert.deepEqual(events, ['complete', 'archive'])
|
||||||
|
assert(fs.existsSync(archived))
|
||||||
|
|
||||||
|
const state = path.join(tmp, '.mnemazine/state'); fs.mkdirSync(state, { recursive: true })
|
||||||
|
const baseline = path.join(state, 'spec-ceiling.json')
|
||||||
|
assert.match((await loadSpecCeiling({ root: tmp, vault })).error, /no baseline/)
|
||||||
|
fs.writeFileSync(baseline, JSON.stringify({ vault, checked: 10, ceiling: 0 }))
|
||||||
|
const before = fs.readFileSync(baseline, 'utf8')
|
||||||
|
const loaded = await loadSpecCeiling({ root: tmp, vault })
|
||||||
|
assert.equal(loaded.error, null)
|
||||||
|
assert.equal(loaded.file, baseline)
|
||||||
|
assert.match((await loadSpecCeiling({ root: tmp, vault: path.join(tmp, 'other-vault') })).error, /different vault/)
|
||||||
|
assert.equal(fs.readFileSync(baseline, 'utf8'), before, 'baseline must not be copied, updated or fabricated')
|
||||||
|
const scripts = path.join(tmp, 'scripts'); fs.mkdirSync(scripts)
|
||||||
|
for (const name of ['coverage-check', 'vault-quality-gate', 'spec-ceiling', 'report-quality-gate', 'human-layer-gate']) fs.writeFileSync(path.join(scripts, `mnemazine-${name}.mjs`), 'console.log("fixture gate passed")\n')
|
||||||
|
const jobState = path.join(tmp, 'job-state'), inbox = path.join(tmp, 'inbox'), reports = path.join(tmp, 'reports')
|
||||||
|
for (const folder of [jobState, inbox, reports]) fs.mkdirSync(folder)
|
||||||
|
fs.writeFileSync(path.join(inbox, 'source.md'), 'source fixture')
|
||||||
|
fs.writeFileSync(path.join(reports, 'visual-knowledge-report.html'), '<html>fixture</html>')
|
||||||
|
fs.writeFileSync(path.join(jobState, 'last-action-brief.md'), 'fixture brief')
|
||||||
|
const pending = { ok: false, phase: 'pending_archive', pre_archive_ready: true, archive_pending: 1, processed: 1, deep: true, enrich_required: true, strict_archive_knowledge: true, synthesize: { atomized: 1, enriched: 1 }, vault }
|
||||||
|
fs.writeFileSync(path.join(jobState, 'last-run.json'), JSON.stringify(pending))
|
||||||
|
const check = (beforeArchive = true) => spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-complete-check.mjs'), '--require-deep', ...(beforeArchive ? ['--before-archive'] : [])], { encoding: 'utf8', timeout: 10000, cwd: tmp, env: { ...process.env, MNEMAZINE_ROOT: tmp, MNEMAZINE_STATE: jobState, MNEMAZINE_INBOX: inbox, MNEMAZINE_REPORTS: reports, MNEMAZINE_VAULT: vault } })
|
||||||
|
assert.equal(check().status, 0, 'valid pending state uses real canonical fixture baseline, not job-state baseline')
|
||||||
|
assert.equal(check(false).status, 1, 'normal completion must reject pending archive')
|
||||||
|
fs.writeFileSync(path.join(scripts, 'mnemazine-coverage-check.mjs'), 'console.error("fixture uncovered source");process.exit(1)\n')
|
||||||
|
const failedCoverage = check()
|
||||||
|
assert.equal(failedCoverage.status, 1)
|
||||||
|
assert.match(failedCoverage.stdout, /coverage failed/)
|
||||||
|
assert(fs.existsSync(path.join(inbox, 'source.md')))
|
||||||
|
const producer = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-synthesize.mjs'), '--selftest'], { encoding: 'utf8', timeout: 10000, cwd: tmp, env: { ...process.env, MNEMAZINE_ROOT: repo, MNEMAZINE_VAULT: vault, MNEMAZINE_STATE: path.join(tmp, 'job-state'), MNEMAZINE_DEEP: '0' } })
|
||||||
|
assert.equal(producer.status, 0, producer.stderr)
|
||||||
|
console.log('prearchive passed: failed finish/complete retain source, gate-before-move, canonical vault-bound baseline, truthful producer sections')
|
||||||
|
} finally { fs.rmSync(tmp, { recursive: true, force: true }) }
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { promises as fs } from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { evidenceExcerpt, verifyFindings, cloudReadable } from '../scripts/mnemazine-kb-search.mjs'
|
||||||
|
import { loadTaxonomy } from '../scripts/mnemazine-machine-class-gate.mjs'
|
||||||
|
|
||||||
|
const longNote = '# Документ\n' + 'Нерелевантное описание. '.repeat(600) + '\nЛазурный двигатель: ресурс 840 циклов.'
|
||||||
|
assert.ok(evidenceExcerpt(longNote, 'лазурный двигатель').includes('840 циклов'), 'evidence at the end is readable')
|
||||||
|
assert.ok(evidenceExcerpt(longNote, 'лазурный двигатель').length <= 2500)
|
||||||
|
const finding = { note: 'source.md', insight: 'Лазурный двигатель: ресурс 840 циклов.', relevance: 5 }
|
||||||
|
const corpus = new Map([['source.md', longNote]])
|
||||||
|
let result = await verifyFindings('лазурный двигатель', [finding], corpus, async prompt => {
|
||||||
|
assert.ok(prompt.includes('840 циклов'))
|
||||||
|
return { grounded: true, relevant: true, actionable: true }
|
||||||
|
}, true)
|
||||||
|
assert.equal(result.kept.length, 1)
|
||||||
|
result = await verifyFindings('лазурный двигатель', [finding], corpus, async () => { throw new Error('offline verifier fixture') }, true)
|
||||||
|
assert.deepEqual(result, { kept: [], dropped: 1 }, 'verifier error cannot certify evidence')
|
||||||
|
for (const verdict of [{}, { grounded: true, relevant: false }, { grounded: false, relevant: true }]) {
|
||||||
|
result = await verifyFindings('лазурный двигатель', [finding], corpus, async () => verdict, true)
|
||||||
|
assert.equal(result.kept.length, 0, 'missing/negative verdict is not support')
|
||||||
|
}
|
||||||
|
result = await verifyFindings('лазурный двигатель', [finding], new Map(), async () => { throw new Error('must not run for missing source') }, true)
|
||||||
|
assert.equal(result.kept.length, 0)
|
||||||
|
result = await verifyFindings('лазурный двигатель', Array(7).fill(finding), corpus, async () => ({ grounded: true, relevant: true }), true)
|
||||||
|
assert.equal(result.kept.length, 5)
|
||||||
|
assert.equal(result.dropped, 2, 'over-budget findings must not bypass verification')
|
||||||
|
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-evidence-'))
|
||||||
|
try {
|
||||||
|
const nested = path.join(tmp, '02 Здоровье', 'nested')
|
||||||
|
await fs.mkdir(nested, { recursive: true })
|
||||||
|
const privateFile = path.join(nested, 'private.md')
|
||||||
|
await fs.writeFile(privateFile, '---\ndata_class: text\n---\nЛичное')
|
||||||
|
assert.equal(cloudReadable(privateFile, loadTaxonomy()), false, 'nested private section cannot be downgraded')
|
||||||
|
const ordinary = path.join(tmp, 'public.md')
|
||||||
|
await fs.writeFile(ordinary, '---\ndata_class: public\n---\nОткрытое')
|
||||||
|
assert.equal(cloudReadable(ordinary, loadTaxonomy()), true)
|
||||||
|
await fs.writeFile(ordinary, 'Нет frontmatter')
|
||||||
|
assert.equal(cloudReadable(ordinary, loadTaxonomy()), false, 'missing classification is private')
|
||||||
|
} finally { await fs.rm(tmp, { recursive: true, force: true }) }
|
||||||
|
console.log('search evidence regressions: passed')
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { mkdtempSync, mkdirSync, symlinkSync, existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
|
||||||
|
import os from 'node:os'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { spawn, spawnSync } from 'node:child_process'
|
||||||
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { acquireVaultLock } from '../scripts/mnemazine-vault-lock.mjs'
|
||||||
|
|
||||||
|
const script = fileURLToPath(new URL('../scripts/mnemazine-vault-lock.mjs', import.meta.url))
|
||||||
|
const root = mkdtempSync(path.join(os.tmpdir(), 'mnemazine-vault-lock-test-'))
|
||||||
|
const vault = path.join(root, 'vault')
|
||||||
|
const alias = path.join(root, 'alias')
|
||||||
|
mkdirSync(vault)
|
||||||
|
symlinkSync(vault, alias)
|
||||||
|
const dir = path.join(vault, '.mnemazine-pipeline-lock')
|
||||||
|
const run = (target, code, env = process.env) => spawnSync(process.execPath,
|
||||||
|
[script, '--vault', target, '--', process.execPath, '-e', code], { encoding: 'utf8', env })
|
||||||
|
let holder
|
||||||
|
try {
|
||||||
|
// A real independent process owns the vault while another uses a symlink.
|
||||||
|
holder = spawn(process.execPath, [script, '--vault', vault, '--', process.execPath,
|
||||||
|
'-e', 'console.log("ready"); process.stdin.resume()'], { stdio: ['pipe', 'pipe', 'pipe'] })
|
||||||
|
await new Promise((resolve, reject) => {
|
||||||
|
holder.stdout.once('data', resolve)
|
||||||
|
holder.once('error', reject)
|
||||||
|
holder.once('exit', code => reject(new Error(`holder exited ${code}`)))
|
||||||
|
})
|
||||||
|
assert.equal(run(alias, '').status, 75)
|
||||||
|
const otherOwner = JSON.parse(readFileSync(path.join(dir, 'owner.json'), 'utf8'))
|
||||||
|
assert.equal(run(alias, '', { ...process.env, MNEMAZINE_VAULT_LOCK: otherOwner.nonce }).status, 75,
|
||||||
|
'knowing nonce does not make an unrelated process a descendant')
|
||||||
|
const exit = new Promise(resolve => holder.once('exit', resolve))
|
||||||
|
holder.stdin.end()
|
||||||
|
assert.equal(await exit, 0)
|
||||||
|
assert.equal(existsSync(dir), false)
|
||||||
|
|
||||||
|
const release = acquireVaultLock(vault)
|
||||||
|
assert.equal(run(alias, '').status, 0, 'descendant inherits verified lock')
|
||||||
|
assert.equal(run(alias, '', { ...process.env, MNEMAZINE_VAULT_LOCK: 'wrong' }).status, 75)
|
||||||
|
assert.equal(existsSync(dir), true, 'child must not release parent ownership')
|
||||||
|
release()
|
||||||
|
assert.equal(run(vault, 'process.exit(7)').status, 7)
|
||||||
|
assert.equal(existsSync(dir), false, 'command failure cleans lock')
|
||||||
|
const direct = spawnSync(process.execPath, ['--input-type=module', '-e',
|
||||||
|
`import { acquireVaultLock } from ${JSON.stringify(new URL('../scripts/mnemazine-vault-lock.mjs', import.meta.url).href)}; acquireVaultLock(${JSON.stringify(vault)}); process.exit(9)`])
|
||||||
|
assert.equal(direct.status, 9)
|
||||||
|
assert.equal(existsSync(dir), false, 'process.exit cleans direct lock')
|
||||||
|
|
||||||
|
mkdirSync(dir)
|
||||||
|
writeFileSync(path.join(dir, 'owner.json'), JSON.stringify({ pid: 2147483647, start: 'stale', nonce: 'stale' }))
|
||||||
|
assert.equal(run(vault, '').status, 75)
|
||||||
|
assert.equal(existsSync(dir), true, 'stale ownership is never stolen')
|
||||||
|
console.log('vault lock: concurrency, aliases, reentrancy, stale and failure cleanup passed')
|
||||||
|
} finally {
|
||||||
|
holder?.kill('SIGTERM')
|
||||||
|
rmSync(root, { recursive: true, force: true })
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user