release: Mnemazine
Local-first memory system: raw material in, finished notes out. Synthesis on write. This release brings a guided install that explains itself and ends with a live demo pass, eleven fixes to the knowledge pipeline found by running it against a real archive of 216 sources, and a documentation pass in the project's own voice.
This commit is contained in:
+174
-16
@@ -1,12 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
|
||||
# Root of the tree being scanned. Take it from the CURRENT git invocation
|
||||
# (git runs hooks with cwd = worktree top) so a shared script installed at the
|
||||
# main repo path still scans the right worktree. Fall back to script-relative
|
||||
# only outside a git tree. An explicit $1 always wins.
|
||||
ROOT="${1:-$(git rev-parse --show-toplevel 2>/dev/null || (cd "$(dirname "$0")/.." && pwd))}"
|
||||
ROOT_REAL="$(cd "$ROOT" 2>/dev/null && pwd -P || printf '%s' "$ROOT")"
|
||||
|
||||
# Private markers (machine paths, IPs, personal/project names) that must never ship publicly.
|
||||
# `root@` requires a real host char after it (lowercase/digit) so the literal
|
||||
# placeholder `root@YOUR_VPS_HOST` in docs/examples is not a false positive.
|
||||
PRIVATE_MARKERS='/Users/fil|72\.56|root@[a-z0-9]|Полезные знания|_ВХОДЯЩИЕ|TODOCUPS|ПКК|legal-practice|Adventure Book|AthenaOS|Филипп'
|
||||
PRIVATE_MARKER_RULES_DEFAULT=(
|
||||
'private-path|/Users/'
|
||||
'remote-address|72\.56'
|
||||
'remote-root|root@[a-z0-9]'
|
||||
'vault-name-current|Мозг'
|
||||
'vault-name-legacy|Полезные знания'
|
||||
'owner-projects|TODOCUPS|ПКК|AthenaOS|legal-practice|Adventure Book'
|
||||
'owner-name|Филипп'
|
||||
)
|
||||
PRIVATE_MARKERS_FILE="${MNEMAZINE_PRIVATE_MARKERS_FILE:-$ROOT/.mnemazine/private-markers.txt}"
|
||||
# Token-like values across common providers. Require realistic lengths and a
|
||||
# non-word boundary before `sk-` to avoid false positives like `risk-or-x`.
|
||||
# Covers: GitHub OAuth/PAT (gho_/ghp_/ghu_/ghs_/ghr_), OpenAI/Anthropic sk-,
|
||||
@@ -14,6 +28,123 @@ PRIVATE_MARKERS='/Users/fil|72\.56|root@[a-z0-9]|Полезные знания|_
|
||||
# (AIza), JWT (eyJ.header.payload), and PEM private-key blocks.
|
||||
TOKEN_MARKERS='gh[opusr]_[A-Za-z0-9_]{20,}|(^|[^A-Za-z0-9])sk-[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{20,}|(AKIA|ASIA)[A-Z0-9]{16}|glpat-[A-Za-z0-9_-]{20,}|AIza[A-Za-z0-9_-]{30,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----'
|
||||
|
||||
PRIVATE_MARKERS=''
|
||||
|
||||
append_private_marker() {
|
||||
local marker="$1"
|
||||
[ -n "$marker" ] || return 0
|
||||
if [ -z "$PRIVATE_MARKERS" ]; then
|
||||
PRIVATE_MARKERS="$marker"
|
||||
else
|
||||
PRIVATE_MARKERS="$PRIVATE_MARKERS|$marker"
|
||||
fi
|
||||
}
|
||||
|
||||
escape_ere() {
|
||||
printf '%s' "$1" | sed 's/[][\\.^$*+?{}()|]/\\&/g'
|
||||
}
|
||||
|
||||
add_basename_marker() {
|
||||
local value="$1"
|
||||
local base value_real
|
||||
[ -n "$value" ] || return 0
|
||||
case "$value" in
|
||||
"$ROOT"|"$ROOT"/*) return 0 ;;
|
||||
esac
|
||||
value_real="$(cd "$value" 2>/dev/null && pwd -P || printf '%s' "$value")"
|
||||
case "$value_real" in
|
||||
"$ROOT_REAL"|"$ROOT_REAL"/*) return 0 ;;
|
||||
esac
|
||||
base="$(basename "$value")"
|
||||
[ -n "$base" ] || return 0
|
||||
case "$base" in
|
||||
mnemazine|Mnemazine|vault|inbox|reports|state|home|"Mnemazine Inbox") return 0 ;;
|
||||
esac
|
||||
append_private_marker "(^|[^[:alnum:]_])$(escape_ere "$base")([^[:alnum:]_]|$)"
|
||||
}
|
||||
|
||||
toml_escape() {
|
||||
printf '%s' "$1" | sed "s/'/''/g"
|
||||
}
|
||||
|
||||
print_gitleaks_config() {
|
||||
cat <<'EOF'
|
||||
# Generated from scripts/check-public-release.sh.
|
||||
# Do not hand-edit marker rules here; change PRIVATE_MARKER_RULES_DEFAULT there
|
||||
# and regenerate with: bash scripts/check-public-release.sh --print-gitleaks-config > .gitleaks.toml
|
||||
|
||||
[extend]
|
||||
useDefault = true
|
||||
|
||||
[[allowlists]]
|
||||
paths = [
|
||||
'^scripts/check-public-release\.sh$',
|
||||
'^\.gitleaks\.toml$',
|
||||
]
|
||||
|
||||
[[allowlists]]
|
||||
description = 'Retrieval eval anchors are owner-approved measurement fixtures; keep token rules active, suppress only project/vault marker rules.'
|
||||
targetRules = ['vault-name-current', 'owner-projects']
|
||||
paths = [
|
||||
'^tests/retrieval-eval\.mjs$',
|
||||
]
|
||||
|
||||
EOF
|
||||
for rule in "${PRIVATE_MARKER_RULES_DEFAULT[@]}"; do
|
||||
local id="${rule%%|*}"
|
||||
local regex="${rule#*|}"
|
||||
printf '[[rules]]\n'
|
||||
printf "id = '%s'\n" "$(toml_escape "$id")"
|
||||
printf "description = 'Mnemazine private marker: %s'\n" "$(toml_escape "$id")"
|
||||
printf "regex = '%s'\n" "$(toml_escape "$regex")"
|
||||
printf "tags = ['mnemazine-private']\n\n"
|
||||
done
|
||||
}
|
||||
|
||||
if [ "${1:-}" = "--print-gitleaks-config" ]; then
|
||||
print_gitleaks_config
|
||||
exit 0
|
||||
fi
|
||||
|
||||
load_config_markers() {
|
||||
local config="$ROOT/.mnemazine/config.json"
|
||||
[ -f "$config" ] || return 0
|
||||
command -v node >/dev/null 2>&1 || return 0
|
||||
while IFS= read -r value; do
|
||||
add_basename_marker "$value"
|
||||
done < <(node -e '
|
||||
const fs = require("fs")
|
||||
const cfg = JSON.parse(fs.readFileSync(process.argv[1], "utf8"))
|
||||
for (const key of ["vault", "inbox", "root"]) {
|
||||
if (typeof cfg[key] === "string" && cfg[key]) console.log(cfg[key])
|
||||
}
|
||||
' "$config" 2>/dev/null || true)
|
||||
}
|
||||
|
||||
if [ "${MNEMAZINE_PRIVATE_MARKERS_BASE+x}" = "x" ]; then
|
||||
append_private_marker "$MNEMAZINE_PRIVATE_MARKERS_BASE"
|
||||
else
|
||||
for rule in "${PRIVATE_MARKER_RULES_DEFAULT[@]}"; do
|
||||
append_private_marker "${rule#*|}"
|
||||
done
|
||||
load_config_markers
|
||||
add_basename_marker "$HOME"
|
||||
fi
|
||||
|
||||
if [ -f "$PRIVATE_MARKERS_FILE" ]; then
|
||||
while IFS= read -r marker || [ -n "$marker" ]; do
|
||||
marker="${marker%$'\r'}"
|
||||
[ -n "$marker" ] || continue
|
||||
case "$marker" in \#*) continue ;; esac
|
||||
append_private_marker "$marker"
|
||||
done < "$PRIVATE_MARKERS_FILE"
|
||||
fi
|
||||
|
||||
if [ -z "$PRIVATE_MARKERS" ]; then
|
||||
echo "Public release check errored: private marker list is empty; scanner cannot validate privacy." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Pick a scanner. Prefer ripgrep; fall back to POSIX grep so the gate still runs
|
||||
# on machines without rg. A missing scanner must HARD-FAIL, never silently pass.
|
||||
if command -v rg >/dev/null 2>&1; then
|
||||
@@ -30,31 +161,57 @@ if git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
TRACKED_ONLY=1
|
||||
fi
|
||||
|
||||
# Only two files may carry personal markers, and for opposite reasons: the scanners
|
||||
# below have to spell the markers out to hunt for them, and the licence names the
|
||||
# rights holder because that is what a licence is for. Everything else — agent
|
||||
# prompts, skills, tests, reports — went public with `/Users/<name>` and a private
|
||||
# vault name baked in precisely because it sat on this list.
|
||||
private_marker_excluded() {
|
||||
case "$1" in
|
||||
.gitleaks.toml|\
|
||||
scripts/check-public-release.sh|\
|
||||
LICENSE)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
# Files that could ship publicly: everything git tracks PLUS untracked files
|
||||
# not covered by .gitignore (a staged-but-uncommitted secret would otherwise
|
||||
# slip past a tracked-only scan). Ignored runtime noise (.mnemazine, backups)
|
||||
# is correctly skipped — it never reaches a public push.
|
||||
tracked_files() {
|
||||
local mode="${1:-all}"
|
||||
local files=()
|
||||
while IFS= read -r -d '' file; do
|
||||
[ "$file" = "scripts/check-public-release.sh" ] && continue
|
||||
files+=("$ROOT/$file")
|
||||
done < <(git -C "$ROOT" ls-files -z --cached --others --exclude-standard)
|
||||
printf '%s\0' "${files[@]}"
|
||||
}
|
||||
while IFS= read -r -d '' file; do
|
||||
[ "$file" = "scripts/check-public-release.sh" ] && continue
|
||||
# Local runtime instruments intentionally contain machine/vault paths.
|
||||
# Keep token scanning on them; exclude only private-marker noise.
|
||||
if [ "$mode" = "private-marker" ] && private_marker_excluded "$file"; then
|
||||
continue
|
||||
fi
|
||||
files+=("$ROOT/$file")
|
||||
done < <(git -C "$ROOT" ls-files -z --cached --others --exclude-standard)
|
||||
if [ "${#files[@]}" -gt 0 ]; then
|
||||
printf '%s\0' "${files[@]}"
|
||||
fi
|
||||
}
|
||||
|
||||
# scan PATTERN: print matches under $ROOT, excluding vendored/VCS noise and this
|
||||
# script itself (it embeds the marker patterns). Exit: 0 = match, 1 = clean, >=2 = scanner error.
|
||||
scan() {
|
||||
local pattern="$1"
|
||||
local mode="${2:-all}"
|
||||
if [ "$TRACKED_ONLY" -eq 1 ]; then
|
||||
local files=()
|
||||
while IFS= read -r -d '' file; do
|
||||
files+=("$file")
|
||||
done < <(tracked_files)
|
||||
if [ "${#files[@]}" -eq 0 ]; then
|
||||
return 1
|
||||
fi
|
||||
while IFS= read -r -d '' file; do
|
||||
files+=("$file")
|
||||
done < <(tracked_files "$mode")
|
||||
if [ "${#files[@]}" -eq 0 ]; then
|
||||
echo "Public release check errored: no public files available to scan." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$SCANNER" = "rg" ]; then
|
||||
rg -n "$pattern" "${files[@]}"
|
||||
else
|
||||
@@ -74,8 +231,9 @@ scan() {
|
||||
check() {
|
||||
local pattern="$1"
|
||||
local label="$2"
|
||||
local mode="${3:-all}"
|
||||
local status=0
|
||||
scan "$pattern" || status=$?
|
||||
scan "$pattern" "$mode" || status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo "Public release check failed: $label found." >&2
|
||||
exit 1
|
||||
@@ -85,7 +243,7 @@ check() {
|
||||
fi
|
||||
}
|
||||
|
||||
check "$PRIVATE_MARKERS" "private marker"
|
||||
check "$PRIVATE_MARKERS" "private marker" "private-marker"
|
||||
check "$TOKEN_MARKERS" "token-like value"
|
||||
|
||||
# Local extraction cache is gitignored (never shipped), but captured screenshots
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env node
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const HOOK_NAMES = ['args', 'agent', 'parallel', 'phase', 'log']
|
||||
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor
|
||||
|
||||
function findMeta(source) {
|
||||
const match = /(^|\n)\s*export\s+const\s+meta\s*=/.exec(source)
|
||||
if (!match) throw new SyntaxError('export const meta block not found')
|
||||
|
||||
const objectStart = source.indexOf('{', match.index + match[0].length)
|
||||
if (objectStart === -1) throw new SyntaxError('export const meta object not found')
|
||||
|
||||
let depth = 0
|
||||
let quote = ''
|
||||
let lineComment = false
|
||||
let blockComment = false
|
||||
|
||||
for (let i = objectStart; i < source.length; i += 1) {
|
||||
const ch = source[i]
|
||||
const next = source[i + 1]
|
||||
|
||||
if (lineComment) {
|
||||
if (ch === '\n') lineComment = false
|
||||
continue
|
||||
}
|
||||
if (blockComment) {
|
||||
if (ch === '*' && next === '/') {
|
||||
blockComment = false
|
||||
i += 1
|
||||
}
|
||||
continue
|
||||
}
|
||||
if (quote) {
|
||||
if (ch === '\\') {
|
||||
i += 1
|
||||
} else if (ch === quote) {
|
||||
quote = ''
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (ch === '/' && next === '/') {
|
||||
lineComment = true
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
if (ch === '/' && next === '*') {
|
||||
blockComment = true
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === '`') {
|
||||
quote = ch
|
||||
continue
|
||||
}
|
||||
if (ch === '{') depth += 1
|
||||
if (ch === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) return { start: match.index, objectStart, end: i }
|
||||
}
|
||||
}
|
||||
|
||||
throw new SyntaxError('export const meta object is not closed')
|
||||
}
|
||||
|
||||
export function workflowBody(source) {
|
||||
const meta = findMeta(source)
|
||||
const metaText = source.slice(meta.objectStart, meta.end + 1)
|
||||
new Function(`return (${metaText})`)
|
||||
|
||||
let suffix = source.slice(meta.end + 1)
|
||||
suffix = suffix.replace(/^\s*;?/, '')
|
||||
return source.slice(0, meta.start) + suffix
|
||||
}
|
||||
|
||||
export function checkSource(source) {
|
||||
const body = workflowBody(source)
|
||||
new AsyncFunction(...HOOK_NAMES, body)
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
const good = "export const meta = { name: 'ok', phases: [{ title: 'Guard' }] }\nconst x = 1\nif (x) return { ok: true }\n"
|
||||
const badBody = "export const meta = { name: 'bad' }\nif (\n"
|
||||
const badImportMeta = "export const meta = { name: 'bad-import-meta' }\nreturn import.meta.url\n"
|
||||
|
||||
checkSource(good)
|
||||
|
||||
for (const [name, source] of [['bad-body', badBody], ['bad-import-meta', badImportMeta]]) {
|
||||
let failed = false
|
||||
try {
|
||||
checkSource(source)
|
||||
} catch {
|
||||
failed = true
|
||||
}
|
||||
if (!failed) throw new Error(`selftest ${name} unexpectedly passed`)
|
||||
}
|
||||
|
||||
console.log('selftest ok')
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (process.argv.includes('--selftest')) {
|
||||
selftest()
|
||||
return
|
||||
}
|
||||
|
||||
const files = process.argv.slice(2)
|
||||
if (!files.length) {
|
||||
console.error('usage: node scripts/check-workflow-syntax.mjs <workflow.js> [...]')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
checkSource(readFileSync(file, 'utf8'))
|
||||
console.log(`ok ${file}`)
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,52 @@
|
||||
<?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">
|
||||
<!--
|
||||
kb-lint — nightly deterministic vault lint for Mnemazine (launchd template).
|
||||
|
||||
This is a TEMPLATE. launchd starts jobs with an empty PATH, so node is
|
||||
called by absolute path — generate a concrete plist locally
|
||||
(machine-specific paths stay out of the repo):
|
||||
|
||||
sed -e "s#__NODE__#$(command -v node)#g" \
|
||||
-e "s#__NODE_BIN__#$(dirname "$(command -v node)")#g" \
|
||||
-e "s#__ROOT__#$PWD#g" \
|
||||
scripts/com.mnemazine.kb-lint.plist.template \
|
||||
> ~/Library/LaunchAgents/com.mnemazine.kb-lint.plist
|
||||
launchctl load ~/Library/LaunchAgents/com.mnemazine.kb-lint.plist
|
||||
|
||||
Deactivate:
|
||||
launchctl unload ~/Library/LaunchAgents/com.mnemazine.kb-lint.plist
|
||||
|
||||
Runs nightly at 03:30. Markdown report lands in the vault
|
||||
(99 Система/_lint/), process log in /tmp/kb-lint.log.
|
||||
-->
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.mnemazine.kb-lint</string>
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>__NODE__</string>
|
||||
<string>__ROOT__/scripts/mnemazine-kb-lint.mjs</string>
|
||||
<string>--json</string>
|
||||
</array>
|
||||
<key>StartCalendarInterval</key>
|
||||
<dict>
|
||||
<key>Hour</key>
|
||||
<integer>3</integer>
|
||||
<key>Minute</key>
|
||||
<integer>30</integer>
|
||||
</dict>
|
||||
<key>EnvironmentVariables</key>
|
||||
<dict>
|
||||
<key>PATH</key>
|
||||
<string>__NODE_BIN__:/usr/local/bin:/usr/bin:/bin</string>
|
||||
</dict>
|
||||
<key>StandardOutPath</key>
|
||||
<string>/tmp/kb-lint.log</string>
|
||||
<key>StandardErrorPath</key>
|
||||
<string>/tmp/kb-lint.log</string>
|
||||
<key>RunAtLoad</key>
|
||||
<false/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,289 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
graphify_clean.py — durable post-processor for the Мнемозина knowledge graph.
|
||||
|
||||
Problem it solves
|
||||
------------------
|
||||
kb-refine notes share a fixed card template ("🎯 Как это поможет мне",
|
||||
"Когда использовать", "Связанные темы", "Достоверность", ...). graphify's
|
||||
semantic extractor emits every one of those section headers as its own node.
|
||||
On the 2026-06-04 audit those template fields were ~39% of all nodes (1046 of
|
||||
2873) and, because the same label appears in almost every note, they collapse
|
||||
into false mega-hubs that glue unrelated domains together — hiding the real
|
||||
connectivity of the graph.
|
||||
|
||||
This script runs AFTER `graphify ... --update` (or a full build) and cleans the
|
||||
final graph.json deterministically — no LLM, no tokens. It is idempotent: run it
|
||||
as many times as you like. Because it operates on the final merged graph, it also
|
||||
neutralises the semantic-cache re-injection problem (templates that the cache
|
||||
keeps re-adding are stripped on every pass).
|
||||
|
||||
What it does
|
||||
------------
|
||||
1. Back up graph.json -> .graph_preclean.json
|
||||
2. Drop template/structural nodes (curated blocklist + structural substrings),
|
||||
never touching file_type == "code".
|
||||
3. Merge duplicate concept nodes by normalized label (collapse "Юнит-экономика"
|
||||
that appears in 3 files into one node, rewiring edges) — this is what restores
|
||||
real cross-note connectivity.
|
||||
4. Drop self-loops, recluster, auto-label communities by their top-degree member.
|
||||
5. Rewrite graph.json (+ .graphify_labels.json), regenerate GRAPH_REPORT.md and
|
||||
graph.html.
|
||||
6. Print a before/after ledger AND surface any *new* high-frequency non-code label
|
||||
that is NOT yet in the blocklist, so a freshly-added template field gets flagged
|
||||
for review instead of silently inflating the graph.
|
||||
|
||||
Why a curated blocklist (not blind frequency)
|
||||
----------------------------------------------
|
||||
A blind "drop anything appearing >= N times" rule would, as the vault grows,
|
||||
eventually nuke genuine recurring concepts ("Claude Code", "Agent OS"). So the
|
||||
drop set is an explicit, reviewed list of kb-refine card fields. Frequency is used
|
||||
only to *surface candidates* for human review (--review), never to auto-drop.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python3 graphify_clean.py # clean the vault graph (default path)
|
||||
python3 graphify_clean.py /path/to/graph.json # clean a specific graph
|
||||
python3 graphify_clean.py --review # also list freq>=THRESHOLD labels not blocklisted
|
||||
python3 graphify_clean.py --no-viz # skip graph.html regeneration
|
||||
|
||||
Run it right after every graphify build/update of the Мнемозина vault.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
# Override with MNEMAZINE_VAULT or pass the graph path.
|
||||
_VAULT = Path(os.environ.get("MNEMAZINE_VAULT") or (Path(__file__).resolve().parents[1] / "vault"))
|
||||
DEFAULT_GRAPH = str(_VAULT / "graphify-out" / "graph.json")
|
||||
|
||||
# --- curated kb-refine card template fields (normalized: lowercased, ws-collapsed) ---
|
||||
# These are SECTION HEADERS, not knowledge. Reviewed from the 2026-06-04 audit.
|
||||
TEMPLATE_LABELS = {
|
||||
"как это поможет мне", "🎯 как это поможет мне",
|
||||
"когда использовать", "связанные темы", "связанные заметки",
|
||||
"что это и зачем", "что это",
|
||||
"достоверность", "достоверность и границы", "границы достоверности",
|
||||
"описание конечного результата",
|
||||
"чек-лист качества", "проверочный чек-лист", "проверка",
|
||||
"тип материала", "плейсхолдеры",
|
||||
"суть / как работает", "извлечённая суть", "извлеченная суть",
|
||||
"что было лишним или слабым", "что было слабым",
|
||||
"улучшенная версия", "готовая версия", "готовая версия (установка)",
|
||||
"что полезного в исходнике", "что улучшено",
|
||||
"как применять", "универсальный шаблон", "универсальный prompt",
|
||||
"источник", "источники", "источники внутри папки", "источники из пачки",
|
||||
"официальные источники",
|
||||
"установка", "быстрый старт", "риски", "ограничения", "контекст", "зачем",
|
||||
"важная оговорка", "короткий вывод", "итог", "вывод", "резюме", "название",
|
||||
"что уже зафиксировано",
|
||||
"два чек-листа полноты", "два обязательных чек-листа полноты",
|
||||
"источники и опорные документы", "источники и референсы",
|
||||
}
|
||||
|
||||
# structural / self-ingested files (substring match on normalized label)
|
||||
STRUCTURAL_SUBSTR = (
|
||||
"содержание", "оглавление", "мастер-индекс", "_community",
|
||||
"лог обработки", "code:json",
|
||||
)
|
||||
|
||||
# frequency threshold used ONLY to surface review candidates (never auto-drop)
|
||||
REVIEW_FREQ = 4
|
||||
|
||||
|
||||
def norm(s: str) -> str:
|
||||
return re.sub(r"\s+", " ", str(s).strip().lower())
|
||||
|
||||
|
||||
def load_graph(path: Path):
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
data = json.loads(path.read_text())
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
|
||||
|
||||
def is_code(G, n) -> bool:
|
||||
return G.nodes[n].get("file_type", "") == "code"
|
||||
|
||||
|
||||
def is_template(G, n) -> bool:
|
||||
if is_code(G, n):
|
||||
return False
|
||||
l = norm(G.nodes[n].get("label", n))
|
||||
return l in TEMPLATE_LABELS or any(s in l for s in STRUCTURAL_SUBSTR)
|
||||
|
||||
|
||||
def drop_templates(G):
|
||||
drop = [n for n in G.nodes if is_template(G, n)]
|
||||
counts = Counter(str(G.nodes[n].get("label", n))[:40] for n in drop)
|
||||
G.remove_nodes_from(drop)
|
||||
return len(drop), counts
|
||||
|
||||
|
||||
def merge_duplicate_concepts(G):
|
||||
"""Collapse non-code nodes that share a normalized label into one canonical
|
||||
(highest-degree) node, rewiring edges. Returns count of merged-away nodes."""
|
||||
groups = defaultdict(list)
|
||||
for n in G.nodes:
|
||||
if not is_code(G, n):
|
||||
groups[norm(G.nodes[n].get("label", n))].append(n)
|
||||
|
||||
mapping = {}
|
||||
for members in groups.values():
|
||||
if len(members) > 1:
|
||||
canon = max(members, key=lambda n: G.degree(n))
|
||||
for m in members:
|
||||
if m != canon:
|
||||
mapping[m] = canon
|
||||
|
||||
for src, canon in mapping.items():
|
||||
if src not in G:
|
||||
continue
|
||||
for nb in list(G.neighbors(src)):
|
||||
tgt = mapping.get(nb, nb)
|
||||
if tgt == canon or nb == canon:
|
||||
continue
|
||||
d = G.get_edge_data(src, nb) or {}
|
||||
G.add_edge(canon, tgt, **{k: v for k, v in d.items() if k not in ("source", "target")})
|
||||
G.remove_node(src)
|
||||
|
||||
import networkx as nx
|
||||
|
||||
G.remove_edges_from(list(nx.selfloop_edges(G)))
|
||||
return len(mapping)
|
||||
|
||||
|
||||
def components_stats(G):
|
||||
import networkx as nx
|
||||
|
||||
comps = list(nx.connected_components(G.to_undirected()))
|
||||
return len(comps), (max((len(c) for c in comps), default=0))
|
||||
|
||||
|
||||
def review_candidates(G):
|
||||
"""Non-code labels appearing >= REVIEW_FREQ times that are NOT blocklisted."""
|
||||
cnt = Counter(norm(G.nodes[n].get("label", n)) for n in G.nodes if not is_code(G, n))
|
||||
out = []
|
||||
for lbl, c in cnt.most_common():
|
||||
if c >= REVIEW_FREQ and lbl not in TEMPLATE_LABELS and not any(s in lbl for s in STRUCTURAL_SUBSTR):
|
||||
out.append((lbl, c))
|
||||
return out
|
||||
|
||||
|
||||
def short(s: str, n: int = 30) -> str:
|
||||
s = str(s)
|
||||
return (s[: n - 1] + "…") if len(s) > n else s
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="Clean the Мнемозина knowledge graph (durable post-graphify pass).")
|
||||
ap.add_argument("graph", nargs="?", default=DEFAULT_GRAPH, help="path to graph.json")
|
||||
ap.add_argument("--review", action="store_true", help="list freq>=%d labels not in blocklist" % REVIEW_FREQ)
|
||||
ap.add_argument("--no-viz", action="store_true", help="skip graph.html regeneration")
|
||||
args = ap.parse_args()
|
||||
|
||||
graph_path = Path(args.graph)
|
||||
if not graph_path.exists():
|
||||
print(f"error: {graph_path} not found", file=sys.stderr)
|
||||
return 1
|
||||
out_dir = graph_path.parent
|
||||
|
||||
try:
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.export import to_json
|
||||
except ImportError:
|
||||
print("error: graphify not importable in this interpreter", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
G = load_graph(graph_path)
|
||||
n0, e0 = G.number_of_nodes(), G.number_of_edges()
|
||||
comps0, big0 = components_stats(G)
|
||||
|
||||
# 1) backup
|
||||
(out_dir / ".graph_preclean.json").write_text(graph_path.read_text())
|
||||
|
||||
# 2) drop templates
|
||||
dropped, drop_counts = drop_templates(G)
|
||||
# 3) merge duplicate concepts
|
||||
merged = merge_duplicate_concepts(G)
|
||||
|
||||
n1, e1 = G.number_of_nodes(), G.number_of_edges()
|
||||
comps1, big1 = components_stats(G)
|
||||
|
||||
# 4) recluster + auto-label
|
||||
communities = cluster(G)
|
||||
cohesion = score_all(G, communities)
|
||||
labels = {}
|
||||
for c, members in communities.items():
|
||||
top = max(members, key=lambda n: G.degree(n))
|
||||
labels[c] = short(G.nodes[top].get("label", top))
|
||||
for n in members:
|
||||
G.nodes[n]["community"] = c
|
||||
|
||||
# 5) save graph + labels
|
||||
to_json(G, communities, str(graph_path), force=True)
|
||||
(out_dir / ".graphify_labels.json").write_text(
|
||||
json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False)
|
||||
)
|
||||
|
||||
# 5b) regenerate report + html
|
||||
try:
|
||||
from graphify.analyze import god_nodes, surprising_connections
|
||||
from graphify.detect import detect
|
||||
from graphify.report import generate
|
||||
|
||||
root = (out_dir / ".graphify_root")
|
||||
scan_root = Path(root.read_text().strip()) if root.exists() else out_dir.parent
|
||||
det = detect(scan_root)
|
||||
rep = generate(
|
||||
G, communities, cohesion, labels,
|
||||
god_nodes(G), surprising_connections(G, communities),
|
||||
det, {"input": 0, "output": 0}, str(scan_root),
|
||||
)
|
||||
(out_dir / "GRAPH_REPORT.md").write_text(rep)
|
||||
except Exception as exc: # report is non-critical
|
||||
print(f"warn: report not regenerated ({exc})", file=sys.stderr)
|
||||
|
||||
if not args.no_viz:
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
subprocess.run(["graphify", "export", "html"], cwd=str(out_dir.parent), check=False,
|
||||
capture_output=True, timeout=120)
|
||||
except Exception as exc:
|
||||
print(f"warn: html not regenerated ({exc})", file=sys.stderr)
|
||||
|
||||
# 6) ledger
|
||||
print("graphify_clean — ledger")
|
||||
print("─" * 46)
|
||||
print(f" nodes: {n0} → {n1} (dropped {dropped} templates, merged {merged} dups)")
|
||||
print(f" edges: {e0} → {e1}")
|
||||
print(f" components: {comps0} → {comps1}")
|
||||
print(f" largest: {big0} ({big0*100//max(n0,1)}%) → {big1} ({big1*100//max(n1,1)}%)")
|
||||
print(f" communities: {len(communities)}")
|
||||
if dropped:
|
||||
top = drop_counts.most_common(8)
|
||||
print(" top dropped: " + ", ".join(f"{k}×{v}" for k, v in top))
|
||||
|
||||
cands = review_candidates(G)
|
||||
if cands:
|
||||
print(f"\n ⚠ {len(cands)} non-blocklisted label(s) appear ≥{REVIEW_FREQ}× — review if template noise:")
|
||||
for lbl, c in cands[:12]:
|
||||
print(f" {c:3} {short(lbl, 48)}")
|
||||
print(" (add real template fields to TEMPLATE_LABELS; leave genuine concepts)")
|
||||
|
||||
if args.review and not cands:
|
||||
print(f"\n no non-blocklisted labels at freq ≥{REVIEW_FREQ} — blocklist is current.")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": { "type": "string" },
|
||||
"action": { "type": "string", "enum": ["deep", "light", "skip"] },
|
||||
"verified": { "type": "string" },
|
||||
"sources": { "type": "array", "items": { "type": "string" } },
|
||||
"lines_before": { "type": "number" },
|
||||
"lines_after": { "type": "number" },
|
||||
"summary": { "type": "string" },
|
||||
"community": { "type": "array", "items": { "type": "string" } }
|
||||
},
|
||||
"required": ["path", "action", "verified", "sources", "lines_before", "lines_after", "summary", "community"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
Executable
+195
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python3
|
||||
"""kb-fetch <url> [--allow-remote] [--timeout N] — один URL → один JSON в stdout.
|
||||
|
||||
Бесплатный каскад скрейпа Мнемозины (решение 2026-07-25, docs/PLAN + scrape-decision):
|
||||
ярус 0 markitdown — бинарники (pdf/docx/pptx/xlsx) и медиа-домены → стадия 0
|
||||
ярус 1 trafilatura — статический HTML (~80% случаев), русский проверен живьём
|
||||
ярус 2 needs_js — exit 2: агент сам эскалирует на Playwright MCP / WebFetch
|
||||
remote Jina Reader — ТОЛЬКО с --allow-remote и только публичное: квотный тариф,
|
||||
по правилу владельца это категория «платно», в автоматику не входит.
|
||||
Exit: 0 годный текст · 2 пусто/нужен JS · 3 заблокировано · 4 сеть/таймаут.
|
||||
Правило модели: ok=false → не выдумывать содержимое, пометить «источник недоступен».
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import certifi
|
||||
|
||||
# ponytail: trafilatura живёт в venv kb-web и не лежит на PATH — берём его напрямую,
|
||||
# фолбэк на PATH оставлен для чужих машин
|
||||
TRAFILATURA = os.environ.get(
|
||||
"MNEMAZINE_TRAFILATURA_BIN",
|
||||
next((c for c in (os.path.expanduser("~/.venvs/kb-web/bin/trafilatura"),)
|
||||
if os.path.exists(c)), "trafilatura"),
|
||||
)
|
||||
|
||||
SSL_CTX = ssl.create_default_context(cafile=certifi.where()) # venv-python macOS без системных корней
|
||||
|
||||
MEDIA_HOSTS = ("youtube.com", "youtu.be", "vimeo.com", "rutube.ru", "vk.com/video")
|
||||
BINARY_EXT = (".pdf", ".docx", ".pptx", ".xlsx", ".epub")
|
||||
CHALLENGE = ("Just a moment", "Checking your browser", "Проверка браузера", "cf-chl",
|
||||
"Enable JavaScript and cookies")
|
||||
MIN_CHARS = 400 # ponytail: порог «годного» текста; крутить по опыту прогонов
|
||||
UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
|
||||
|
||||
|
||||
def out(obj, code):
|
||||
print(json.dumps(obj, ensure_ascii=False))
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
def result(url, ok, tool, tier, md, reason=""):
|
||||
return {"ok": ok, "url": url, "tool": tool, "tier": tier, "reason": reason,
|
||||
"lang": "ru" if cyr_share(md) > 0.5 else "", "chars": len(md),
|
||||
"fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||
"markdown": md}
|
||||
|
||||
|
||||
def cyr_share(text):
|
||||
letters = [c for c in text if c.isalpha()]
|
||||
if not letters:
|
||||
return 0.0
|
||||
return sum(1 for c in letters if "Ѐ" <= c <= "ӿ") / len(letters)
|
||||
|
||||
|
||||
def mojibake(text):
|
||||
return any(m in text for m in ("Ð", "Ñ\x83", "�"))
|
||||
|
||||
|
||||
def boiler_ratio(text):
|
||||
lines = [l.strip() for l in text.splitlines() if l.strip()]
|
||||
if len(lines) < 8:
|
||||
return 0.0
|
||||
return 1 - len(set(lines)) / len(lines)
|
||||
|
||||
|
||||
def fetch_html(url, timeout):
|
||||
# кириллица в пути/квери валит urllib ascii-кодеком — percent-кодируем всё вне ASCII
|
||||
url = urllib.parse.quote(url, safe=":/?&=#%+@;,$!*'()[]~-._")
|
||||
req = urllib.request.Request(url, headers={"User-Agent": UA})
|
||||
with urllib.request.urlopen(req, timeout=timeout, context=SSL_CTX) as r:
|
||||
raw = r.read()
|
||||
ctype = r.headers.get("Content-Type", "")
|
||||
final = r.geturl()
|
||||
# charset живёт в HTTP-заголовке (легаси-рунет: koi8-r/1251 без <meta>) — из файла его
|
||||
# не восстановить, поэтому нормализуем в utf-8 здесь, до экстракции
|
||||
charset = ""
|
||||
if "charset=" in ctype.lower():
|
||||
charset = ctype.lower().split("charset=")[1].split(";")[0].strip()
|
||||
if charset and charset not in ("utf-8", "utf8"):
|
||||
try:
|
||||
text = raw.decode(charset, errors="replace")
|
||||
raw = text.encode("utf-8")
|
||||
except LookupError:
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
else:
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
if mojibake(text) and cyr_share(text) < 0.15:
|
||||
try:
|
||||
text = raw.decode("windows-1251", errors="replace")
|
||||
raw = text.encode("utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
return raw, text, ctype, final
|
||||
|
||||
|
||||
def run_trafilatura(raw):
|
||||
# HTML подаётся в stdin (флаг -i ждёт СПИСОК URL-ов, не документ); байты уже
|
||||
# нормализованы в utf-8 по HTTP-charset в fetch_html
|
||||
r = subprocess.run([TRAFILATURA, "--output-format", "markdown"], input=raw,
|
||||
capture_output=True, timeout=60)
|
||||
return (r.stdout or b"").decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def run_markitdown(target, timeout=120):
|
||||
# URL скачиваем сами (у markitdown свой fetch без наших сертификатов/UA), файл отдаём как есть
|
||||
if target.startswith("http"):
|
||||
req = urllib.request.Request(target, headers={"User-Agent": UA})
|
||||
with urllib.request.urlopen(req, timeout=60, context=SSL_CTX) as r:
|
||||
data = r.read()
|
||||
suffix = "." + target.split("?")[0].rstrip("/").split(".")[-1][:5]
|
||||
if "/" in suffix or len(suffix) < 3:
|
||||
suffix = ".bin"
|
||||
with tempfile.NamedTemporaryFile("wb", suffix=suffix, delete=False) as f:
|
||||
f.write(data)
|
||||
target = f.name
|
||||
r = subprocess.run(["markitdown", target], capture_output=True, text=True, timeout=timeout)
|
||||
return r.stdout or ""
|
||||
|
||||
|
||||
def main():
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
if not args:
|
||||
print("usage: kb-fetch <url> [--allow-remote] [--timeout N]", file=sys.stderr)
|
||||
sys.exit(4)
|
||||
url = args[0]
|
||||
allow_remote = "--allow-remote" in sys.argv
|
||||
timeout = 30
|
||||
if "--timeout" in sys.argv:
|
||||
timeout = int(sys.argv[sys.argv.index("--timeout") + 1])
|
||||
|
||||
low = url.lower()
|
||||
if any(h in low for h in MEDIA_HOSTS):
|
||||
out(result(url, False, "yt-dlp", 0, "", "media: гони через стадию 0 (transcribe)"), 2)
|
||||
if any(low.split("?")[0].endswith(e) for e in BINARY_EXT):
|
||||
try:
|
||||
md = run_markitdown(url)
|
||||
except Exception as e:
|
||||
out(result(url, False, "markitdown", 0, "", f"markitdown: {e}"), 4)
|
||||
code = 0 if len(md) >= MIN_CHARS else 2
|
||||
out(result(url, code == 0, "markitdown", 0, md, "" if code == 0 else "пустой конверт"), code)
|
||||
|
||||
try:
|
||||
raw, html, ctype, final = fetch_html(url, timeout)
|
||||
except urllib.error.HTTPError as e:
|
||||
code = 3 if e.code in (401, 403, 429, 451) else 4
|
||||
out(result(url, False, "curl", 1, "", f"http {e.code}"), code)
|
||||
except Exception as e:
|
||||
out(result(url, False, "curl", 1, "", f"сеть: {e}"), 4)
|
||||
|
||||
if "text/html" not in ctype and ctype:
|
||||
md = run_markitdown(url)
|
||||
code = 0 if len(md) >= MIN_CHARS else 2
|
||||
out(result(url, code == 0, "markitdown", 0, md, ctype if code else "пустой конверт"), code)
|
||||
|
||||
if any(m in html[:5000] for m in CHALLENGE):
|
||||
if allow_remote:
|
||||
try: # Jina — чужой IP снимает challenge; квотная категория, только явный флаг
|
||||
_, md, _, _ = fetch_html("https://r.jina.ai/" + url, max(timeout, 60))
|
||||
if len(md) >= MIN_CHARS and not any(m in md for m in CHALLENGE):
|
||||
out(result(url, True, "jina", 3, md, "remote-quota"), 0)
|
||||
except Exception:
|
||||
pass
|
||||
out(result(url, False, "curl", 1, "", "challenge/cloudflare"), 3)
|
||||
|
||||
md = run_trafilatura(raw)
|
||||
# два голоса: страница богата таблицами, а экстракт их срезал → добрать markitdown
|
||||
if html.count("<table") > 3 and "|---" not in md:
|
||||
md2 = run_markitdown(url)
|
||||
if len(md2) > len(md):
|
||||
md = md2
|
||||
tool = "markitdown"
|
||||
else:
|
||||
tool = "trafilatura"
|
||||
else:
|
||||
tool = "trafilatura"
|
||||
|
||||
ru_domain = any(t in low for t in (".ru/", ".xn--p1ai", ".su/")) or low.endswith((".ru", ".su"))
|
||||
if md and ru_domain and cyr_share(md) < 0.15:
|
||||
out(result(url, False, tool, 1, "", "кириллица <15% на ru-домене — битая экстракция"), 2)
|
||||
if md and (mojibake(md) or boiler_ratio(md) > 0.4):
|
||||
out(result(url, False, tool, 1, "", "мохибейк/boilerplate"), 2)
|
||||
if len(md) < MIN_CHARS:
|
||||
out(result(url, False, tool, 1, "", "needs_js: мало текста — эскалируй на Playwright MCP/WebFetch"), 2)
|
||||
out(result(url, True, tool, 1, md), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""kb-search "<query>" [--ru] [--max N] — метапоиск без ключей → JSON-массив в stdout.
|
||||
|
||||
Ярусы 3–4 цепочки поиска Мнемозины (первый ярус — встроенный WebSearch агента, он
|
||||
бесплатен и зовётся напрямую; этот скрипт нужен, когда WebSearch пуст или пайплайн
|
||||
работает вне харнесса). Внутри ddgs: brave → duckduckgo → mojeek → startpage; --ru
|
||||
добавляет yandex последним, потому что рунет он индексирует лучше всех, но и банит
|
||||
агрессивнее всех. Дисциплина: пауза 2с между бэкендами, один провал = следующий
|
||||
бэкенд, все провалились = exit 1 с честным «поиск деградировал» (это не ошибка
|
||||
скрипта — модель помечает факт как непроверенный, не выдумывает выдачу).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
DDGS = os.environ.get("MNEMAZINE_DDGS_BIN", "ddgs")
|
||||
BACKENDS = ["brave", "duckduckgo", "mojeek", "startpage"]
|
||||
|
||||
|
||||
def main():
|
||||
args = [a for a in sys.argv[1:] if not a.startswith("--")]
|
||||
if not args:
|
||||
print("usage: kb-search \"<query>\" [--ru] [--max N]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
query = args[0]
|
||||
ru = "--ru" in sys.argv
|
||||
max_n = 10
|
||||
if "--max" in sys.argv:
|
||||
max_n = int(sys.argv[sys.argv.index("--max") + 1])
|
||||
|
||||
backends = BACKENDS + (["yandex"] if ru else [])
|
||||
region = "ru-ru" if ru else "us-en"
|
||||
errors = []
|
||||
for i, b in enumerate(backends):
|
||||
if i:
|
||||
time.sleep(2)
|
||||
try:
|
||||
# ddgs пишет только в файл — /dev/stdout ломает его click-обвязку
|
||||
tmp = tempfile.mktemp(suffix=".json")
|
||||
subprocess.run(
|
||||
[DDGS, "text", "-q", query, "-m", str(max_n), "-b", b, "-r", region,
|
||||
"-o", tmp, "-nc"],
|
||||
capture_output=True, text=True, timeout=40)
|
||||
if not os.path.exists(tmp):
|
||||
errors.append(f"{b}: файл выдачи не создан")
|
||||
continue
|
||||
rows = json.load(open(tmp))
|
||||
os.unlink(tmp)
|
||||
if rows:
|
||||
print(json.dumps(
|
||||
[{"title": x.get("title", ""), "url": x.get("href", ""),
|
||||
"snippet": x.get("body", ""), "engine": b} for x in rows],
|
||||
ensure_ascii=False))
|
||||
return
|
||||
errors.append(f"{b}: 0 результатов")
|
||||
except Exception as e:
|
||||
errors.append(f"{b}: {e}")
|
||||
print(json.dumps({"ok": False, "reason": "поиск деградировал: " + "; ".join(errors)},
|
||||
ensure_ascii=False))
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,284 @@
|
||||
#!/usr/bin/env node
|
||||
// ПРИБОР КРИТЕРИЯ 3 (память агентов) — мастер §4. Контракт, а не документ о контракте.
|
||||
//
|
||||
// Коды выхода (мастер §4):
|
||||
// 0 — контракт жив: граф на месте и свежее последней ноты, MCP-сервер стартует и отвечает,
|
||||
// канал заявок жив, зомби-задач нет, ответ сервера несёт поле subject (§18.4).
|
||||
// 1 — любое звено мертво.
|
||||
// 2 — граф не найден (отличаем «нет графа» от «звено мертво» — враждебная проба П18).
|
||||
//
|
||||
// Живой vault: MNEMAZINE_VAULT → --vault → резолвер (личный vault по rules/structure.md).
|
||||
// Путь к графу берётся из шаблона config/mcp-vault.json и ВЫЧИСЛЯЕТСЯ из MNEMAZINE_VAULT,
|
||||
// а не зашит — иначе шаблон протухнет на чужой машине.
|
||||
//
|
||||
// Флаги:
|
||||
// --fix-config <path> привести шаблон mcp-vault.json к вычисляемому пути (идемпотентно)
|
||||
// --reap-stale-tasks зомби: status:running при мёртвом PID → stale, код 1
|
||||
// --require-channel-proof дополнительно требовать живой заявки, прошедшей воронку инбокса
|
||||
// --json машинный вывод
|
||||
import { parseArgs } from 'node:util'
|
||||
import { promises as fs, existsSync, readFileSync, writeFileSync, statSync } from 'node:fs'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import os from 'node:os'
|
||||
|
||||
const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const HOME = os.homedir()
|
||||
const CONFIG_TEMPLATE = path.join(REPO, 'config', 'mcp-vault.json')
|
||||
const SEMANTIC_TASK = path.join(REPO, '.mnemazine', 'state', 'semantic-graph-task.json')
|
||||
const INBOX = process.env.MNEMAZINE_INBOX || path.join(HOME, 'Desktop', 'Mnemazine Inbox')
|
||||
const STUB = '/path/to/vault'
|
||||
const PROBE_TIMEOUT_MS = 30000
|
||||
|
||||
// --- Резолвинг живого vault и графа --------------------------------------------------------------
|
||||
function resolveLiveVault(cli) {
|
||||
const v = cli || process.env.MNEMAZINE_VAULT || resolveVault({ requireExists: false })
|
||||
return path.resolve(v)
|
||||
}
|
||||
|
||||
/** Раскрывает ${MNEMAZINE_VAULT}, $MNEMAZINE_VAULT, ведущий ~ в аргументе шаблона. */
|
||||
function expandPath(raw, vault) {
|
||||
return raw
|
||||
.replace(/\$\{MNEMAZINE_VAULT\}/g, vault)
|
||||
.replace(/\$MNEMAZINE_VAULT\b/g, vault)
|
||||
.replace(/^~(?=\/)/, HOME)
|
||||
}
|
||||
|
||||
/** Достаёт последний аргумент (путь к графу) из шаблона mcp-vault.json. */
|
||||
function templateGraphArg() {
|
||||
const j = JSON.parse(readFileSync(CONFIG_TEMPLATE, 'utf8'))
|
||||
const args = j?.mcpServers?.['vault-graph']?.args
|
||||
if (!Array.isArray(args) || !args.length) throw new Error('mcp-vault.json: нет mcpServers.vault-graph.args')
|
||||
return String(args[args.length - 1])
|
||||
}
|
||||
|
||||
// --- MCP-проба: полный handshake по line-delimited JSON-RPC, тот же транспорт, что у Claude --------
|
||||
function mcpProbe(graphPath) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn('python3', ['-m', 'graphify.serve', graphPath], { stdio: ['pipe', 'pipe', 'pipe'] })
|
||||
const pending = new Map()
|
||||
let idc = 1, buf = '', errbuf = '', settled = false
|
||||
const finish = out => { if (settled) return; settled = true; clearTimeout(timer); try { child.kill('SIGKILL') } catch {}; resolve(out) }
|
||||
const timer = setTimeout(() => finish({ alive: false, reason: 'timeout', stderr: errbuf.slice(0, 400) }), PROBE_TIMEOUT_MS)
|
||||
child.on('error', e => finish({ alive: false, reason: `spawn: ${e.message}` }))
|
||||
child.stderr.on('data', d => { errbuf += d })
|
||||
child.stdout.on('data', d => {
|
||||
buf += d
|
||||
let i
|
||||
while ((i = buf.indexOf('\n')) >= 0) {
|
||||
const line = buf.slice(0, i); buf = buf.slice(i + 1)
|
||||
if (!line.trim()) continue
|
||||
let m; try { m = JSON.parse(line) } catch { continue }
|
||||
if (m.id != null && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id) }
|
||||
}
|
||||
})
|
||||
const send = (method, params) => new Promise(res => {
|
||||
const id = idc++; pending.set(id, res)
|
||||
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\n')
|
||||
})
|
||||
const notify = (method, params) => child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\n')
|
||||
;(async () => {
|
||||
try {
|
||||
const init = await send('initialize', { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'agent-memory-check', version: '1' } })
|
||||
if (init.error) return finish({ alive: false, reason: `initialize: ${JSON.stringify(init.error)}` })
|
||||
notify('notifications/initialized', {})
|
||||
const tools = (await send('tools/list', {})).result?.tools?.map(t => t.name) || []
|
||||
// god_nodes даёт гарантированно существующий label → get_node на нём проверяет контракт subject.
|
||||
const god = await send('tools/call', { name: 'god_nodes', arguments: { top_n: 1 } })
|
||||
const godText = (god.result?.content || []).map(c => c.text).join('\n')
|
||||
const label = (godText.match(/\d+\.\s+(.+?)\s+-\s+\d+\s+edges/) || [])[1] || ''
|
||||
let nodeText = ''
|
||||
if (label) {
|
||||
const node = await send('tools/call', { name: 'get_node', arguments: { label } })
|
||||
nodeText = (node.result?.content || []).map(c => c.text).join('\n')
|
||||
}
|
||||
const hasSubject = /^\s*Subject\s*:/im.test(nodeText)
|
||||
finish({ alive: true, serverInfo: init.result?.serverInfo || null, tools, probeLabel: label, nodeText, hasSubject })
|
||||
} catch (e) { finish({ alive: false, reason: e.message, stderr: errbuf.slice(0, 400) }) }
|
||||
})()
|
||||
})
|
||||
}
|
||||
|
||||
// --- Свежесть графа: mtime графа против самой свежей ноты + маркер needs_update --------------------
|
||||
const NON_CODE = new Set(['.md', '.txt', '.pdf', '.png', '.jpg', '.jpeg', '.webp', '.heic', '.tiff', '.gif'])
|
||||
async function newestNoteMtime(vault) {
|
||||
let newest = 0
|
||||
async function walk(dir) {
|
||||
for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (e.name.startsWith('graphify-out') || e.name === '.git' || e.name === '.obsidian') continue
|
||||
const p = path.join(dir, e.name)
|
||||
if (e.isDirectory()) await walk(p)
|
||||
else if (e.isFile() && NON_CODE.has(path.extname(e.name).toLowerCase())) {
|
||||
const s = await fs.stat(p).catch(() => null)
|
||||
if (s) newest = Math.max(newest, s.mtimeMs)
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
return newest
|
||||
}
|
||||
|
||||
// --- Зомби-задача: живость PID, не поле status ---------------------------------------------------
|
||||
function pidAlive(pid) {
|
||||
if (!Number.isInteger(pid) || pid <= 0) return false
|
||||
try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } // EPERM = жив, но чужой
|
||||
}
|
||||
function reapStaleTasks() {
|
||||
if (!existsSync(SEMANTIC_TASK)) return { zombie: false, reaped: false, note: 'файла задачи нет' }
|
||||
let t
|
||||
try { t = JSON.parse(readFileSync(SEMANTIC_TASK, 'utf8')) } catch { return { zombie: true, reaped: false, note: 'нечитаемый json' } }
|
||||
if (t.status !== 'running') return { zombie: false, reaped: false, status: t.status }
|
||||
if (pidAlive(t.pid)) return { zombie: false, reaped: false, status: 'running', pid: t.pid }
|
||||
const next = { ...t, status: 'stale', running: false, reaped_at: new Date().toISOString(), reaped_reason: `pid ${t.pid} мёртв при status:running` }
|
||||
writeFileSync(SEMANTIC_TASK, JSON.stringify(next, null, 2) + '\n')
|
||||
return { zombie: true, reaped: true, pid: t.pid }
|
||||
}
|
||||
|
||||
// --- Канал заявок: живая заявка, прошедшая воронку инбокса ----------------------------------------
|
||||
async function channelProof(vault) {
|
||||
// Проба: нота type: agent-research в корпусе (не шаблон), source: которой указывает на файл-заявку.
|
||||
const notes = []
|
||||
async function walk(dir) {
|
||||
for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (e.name.startsWith('graphify-out') || e.name === '.git') continue
|
||||
const p = path.join(dir, e.name)
|
||||
if (e.isDirectory()) await walk(p)
|
||||
else if (e.isFile() && e.name.endsWith('.md')) {
|
||||
const head = readFileSync(p, 'utf8').slice(0, 1200)
|
||||
if (/^type:\s*"?agent-research"?/m.test(head) && !/_ШАБЛОНЫ|_TEMPLATES|template/i.test(p) &&
|
||||
/^sources?:.*agent-research--/m.test(head)) notes.push(p)
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
const inboxLive = existsSync(INBOX)
|
||||
return { inboxLive, proofNotes: notes, proven: notes.length > 0 }
|
||||
}
|
||||
|
||||
// --- fix-config: привести шаблон к вычисляемому пути (идемпотентно) -------------------------------
|
||||
function fixConfig(target) {
|
||||
const file = target || CONFIG_TEMPLATE
|
||||
const j = JSON.parse(readFileSync(file, 'utf8'))
|
||||
const args = j?.mcpServers?.['vault-graph']?.args
|
||||
if (!Array.isArray(args) || !args.length) throw new Error('нет mcpServers.vault-graph.args')
|
||||
const want = '${MNEMAZINE_VAULT}/graphify-out/graph.json'
|
||||
const last = String(args[args.length - 1])
|
||||
if (last === want) return { changed: false, path: last }
|
||||
args[args.length - 1] = want
|
||||
writeFileSync(file, JSON.stringify(j, null, 2) + '\n')
|
||||
return { changed: true, from: last, to: want }
|
||||
}
|
||||
|
||||
// --- Главная сборка ------------------------------------------------------------------------------
|
||||
async function run({ vault: cliVault, requireChannelProof, json }) {
|
||||
const vault = resolveLiveVault(cliVault)
|
||||
const links = []
|
||||
const add = (name, ok, detail) => links.push({ name, ok, detail })
|
||||
|
||||
// Звено 0: шаблон вычисляем и без заглушки.
|
||||
let templateArg, graphPath
|
||||
try {
|
||||
templateArg = templateGraphArg()
|
||||
graphPath = expandPath(templateArg, vault)
|
||||
const clean = !templateArg.includes(STUB)
|
||||
const computed = /\$\{?MNEMAZINE_VAULT/.test(templateArg) || templateArg.includes(vault)
|
||||
add('template', clean && computed, { templateArg, graphPath, clean, computed })
|
||||
} catch (e) {
|
||||
add('template', false, { error: e.message })
|
||||
return report(links, 2, vault, json) // без шаблона граф не найти
|
||||
}
|
||||
|
||||
// Звено 1: граф найден (иначе код 2).
|
||||
const graphFound = existsSync(graphPath)
|
||||
add('graph_found', graphFound, { graphPath })
|
||||
if (!graphFound) return report(links, 2, vault, json)
|
||||
|
||||
// Звено 2: граф свежее последней ноты И нет needs_update.
|
||||
const graphMtime = statSync(graphPath).mtimeMs
|
||||
const needsUpdate = existsSync(path.join(vault, 'graphify-out', 'needs_update'))
|
||||
const newest = await newestNoteMtime(vault)
|
||||
const fresh = graphMtime >= newest && !needsUpdate
|
||||
add('graph_fresh', fresh, {
|
||||
graph_mtime: new Date(graphMtime).toISOString(),
|
||||
newest_note: newest ? new Date(newest).toISOString() : null,
|
||||
needs_update: needsUpdate,
|
||||
})
|
||||
|
||||
// Звено 3: зомби-задач нет.
|
||||
const z = reapStaleTasks()
|
||||
add('no_zombie', !z.zombie, z)
|
||||
|
||||
// Звено 4+5: сервер стартует, отвечает, и ответ несёт поле subject (§18.4).
|
||||
const probe = await mcpProbe(graphPath)
|
||||
add('server_alive', probe.alive, { serverInfo: probe.serverInfo, tools: probe.tools, reason: probe.reason, stderr: probe.stderr })
|
||||
add('subject_contract', probe.alive ? probe.hasSubject : false, {
|
||||
probeLabel: probe.probeLabel,
|
||||
hasSubject: probe.hasSubject,
|
||||
note: probe.alive && !probe.hasSubject
|
||||
? 'ответ get_node не несёт поля Subject: серверный шаблон graphify 1.8.1 его не отдаёт и граф не хранит subject на узлах — §18.4 не замкнуто'
|
||||
: undefined,
|
||||
})
|
||||
|
||||
// Звено 6: канал заявок.
|
||||
const ch = await channelProof(vault)
|
||||
add('channel', requireChannelProof ? ch.proven : ch.inboxLive, ch)
|
||||
|
||||
const code = links.every(l => l.ok) ? 0 : 1
|
||||
return report(links, code, vault, json)
|
||||
}
|
||||
|
||||
function report(links, code, vault, json) {
|
||||
if (json) {
|
||||
console.log(JSON.stringify({ ok: code === 0, code, vault, links }, null, 2))
|
||||
} else {
|
||||
console.log(`ПАМЯТЬ АГЕНТОВ — критерий 3 (vault: ${vault})`)
|
||||
for (const l of links) console.log(` ${l.ok ? '✓' : '✗'} ${l.name}${l.ok ? '' : ' ← ' + (l.detail?.note || l.detail?.reason || l.detail?.error || JSON.stringify(l.detail))}`)
|
||||
console.log(code === 0 ? 'контракт жив (0)' : code === 2 ? 'граф не найден (2)' : 'звено мертво (1)')
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const { strictEqual: eq, ok } = await import('node:assert')
|
||||
eq(expandPath('${MNEMAZINE_VAULT}/graphify-out/graph.json', '/V'), '/V/graphify-out/graph.json')
|
||||
eq(expandPath('$MNEMAZINE_VAULT/g.json', '/V'), '/V/g.json')
|
||||
eq(expandPath('~/vault-dir/g.json', 'x'), path.join(HOME, 'vault-dir/g.json'))
|
||||
eq(pidAlive(process.pid), true) // сам процесс жив
|
||||
eq(pidAlive(2 ** 31 - 1), false) // невозможный pid мёртв
|
||||
eq(pidAlive(0), false)
|
||||
ok(templateGraphArg().includes('MNEMAZINE_VAULT'), 'шаблон вычисляем из MNEMAZINE_VAULT')
|
||||
ok(!templateGraphArg().includes(STUB), 'в шаблоне нет заглушки')
|
||||
console.log('selftest ok')
|
||||
return 0
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { values: v } = parseArgs({
|
||||
options: {
|
||||
vault: { type: 'string' },
|
||||
'fix-config': { type: 'string' },
|
||||
'reap-stale-tasks': { type: 'boolean' },
|
||||
'require-channel-proof': { type: 'boolean' },
|
||||
selftest: { type: 'boolean' },
|
||||
json: { type: 'boolean' },
|
||||
},
|
||||
allowPositionals: true,
|
||||
})
|
||||
|
||||
if (v.selftest) return selftest()
|
||||
if (v['fix-config'] !== undefined) {
|
||||
const r = fixConfig(v['fix-config'] || undefined)
|
||||
console.log(v.json ? JSON.stringify(r) : (r.changed ? `шаблон исправлен: ${r.from} → ${r.to}` : `шаблон уже вычисляем: ${r.path}`))
|
||||
return 0
|
||||
}
|
||||
if (v['reap-stale-tasks']) {
|
||||
const r = reapStaleTasks()
|
||||
console.log(v.json ? JSON.stringify(r) : (r.zombie ? `зомби ${r.reaped ? 'снят' : 'найден'}: pid ${r.pid} — ${r.note || 'status:running при мёртвом pid'}` : `зомби-задач нет (${r.status || r.note || 'ok'})`))
|
||||
return r.zombie ? 1 : 0
|
||||
}
|
||||
return run({ vault: v.vault, requireChannelProof: v['require-channel-proof'], json: v.json })
|
||||
}
|
||||
|
||||
main().then(c => process.exit(c)).catch(e => { console.error(e?.message || e); process.exit(1) })
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
if (hit.includes('=')) return hit.split('=').slice(1).join('=')
|
||||
return argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const SUGGESTIONS = path.resolve(arg('suggestions', path.join(process.cwd(), 'reports', `${new Date().toISOString().slice(0, 10)}-capability-link-suggestions.json`)))
|
||||
const THRESHOLD = Number(arg('threshold', '35'))
|
||||
const APPLY = argv.includes('--apply')
|
||||
const LIMIT = Number(arg('limit', '0'))
|
||||
|
||||
const SKIP_REL = [
|
||||
/^99 Система\//,
|
||||
/^00 Входящие\//,
|
||||
/^AGENTS\.md$/,
|
||||
/^_ROUTING\.md$/,
|
||||
/^Лог обработки\.md$/,
|
||||
/^08 AI и Инструменты\/Capabilities\//
|
||||
]
|
||||
|
||||
const PURPOSES = {
|
||||
'graphify': 'построить или запросить граф связей перед реализацией знания',
|
||||
'knowledge-ops': 'сохранить, дедуплицировать и связать знание с другими слоями базы',
|
||||
'ui-ux-pro-max': 'применить готовые UI/UX-паттерны при превращении знания в интерфейс',
|
||||
'agent-browser': 'проверить веб-сценарий через управляемый браузер',
|
||||
'test-driven-development': 'реализовать методику через тесты и проверяемый цикл разработки',
|
||||
'context7': 'подтянуть свежую документацию перед кодом или настройкой',
|
||||
'firecrawl-mcp': 'извлечь содержимое сайта как источник для проверки и атомизации',
|
||||
'github': 'проверить репозиторий, issues, stars, commits или PR как evidence',
|
||||
'memory': 'сохранить устойчивую связь/факт в MCP memory после отбора',
|
||||
'ads': 'превратить знание в аудит или улучшение рекламной кампании',
|
||||
'remotion-official': 'реализовать видео/анимацию через Remotion',
|
||||
'playwright': 'проверить веб-интерфейс и сценарии в браузере',
|
||||
'documents': 'создать или отредактировать документальный артефакт',
|
||||
'local-doc-ops': 'локально обработать PDF/OCR/документы без утечки сырья',
|
||||
'codex-review': 'провести код-ревью перед применением в проекте'
|
||||
}
|
||||
|
||||
function purposeFor(s) {
|
||||
return PURPOSES[s.id] || String(s.description || '').replace(/\s+/g, ' ').slice(0, 120)
|
||||
}
|
||||
|
||||
function statusFor(s) {
|
||||
if (['mcp', 'plugin'].includes(s.type)) return 'local, включать только по задаче'
|
||||
return 'local/evaluate'
|
||||
}
|
||||
|
||||
function blockFor(suggestions) {
|
||||
const rows = suggestions.map(s => {
|
||||
const link = `[[_СПОСОБНОСТИ — реестр|${s.id}]]`
|
||||
return `| ${link} | ${s.type} | ${purposeFor(s)} | ${statusFor(s)} |`
|
||||
})
|
||||
return `\n## Применимые способности\n\n| Способность | Тип | Зачем здесь | Статус |\n|---|---|---|---|\n${rows.join('\n')}\n`
|
||||
}
|
||||
|
||||
function insertBlock(text, block) {
|
||||
if (/^##\s+Применимые способности\b/m.test(text)) return text
|
||||
const markers = [
|
||||
/^##\s+(Достоверность|Verification|Проверка)\b/m,
|
||||
/^##\s+(Связанные темы|Related Notes|Связи)\b/m,
|
||||
/^##\s+(Следующее действие|Next Action)\b/m
|
||||
]
|
||||
for (const re of markers) {
|
||||
const m = text.match(re)
|
||||
if (m && typeof m.index === 'number') {
|
||||
return `${text.slice(0, m.index).trimEnd()}\n${block}\n${text.slice(m.index)}`
|
||||
}
|
||||
}
|
||||
return `${text.trimEnd()}\n${block}\n`
|
||||
}
|
||||
|
||||
const data = JSON.parse(await fs.readFile(SUGGESTIONS, 'utf8'))
|
||||
const candidates = []
|
||||
for (const item of data.suggestions || []) {
|
||||
if (SKIP_REL.some(re => re.test(item.rel))) continue
|
||||
const picked = []
|
||||
const seen = new Set()
|
||||
for (const s of item.suggestions || []) {
|
||||
if (s.score < THRESHOLD || seen.has(s.id)) continue
|
||||
seen.add(s.id)
|
||||
picked.push(s)
|
||||
}
|
||||
if (picked.length) candidates.push({ ...item, suggestions: picked })
|
||||
}
|
||||
|
||||
const chosen = LIMIT > 0 ? candidates.slice(0, LIMIT) : candidates
|
||||
const changed = []
|
||||
const skipped = []
|
||||
|
||||
for (const item of chosen) {
|
||||
const file = path.join(VAULT, item.rel)
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
if (/^##\s+Применимые способности\b/m.test(text)) {
|
||||
skipped.push({ rel: item.rel, reason: 'already_has_block' })
|
||||
continue
|
||||
}
|
||||
const next = insertBlock(text, blockFor(item.suggestions))
|
||||
if (next !== text) {
|
||||
changed.push({ rel: item.rel, capabilities: item.suggestions.map(s => s.id) })
|
||||
if (APPLY) await fs.writeFile(file, next)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
apply: APPLY,
|
||||
threshold: THRESHOLD,
|
||||
candidates: candidates.length,
|
||||
changed: changed.length,
|
||||
skipped: skipped.length,
|
||||
changed_preview: changed.slice(0, 80)
|
||||
}, null, 2))
|
||||
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import crypto from 'node:crypto'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const INBOX = path.resolve(arg('inbox', process.env.MNEMAZINE_INBOX || path.join(os.homedir(), 'Desktop', 'Mnemazine Inbox')))
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const ARCHIVE = path.resolve(arg('archive', process.env.MNEMAZINE_ARCHIVE || path.join(INBOX, '_archive')))
|
||||
const APPLY = argv.includes('--apply')
|
||||
const ALLOW_WEAK_ARCHIVE = argv.includes('--allow-weak-archive')
|
||||
const VERBOSE = argv.includes('--verbose')
|
||||
const STARTED_AT = new Date().toISOString()
|
||||
|
||||
async function ensureDir(dir) {
|
||||
await fs.mkdir(dir, { recursive: true })
|
||||
}
|
||||
|
||||
async function sha256(file) {
|
||||
const hash = crypto.createHash('sha256')
|
||||
hash.update(await fs.readFile(file))
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
function sourceRef(hash) {
|
||||
return `local-media:${String(hash).slice(0, 16)}`
|
||||
}
|
||||
|
||||
function addSourceValues(raw, out) {
|
||||
for (const part of String(raw).replace(/^\[|\]$/g, '').split(',')) {
|
||||
const value = part.trim().replace(/^["']|["']$/g, '')
|
||||
if (value) out.add(path.basename(value))
|
||||
}
|
||||
}
|
||||
|
||||
// Provenance именованного файла (PDF/DOCX/…) — basename в `source:`/`sources:` frontmatter,
|
||||
// а не local-media-хэш скриншота. Без этого гейт не видит покрытие и не даёт архивировать.
|
||||
export function sourceBasenames(text) {
|
||||
const out = new Set()
|
||||
if (!text.startsWith('---')) return out
|
||||
const end = text.indexOf('\n---', 3)
|
||||
const fm = end === -1 ? text.slice(3) : text.slice(3, end)
|
||||
let inList = false
|
||||
for (const line of fm.split('\n')) {
|
||||
const kv = line.match(/^\s*(sources?):\s*(.*)$/i)
|
||||
if (kv) {
|
||||
inList = !kv[2].trim()
|
||||
addSourceValues(kv[2], out)
|
||||
continue
|
||||
}
|
||||
if (!inList) continue
|
||||
const item = line.match(/^\s*-\s*(.+)$/)
|
||||
if (item) addSourceValues(item[1], out)
|
||||
else if (line.trim()) inList = false
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function activeInboxFiles() {
|
||||
return (await fs.readdir(INBOX, { withFileTypes: true }).catch(() => []))
|
||||
.filter(item => item.isFile() && !item.name.startsWith('.'))
|
||||
.map(item => path.join(INBOX, item.name))
|
||||
}
|
||||
|
||||
async function vaultMarkdownFiles() {
|
||||
const out = []
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const file = path.join(dir, item.name)
|
||||
const rel = path.relative(VAULT, file).replace(/\\/g, '/')
|
||||
if (item.isDirectory()) {
|
||||
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
if (rel === '99 Система' || rel.startsWith('99 Система/')) continue
|
||||
await walk(file)
|
||||
} else if (item.isFile() && item.name.endsWith('.md')) {
|
||||
out.push(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(VAULT)
|
||||
return out
|
||||
}
|
||||
|
||||
async function buildCoverageIndex() {
|
||||
const notes = []
|
||||
for (const file of await vaultMarkdownFiles()) {
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
const sources = sourceBasenames(text)
|
||||
if (!text.includes('local-media:') && !text.includes('source_hash') && sources.size === 0) continue
|
||||
notes.push({ file, text, sources, strict: strictKnowledgeReady(text) })
|
||||
}
|
||||
return notes
|
||||
}
|
||||
|
||||
function coverageFor(hash, basename, notes) {
|
||||
const ref = sourceRef(hash)
|
||||
const matches = notes.filter(note =>
|
||||
note.text.includes(ref) || note.text.includes(hash) || note.sources.has(basename))
|
||||
const strictMatches = matches.filter(note => note.strict)
|
||||
const fullStrictMatches = strictMatches.filter(note => !path.basename(note.file).startsWith('synthesis-'))
|
||||
return {
|
||||
covered: fullStrictMatches.length > 0,
|
||||
weak_covered: matches.length > 0,
|
||||
strict_final: fullStrictMatches.length > 0,
|
||||
notes: matches.slice(0, 8).map(note => path.relative(VAULT, note.file)),
|
||||
strict_notes: fullStrictMatches.slice(0, 8).map(note => path.relative(VAULT, note.file)),
|
||||
synthesis_notes: strictMatches
|
||||
.filter(note => path.basename(note.file).startsWith('synthesis-'))
|
||||
.slice(0, 8)
|
||||
.map(note => path.relative(VAULT, note.file))
|
||||
}
|
||||
}
|
||||
|
||||
async function archiveFile(file, hash) {
|
||||
const month = new Date().toISOString().slice(0, 7)
|
||||
const dir = path.join(ARCHIVE, month)
|
||||
await ensureDir(dir)
|
||||
const ext = path.extname(file)
|
||||
let target = path.join(dir, `${hash}${ext}`)
|
||||
let suffix = 1
|
||||
while (existsSync(target)) {
|
||||
target = path.join(dir, `${hash}-${suffix}${ext}`)
|
||||
suffix += 1
|
||||
}
|
||||
await fs.rename(file, target)
|
||||
return target
|
||||
}
|
||||
|
||||
async function writeState(result) {
|
||||
await ensureDir(STATE)
|
||||
const stamp = STARTED_AT.replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
|
||||
const file = path.join(STATE, `archive-covered-${stamp}.json`)
|
||||
await fs.writeFile(file, `${JSON.stringify(result, null, 2)}\n`, 'utf8')
|
||||
return file
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (!existsSync(INBOX)) throw new Error(`Inbox not found: ${INBOX}`)
|
||||
const notes = await buildCoverageIndex()
|
||||
const files = await activeInboxFiles()
|
||||
const items = []
|
||||
for (const file of files) {
|
||||
const hash = await sha256(file)
|
||||
const coverage = coverageFor(hash, path.basename(file), notes)
|
||||
const canMove = ALLOW_WEAK_ARCHIVE ? coverage.weak_covered : coverage.strict_final
|
||||
items.push({
|
||||
file,
|
||||
name: path.basename(file),
|
||||
hash,
|
||||
source_ref: sourceRef(hash),
|
||||
covered: coverage.covered,
|
||||
weak_covered: coverage.weak_covered,
|
||||
strict_final: coverage.strict_final,
|
||||
notes: coverage.notes,
|
||||
strict_notes: coverage.strict_notes,
|
||||
synthesis_notes: coverage.synthesis_notes,
|
||||
action: canMove ? (APPLY ? 'archive' : 'would_archive') : 'keep'
|
||||
})
|
||||
}
|
||||
|
||||
const moved = []
|
||||
if (APPLY) {
|
||||
for (const item of items.filter(item => item.action === 'archive')) {
|
||||
item.archived_to = await archiveFile(item.file, item.hash)
|
||||
moved.push(item.archived_to)
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
ok: true,
|
||||
apply: APPLY,
|
||||
allow_weak_archive: ALLOW_WEAK_ARCHIVE,
|
||||
strict_final: !ALLOW_WEAK_ARCHIVE,
|
||||
inbox: INBOX,
|
||||
vault: VAULT,
|
||||
archive: ARCHIVE,
|
||||
total: items.length,
|
||||
covered: items.filter(item => item.covered).length,
|
||||
weak_covered: items.filter(item => item.weak_covered).length,
|
||||
final_covered: items.filter(item => item.strict_final).length,
|
||||
missing: items.filter(item => !item.covered).length,
|
||||
movable: items.filter(item => ALLOW_WEAK_ARCHIVE ? item.weak_covered : item.strict_final).length,
|
||||
moved: moved.length,
|
||||
kept: items.filter(item => item.action === 'keep').length,
|
||||
started_at: STARTED_AT,
|
||||
finished_at: new Date().toISOString(),
|
||||
items
|
||||
}
|
||||
result.state_file = await writeState(result)
|
||||
const summary = VERBOSE ? result : { ...result, items: undefined }
|
||||
console.log(JSON.stringify(summary, null, 2))
|
||||
if (result.missing > 0 || (result.total > 0 && result.movable === 0)) process.exitCode = 2
|
||||
}
|
||||
|
||||
// запускаем скан только при прямом вызове — импорт (тесты) не должен трогать инбокс
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main().catch(error => {
|
||||
console.error(error.message || error)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { spawn } from 'node:child_process'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function hasFlag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(item => item === `--${name}` || item.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
function args(name) {
|
||||
const out = []
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const item = argv[i]
|
||||
if (item === `--${name}`) out.push(argv[++i] || '')
|
||||
else if (item.startsWith(`--${name}=`)) out.push(item.split('=').slice(1).join('='))
|
||||
}
|
||||
return out.filter(Boolean)
|
||||
}
|
||||
|
||||
function shellQuote(value) {
|
||||
return `'${String(value).replace(/'/g, `'\\''`)}'`
|
||||
}
|
||||
|
||||
function parseManifest(text) {
|
||||
return String(text || '')
|
||||
.split(/\r?\n/)
|
||||
.map(line => line.replace(/\s+#.*$/, '').trim())
|
||||
.filter(line => line && !line.startsWith('#'))
|
||||
}
|
||||
|
||||
const FORBIDDEN_TARGET_PATTERNS = [
|
||||
/^\.env(?:\.|$)/,
|
||||
/(^|\/)\.env(?:\.|$)/,
|
||||
/(^|\/)\.git(?:\/|$)/,
|
||||
/(^|\/)node_modules(?:\/|$)/,
|
||||
/(^|\/)\.ssh(?:\/|$)/,
|
||||
/(^|\/)\.mnemazine\/(archive|backlog|cache|config(?:\.|\/|$)|config\.env|known_hosts|quarantine|rebuild|state|tmp)(?:\/|$)/,
|
||||
/(^|\/)\.codex\/sessions(?:\/|$)/,
|
||||
/(^|\/)\.claude\/projects(?:\/|$)/,
|
||||
/(^|\/)reports(?:\/|$)/,
|
||||
/(^|\/)graphify-out\/cache(?:\/|$)/
|
||||
]
|
||||
|
||||
const FORBIDDEN_NAME = /(^|[/._-])(secret|secrets|token|tokens|credential|credentials|password|passwd|keychain|private-key|id_rsa|oauth)([/._-]|$)/i
|
||||
const TOKEN_LIKE = /gh[opusr]_[A-Za-z0-9_]{20,}|(^|[^A-Za-z0-9])sk-[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{20,}|(AKIA|ASIA)[A-Z0-9]{16}|glpat-[A-Za-z0-9_-]{20,}|AIza[A-Za-z0-9_-]{30,}|eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----/
|
||||
|
||||
function cleanRel(rel, label = 'path') {
|
||||
if (!rel || rel.includes('\0')) throw new Error(`empty or invalid ${label}`)
|
||||
if (path.isAbsolute(rel)) throw new Error(`absolute ${label} is not allowed: ${rel}`)
|
||||
const normalized = path.posix.normalize(rel.replaceAll('\\', '/'))
|
||||
if (normalized === '.' || normalized.startsWith('../') || normalized.includes('/../')) {
|
||||
throw new Error(`${label} escapes root: ${rel}`)
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function assertAllowedTarget(target) {
|
||||
const hit = FORBIDDEN_TARGET_PATTERNS.find(re => re.test(target))
|
||||
if (hit || FORBIDDEN_NAME.test(target)) throw new Error(`forbidden mirror target: ${target}`)
|
||||
}
|
||||
|
||||
function parseEntry(line, { home }) {
|
||||
const [kind, rest] = line.includes(':') ? line.split(/:(.*)/s) : ['home', line]
|
||||
const sourceRel = cleanRel(rest, 'manifest path')
|
||||
if (kind === 'repo') {
|
||||
const target = cleanRel(path.posix.join('Проекты/mnemazine', sourceRel), 'target')
|
||||
assertAllowedTarget(target)
|
||||
return { kind, source: path.join(ROOT, sourceRel), target }
|
||||
}
|
||||
if (kind === 'home') {
|
||||
const target = cleanRel(sourceRel, 'target')
|
||||
assertAllowedTarget(target)
|
||||
return { kind, source: path.join(home, sourceRel), target }
|
||||
}
|
||||
throw new Error(`unknown manifest entry kind "${kind}" in: ${line}`)
|
||||
}
|
||||
|
||||
async function readManifest(file, { home, repoOnly = false } = {}) {
|
||||
const raw = await fs.readFile(file, 'utf8')
|
||||
const entries = parseManifest(raw).map(line => parseEntry(line, { home }))
|
||||
return repoOnly ? entries.filter(entry => entry.kind === 'repo') : entries
|
||||
}
|
||||
|
||||
async function scanPayload(entry) {
|
||||
if (FORBIDDEN_NAME.test(path.basename(entry.source))) throw new Error(`forbidden mirror source name: ${entry.source}`)
|
||||
const stat = await fs.lstat(entry.source)
|
||||
if (!stat.isFile()) throw new Error(`mirror source is not a regular file: ${entry.source}`)
|
||||
if (stat.isSymbolicLink()) throw new Error(`mirror source symlink refused: ${entry.source}`)
|
||||
const body = await fs.readFile(entry.source, 'utf8').catch(() => '')
|
||||
if (TOKEN_LIKE.test(body)) throw new Error(`token-like payload refused: ${entry.target}`)
|
||||
}
|
||||
|
||||
async function stageEntries(entries, stageRoot) {
|
||||
for (const entry of entries) {
|
||||
await scanPayload(entry)
|
||||
const target = path.join(stageRoot, entry.target)
|
||||
await fs.mkdir(path.dirname(target), { recursive: true })
|
||||
await fs.copyFile(entry.source, target)
|
||||
}
|
||||
}
|
||||
|
||||
function sshArgs({ sshKey, knownHosts, sshOptions }) {
|
||||
const out = ['ssh', '-o', 'BatchMode=yes']
|
||||
if (sshKey) out.push('-i', sshKey)
|
||||
if (knownHosts) out.push('-o', `UserKnownHostsFile=${knownHosts}`, '-o', 'StrictHostKeyChecking=yes')
|
||||
out.push(...sshOptions.flatMap(item => ['-o', item]))
|
||||
return out
|
||||
}
|
||||
|
||||
function buildRsyncArgs({ dest, sshKey, knownHosts, sshOptions, dryRun }) {
|
||||
return [
|
||||
'-av',
|
||||
...(dryRun ? ['-n'] : []),
|
||||
'-e', sshArgs({ sshKey, knownHosts, sshOptions }).map(shellQuote).join(' '),
|
||||
'./',
|
||||
dest
|
||||
]
|
||||
}
|
||||
|
||||
function run(command, commandArgs, cwd) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(command, commandArgs, { cwd, env: process.env, stdio: 'inherit' })
|
||||
child.on('close', code => resolve(code ?? 1))
|
||||
child.on('error', error => {
|
||||
console.error(error.message)
|
||||
resolve(1)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-mirror-selftest-'))
|
||||
const repo = path.join(temp, 'repo')
|
||||
const home = path.join(temp, 'home')
|
||||
await fs.mkdir(path.join(repo, 'scripts'), { recursive: true })
|
||||
await fs.mkdir(path.join(home, '.agents'), { recursive: true })
|
||||
await fs.writeFile(path.join(repo, 'package.json'), '{}\n', 'utf8')
|
||||
await fs.writeFile(path.join(home, '.agents/SHARED.md'), '# shared\n', 'utf8')
|
||||
const manifest = path.join(temp, 'manifest.txt')
|
||||
await fs.writeFile(manifest, 'repo:package.json\nhome:.agents/SHARED.md\n', 'utf8')
|
||||
const entries = await readManifest(manifest, { home })
|
||||
if (entries.length !== 2 || entries[0].target !== 'Проекты/mnemazine/package.json') throw new Error('selftest manifest mapping failed')
|
||||
const stage = path.join(temp, 'stage')
|
||||
await stageEntries(entries, stage)
|
||||
if (!existsSync(path.join(stage, 'Проекты/mnemazine/package.json'))) throw new Error('selftest staging repo file failed')
|
||||
const repoOnly = await readManifest(manifest, { home: path.join(temp, 'clean-home'), repoOnly: true })
|
||||
if (repoOnly.length !== 1) throw new Error('selftest repo-only failed')
|
||||
for (const bad of ['home:.env', 'home:.ssh/id_rsa', 'repo:../x', 'repo:secret-token.txt']) {
|
||||
let threw = false
|
||||
try { parseEntry(bad, { home }) } catch { threw = true }
|
||||
if (!threw) throw new Error(`selftest accepted forbidden entry: ${bad}`)
|
||||
}
|
||||
const rsync = buildRsyncArgs({ dest: 'host:/x/', sshKey: '/k', knownHosts: '/known hosts', sshOptions: ['Port=22'], dryRun: true })
|
||||
if (!rsync.includes('-n') || rsync.join(' ').includes(`StrictHostKeyChecking=${'no'}`)) throw new Error('selftest rsync args failed')
|
||||
await fs.rm(temp, { recursive: true, force: true })
|
||||
console.log(JSON.stringify({ ok: true }, null, 2))
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (hasFlag('selftest')) return selftest()
|
||||
if (arg('ssh-options')) throw new Error('--ssh-options is unsafe for quoted values; use repeated --ssh-option Name=value or MNEMAZINE_MIRROR_SSH_OPTIONS_JSON.')
|
||||
|
||||
const manifest = path.resolve(arg('manifest', process.env.MNEMAZINE_MIRROR_MANIFEST || path.join(ROOT, 'config/athena-mirror-manifest.txt')))
|
||||
const home = path.resolve(arg('home', process.env.MNEMAZINE_MIRROR_HOME || os.homedir()))
|
||||
const dest = arg('dest', process.env.MNEMAZINE_MIRROR_DEST || '')
|
||||
const sshKey = arg('ssh-key', process.env.MNEMAZINE_MIRROR_SSH_KEY || '')
|
||||
const knownHosts = arg('known-hosts', process.env.MNEMAZINE_MIRROR_KNOWN_HOSTS || '')
|
||||
const envOptions = process.env.MNEMAZINE_MIRROR_SSH_OPTIONS_JSON ? JSON.parse(process.env.MNEMAZINE_MIRROR_SSH_OPTIONS_JSON) : []
|
||||
const sshOptions = [...args('ssh-option'), ...envOptions]
|
||||
const apply = hasFlag('apply')
|
||||
const dryRun = !apply || hasFlag('dry-run')
|
||||
const repoOnly = hasFlag('repo-only')
|
||||
const entries = await readManifest(manifest, { home, repoOnly })
|
||||
const missing = entries.filter(entry => !existsSync(entry.source))
|
||||
if (missing.length) throw new Error(`mirror manifest has missing files:\n${missing.map(item => `- ${item.kind}:${item.target}`).join('\n')}`)
|
||||
if (hasFlag('check')) {
|
||||
for (const entry of entries) await scanPayload(entry)
|
||||
console.log(JSON.stringify({ ok: true, manifest, home, repo: ROOT, entries: entries.length, repo_only: repoOnly }, null, 2))
|
||||
return
|
||||
}
|
||||
if (!dest) throw new Error('Set MNEMAZINE_MIRROR_DEST or pass --dest host:/path/. Default run is dry-run; add --apply for remote write.')
|
||||
const stage = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-mirror-stage-'))
|
||||
try {
|
||||
await stageEntries(entries, stage)
|
||||
const rsync = buildRsyncArgs({ dest, sshKey, knownHosts, sshOptions, dryRun })
|
||||
console.log(JSON.stringify({ ok: true, dry_run: dryRun, manifest, files: entries.length, dest, stage }, null, 2))
|
||||
const code = await run('rsync', rsync, stage)
|
||||
process.exit(code)
|
||||
} finally {
|
||||
await fs.rm(stage, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(error.message || error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,310 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
if (hit.includes('=')) return hit.split('=').slice(1).join('=')
|
||||
return argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const ROOT = path.resolve(process.cwd())
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const OUT_DIR = path.resolve(arg('out', path.join(ROOT, 'reports')))
|
||||
const LIMIT = Number(arg('limit', '80'))
|
||||
|
||||
const EXCLUDED_PARTS = new Set(['.git', '.obsidian'])
|
||||
const SYSTEM_REL = /^99 Система\/(_legacy-index|Лог обработки|_last-session-review|_run-observability|_ROUTING|Agent_Handoff_Graph|Nova_Radar|00 СИСТЕМА|Паспорта_агентов_Мнемозины)/
|
||||
const INDEX_FILE = /(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ|CAPABILITIES|СПОСОБНОСТИ.*)\.(md|json)$/
|
||||
const SYSTEM_ROOT_FILES = new Set([
|
||||
'AGENTS.md',
|
||||
'CLAUDE.md',
|
||||
'_ROUTING.md',
|
||||
'_МАСТЕР-ИНДЕКС.md',
|
||||
'_ШАБЛОНЫ.md',
|
||||
'Лог обработки.md'
|
||||
])
|
||||
|
||||
const CANON_SECTIONS = [
|
||||
'00 Входящие',
|
||||
'01 Обо мне',
|
||||
'01 Право и Юриспруденция',
|
||||
'02 Бизнес и Предпринимательство',
|
||||
'02 Здоровье',
|
||||
'02 Знания',
|
||||
'03 Проекты',
|
||||
'04 Образование',
|
||||
'05 Кино и Сериалы',
|
||||
'06 Промты',
|
||||
'07 Бизнес и Финансы',
|
||||
'08 AI и Инструменты',
|
||||
'09 Личная продуктивность',
|
||||
'09 Технологии и Разработка',
|
||||
'99 Система'
|
||||
]
|
||||
|
||||
const SECTION_ALIASES = new Map([
|
||||
['09 Технологии', '09 Технологии и Разработка'],
|
||||
['09 Техническое', '09 Технологии и Разработка'],
|
||||
['05 Продуктивность и Процессы', '09 Личная продуктивность'],
|
||||
['07 Скиллы', '08 AI и Инструменты/skills']
|
||||
])
|
||||
|
||||
const RAW_PATTERNS = [
|
||||
[/raw\s+ocr/i, 'raw OCR'],
|
||||
[/сырой\s+ocr/i, 'сырой OCR'],
|
||||
[/Локальное извлечение/i, 'локальное извлечение'],
|
||||
[/intake-draft/i, 'intake draft'],
|
||||
[/temp_image/i, 'temp image'],
|
||||
[/\bIMG_\d+/i, 'raw image filename'],
|
||||
[/\.(WEBP|PNG|JPE?G)\b/i, 'raw image extension'],
|
||||
[/TODO:\s*rewrite/i, 'rewrite TODO'],
|
||||
[/скриншот\s+без\s+контекста/i, 'screenshot without context']
|
||||
]
|
||||
|
||||
const HEADING_RULES = {
|
||||
meaning: [/^##+\s+(Что это|Суть|Что это и зачем|What This Is)(?:\s|$)/im],
|
||||
value: [/^##+\s+(Зачем|Зачем мне|Как это поможет|Почему важно|Why It Matters)(?:\s|$)/im],
|
||||
use: [/^##+\s+(Как применить|Как использовать|Когда использовать|How To Use)(?:\s|$)/im],
|
||||
source: [/^##+\s+(Источник|Источники|Source|Sources|Источники и подтверждения)(?:\s|$)/im, /\bsource(_url)?:\s*["']?[^"'\n]+/i],
|
||||
verification: [/^##+\s+(Достоверность|Проверка|Верификация|Verification|Риски и проверки)(?:\s|$)/im, /\bverified:\s*["']?[^"'\n]+/i],
|
||||
related: [/^##+\s+(Связанные темы|Related Notes|Связи)(?:\s|$)/im, /\[\[[^\]]+\]\]/]
|
||||
}
|
||||
|
||||
function shouldSkip(rel) {
|
||||
const parts = rel.split(path.sep)
|
||||
return parts.some(part => EXCLUDED_PARTS.has(part) || part.startsWith('graphify-out'))
|
||||
}
|
||||
|
||||
async function walk(dir) {
|
||||
const out = []
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const p = path.join(dir, item.name)
|
||||
if (item.isDirectory()) out.push(...await walk(p))
|
||||
else if (item.isFile() && item.name.endsWith('.md')) out.push(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function frontmatter(text) {
|
||||
if (!text.startsWith('---\n')) return {}
|
||||
const end = text.indexOf('\n---', 4)
|
||||
if (end === -1) return {}
|
||||
const body = text.slice(4, end)
|
||||
const data = {}
|
||||
for (const line of body.split('\n')) {
|
||||
const m = line.match(/^([A-Za-zА-Яа-я0-9_-]+):\s*(.*)$/)
|
||||
if (!m) continue
|
||||
data[m[1]] = m[2].trim().replace(/^['"]|['"]$/g, '')
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
function topSection(rel) {
|
||||
if (!rel.includes(path.sep)) {
|
||||
if (/^(AGENTS|CLAUDE|Лог обработки|_ROUTING|_МАСТЕР-ИНДЕКС|_COMMUNITY_)/.test(rel)) return '99 Система'
|
||||
}
|
||||
return rel.split(path.sep)[0] || ''
|
||||
}
|
||||
|
||||
function titleFrom(file, text, fm) {
|
||||
if (fm.title) return fm.title
|
||||
const h1 = text.match(/^#\s+(.+)$/m)
|
||||
if (h1) return h1[1].trim()
|
||||
return path.basename(file, '.md')
|
||||
}
|
||||
|
||||
function inferSection(note) {
|
||||
const title = String(note.title || '').toLowerCase()
|
||||
const tags = String(note.fm.tags || '').toLowerCase()
|
||||
const type = String(note.fm.type || '').toLowerCase()
|
||||
const pathHint = note.rel.toLowerCase()
|
||||
const section = String(note.section || '')
|
||||
const isCapability = note.rel.includes('/Capabilities/') || section === '08 AI и Инструменты' && /способност|capabilit/i.test(pathHint)
|
||||
|
||||
if (/^_community_/i.test(note.basename)) return '99 Система'
|
||||
if (section === '06 Промты' || pathHint.startsWith('06 промты/') || type === 'prompt') return '06 Промты'
|
||||
if (pathHint.startsWith('08 ai и инструменты/skills/')) return '08 AI и Инструменты'
|
||||
if (section === '08 AI и Инструменты' && (pathHint.includes('/claude code/') || pathHint.includes('/project structure/') || /^ai-инструменты/.test(title))) return '08 AI и Инструменты'
|
||||
if (section === '09 Технологии и Разработка' && /database|api|gateway|queue|sre|frontend|backend|erd|nvr|analytics|scanner|code review|fraud|rag|парсинг|уязвим|база данных|мониторинг|newsletter|confluence|код|сканер/.test(title)) return '09 Технологии и Разработка'
|
||||
if (section === '02 Бизнес и Предпринимательство' && /marketing|monetization|маркетинг|продаж|бизнес|saas|open-source/.test(title + ' ' + pathHint)) return '02 Бизнес и Предпринимательство'
|
||||
if (section === '07 Бизнес и Финансы' && /profit|cash flow|ltv|cac|payback|юнит-эконом|прибыл|финанс/.test(title)) return '07 Бизнес и Финансы'
|
||||
if (pathHint.startsWith('03 проекты/athenaos/')) return '03 Проекты'
|
||||
if (pathHint.startsWith('08 ai и инструменты/claude code/second brain/')) return '08 AI и Инструменты'
|
||||
if (pathHint.startsWith('08 ai и инструменты/mcp/')) return '08 AI и Инструменты'
|
||||
if (isCapability) return '08 AI и Инструменты'
|
||||
if (/^99 система\//.test(pathHint) || /мнемозина|vault|индекс|агентн[ыи]й конвейер|лог обработки|community \d+|^протокол[_\s-]/.test(title)) return '99 Система'
|
||||
if (/обо мне|биограф|личный профиль|профиль владельца/.test(title)) return '01 Обо мне'
|
||||
if (/(^|\s)право(\s|$)|правов|юрид|договор|(^|\s)иск(а|и|ом|ов)?(\s|$)|(^|\s)суд(ы|а|ом|ебн)?(\s|$)|фемида|корпоративн/.test(title)) return '01 Право и Юриспруденция'
|
||||
if (/trading|трейдинг|bloomberg|инвест|бирж|финанс|financial|hedge|хедж|fund|фонд|рын[оа]к|акци[ия]|portfolio|портфел/i.test(title)) return '07 Бизнес и Финансы'
|
||||
if (/здоров|(^|\s)сон(\s|$)|трениров|питани|ментальн|медицин|врач|болезн/.test(title)) return '02 Здоровье'
|
||||
if (/бизнес|стартап|продаж|маркетинг|gtm|unit economics|cash flow|юнит-эконом/.test(title)) return '02 Бизнес и Предпринимательство'
|
||||
if (/кино|сериал|фильм|box office/.test(title)) return '05 Кино и Сериалы'
|
||||
if (/prompt|промпт|шаблон ответа|system prompt/.test(title) || type === 'prompt') return '06 Промты'
|
||||
if (/claude|codex|agent|агент|mcp|llm|rag|ai|нейросет|скилл|skill|github|open-source|browser|ocr|chat|hyperframes|librechat/.test(title) || tags.includes('#ai')) return '08 AI и Инструменты'
|
||||
if (/react|next\.js|api|backend|frontend|monorepo|serverless|архитектур|разработк|код|база данных|парсинг/.test(title)) return '09 Технологии и Разработка'
|
||||
if (/фокус|продуктив|gtd|para|deep work|flow|планиров/.test(title)) return '09 Личная продуктивность'
|
||||
if (/обуч|курс|книга|ментор|образован|learn/.test(title)) return '04 Образование'
|
||||
return note.section || '02 Знания'
|
||||
}
|
||||
|
||||
function canonFlags(note) {
|
||||
const flags = []
|
||||
const soft = []
|
||||
const isSystem = SYSTEM_ROOT_FILES.has(note.rel) || SYSTEM_REL.test(note.rel) || INDEX_FILE.test(note.rel) || note.rel.includes('/Capabilities/_')
|
||||
const isAtomizedSource = /^##\s+Атомизировано(?:\s|$)/m.test(note.text)
|
||||
const requiredCanonPresent = Object.values(HEADING_RULES).every(rules => rules.some(re => re.test(note.text)))
|
||||
const processedType = /^(level2-atom|canonical-summary|tool-record|tool|tool-reference|reference|method|architecture|learning-resource|capability-method|capability-policy|frontend-stack|safety-method|weak-source|archived-reference|project-plan|prompt|business-method)$/i.test(String(note.fm.type || ''))
|
||||
const isProcessedCanon = String(note.fm.status || '').toLowerCase() === 'processed' && requiredCanonPresent && processedType
|
||||
|
||||
if (!isSystem && !isAtomizedSource) {
|
||||
for (const [key, rules] of Object.entries(HEADING_RULES)) {
|
||||
if (!rules.some(re => re.test(note.text))) flags.push(`missing:${key}`)
|
||||
}
|
||||
} else if (isAtomizedSource) {
|
||||
soft.push('atomized-source')
|
||||
}
|
||||
|
||||
for (const [re, label] of RAW_PATTERNS) {
|
||||
if (re.test(note.text)) {
|
||||
if (isSystem || /source|источник/i.test(note.text.match(re)?.input || '')) soft.push(`raw-reference:${label}`)
|
||||
else flags.push(`raw:${label}`)
|
||||
}
|
||||
}
|
||||
|
||||
if (!isSystem && !isAtomizedSource && note.lines > 220) flags.push('long-note')
|
||||
if (!isSystem && !isAtomizedSource && note.headings >= 12) flags.push('many-headings')
|
||||
if (!isSystem && !isAtomizedSource && !isProcessedCanon && /подборка|каталог|топ[-\s]?\d+|серия|\bpack\b|\bstack\b|полная карта/i.test(note.title)) flags.push('collection-candidate')
|
||||
if (/^_COMMUNITY_|Community \d+/.test(note.basename)) {
|
||||
soft.push('graph-community-note')
|
||||
}
|
||||
|
||||
const alias = SECTION_ALIASES.get(note.section)
|
||||
if (alias) flags.push(`section-alias:${alias}`)
|
||||
if (!CANON_SECTIONS.includes(note.section) && !alias && !note.section.startsWith('08 AI и Инструменты/')) flags.push('noncanonical-section')
|
||||
|
||||
const inferred = inferSection(note)
|
||||
if (!isSystem && inferred !== note.section && alias !== inferred && !note.rel.startsWith(inferred + path.sep)) {
|
||||
flags.push(`route:${inferred}`)
|
||||
}
|
||||
|
||||
const score = Math.max(0, 100 - flags.filter(f => !f.startsWith('route:')).length * 12 - soft.length * 3)
|
||||
return { flags, soft, score, inferred }
|
||||
}
|
||||
|
||||
function mdTable(rows) {
|
||||
if (!rows.length) return '_Нет._\n'
|
||||
return [
|
||||
'| Файл | Score | Флаги | Предложение |',
|
||||
'|---|---:|---|---|',
|
||||
...rows.map(r => `| ${r.link} | ${r.score} | ${r.flags.join('<br>')} | ${r.suggestion} |`)
|
||||
].join('\n') + '\n'
|
||||
}
|
||||
|
||||
await fs.mkdir(OUT_DIR, { recursive: true })
|
||||
const allFiles = await walk(VAULT)
|
||||
const files = allFiles.filter(file => !shouldSkip(path.relative(VAULT, file)))
|
||||
|
||||
const notes = []
|
||||
for (const file of files) {
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
const rel = path.relative(VAULT, file)
|
||||
const fm = frontmatter(text)
|
||||
const note = {
|
||||
file,
|
||||
rel,
|
||||
basename: path.basename(file),
|
||||
text,
|
||||
fm,
|
||||
title: titleFrom(file, text, fm),
|
||||
section: topSection(rel),
|
||||
lines: text.split('\n').length,
|
||||
words: (text.match(/\S+/g) || []).length,
|
||||
headings: (text.match(/^##+\s+/gm) || []).length
|
||||
}
|
||||
Object.assign(note, canonFlags(note))
|
||||
note.link = `[[${note.rel.replace(/\.md$/, '')}]]`
|
||||
note.suggestion = note.flags.find(f => f.startsWith('route:'))?.replace('route:', 'перенести в ') ||
|
||||
note.flags.find(f => f.startsWith('section-alias:'))?.replace('section-alias:', 'слить в ') ||
|
||||
(note.flags.includes('long-note') || note.flags.includes('many-headings') || note.flags.includes('collection-candidate') ? 'атомизировать' : 'дописать канон')
|
||||
notes.push(note)
|
||||
}
|
||||
|
||||
const dirty = notes.filter(n => n.flags.length).sort((a, b) => a.score - b.score || b.lines - a.lines)
|
||||
const atomize = notes.filter(n => n.flags.some(f => ['long-note', 'many-headings', 'collection-candidate'].includes(f))).sort((a, b) => b.lines - a.lines)
|
||||
const routes = notes.filter(n => n.flags.some(f => f.startsWith('route:') || f.startsWith('section-alias:'))).sort((a, b) => a.rel.localeCompare(b.rel, 'ru'))
|
||||
const raw = notes.filter(n => n.flags.some(f => f.startsWith('raw:') || f.startsWith('raw-reference:'))).sort((a, b) => a.score - b.score)
|
||||
const bySection = new Map()
|
||||
for (const note of notes) bySection.set(note.section, (bySection.get(note.section) || 0) + 1)
|
||||
|
||||
const report = `# Mnemazine Live Vault Audit — ${today}
|
||||
|
||||
Vault: \`${VAULT}\`
|
||||
|
||||
## Сводка
|
||||
|
||||
- Markdown всего: ${allFiles.length}
|
||||
- Markdown в scoring: ${files.length}
|
||||
- Ноты с флагами: ${dirty.length}
|
||||
- Кандидаты на атомизацию: ${atomize.length}
|
||||
- Кандидаты на перенос/слияние разделов: ${routes.length}
|
||||
- Raw/reference маркеры: ${raw.length}
|
||||
|
||||
## Разделы
|
||||
|
||||
| Раздел | Нот |
|
||||
|---|---:|
|
||||
${[...bySection.entries()].sort((a, b) => a[0].localeCompare(b[0], 'ru')).map(([name, count]) => `| ${name} | ${count} |`).join('\n')}
|
||||
|
||||
## Первые правки: неканон
|
||||
|
||||
${mdTable(dirty.slice(0, LIMIT))}
|
||||
|
||||
## Атомизация
|
||||
|
||||
${mdTable(atomize.slice(0, LIMIT))}
|
||||
|
||||
## Роутинг
|
||||
|
||||
${mdTable(routes.slice(0, LIMIT))}
|
||||
|
||||
## Raw/reference
|
||||
|
||||
${mdTable(raw.slice(0, LIMIT))}
|
||||
|
||||
## Канон применения
|
||||
|
||||
1. Не удалять полезное знание. Сначала атомизировать или карантин.
|
||||
2. Raw OCR, screenshot filenames и длинные подборки не должны быть телом знания.
|
||||
3. Один атом = одна задача применения, один набор источников, одна категория.
|
||||
4. После правок обновить \`_Содержание.md\`, \`_МАСТЕР-ИНДЕКС.md\`, потом Graphify.
|
||||
`
|
||||
|
||||
const json = {
|
||||
generated_at: new Date().toISOString(),
|
||||
vault: VAULT,
|
||||
totals: {
|
||||
markdown_total: allFiles.length,
|
||||
markdown_scored: files.length,
|
||||
dirty: dirty.length,
|
||||
atomize: atomize.length,
|
||||
routes: routes.length,
|
||||
raw: raw.length
|
||||
},
|
||||
sections: Object.fromEntries([...bySection.entries()].sort((a, b) => a[0].localeCompare(b[0], 'ru'))),
|
||||
dirty: dirty.map(({ text, ...n }) => n),
|
||||
atomize: atomize.map(({ text, ...n }) => n),
|
||||
routes: routes.map(({ text, ...n }) => n),
|
||||
raw: raw.map(({ text, ...n }) => n)
|
||||
}
|
||||
|
||||
const base = path.join(OUT_DIR, `${today}-live-vault-audit`)
|
||||
await fs.writeFile(`${base}.md`, report)
|
||||
await fs.writeFile(`${base}.json`, JSON.stringify(json, null, 2))
|
||||
console.log(JSON.stringify({ ok: true, report: `${base}.md`, json: `${base}.json`, ...json.totals }, null, 2))
|
||||
@@ -9,16 +9,61 @@ while IFS= read -r -d '' file; do node --check "$file"; done < <(find scripts te
|
||||
|
||||
npm run selftest:security
|
||||
npm audit --audit-level=moderate
|
||||
npm run public-check
|
||||
if [ "${MNEMAZINE_AUDIT_SKIP_PUBLIC_RELEASE:-0}" = "1" ]; then
|
||||
echo "audit:local public-release scan skipped; run npm run public-check before public release"
|
||||
else
|
||||
npm run public-check
|
||||
fi
|
||||
|
||||
if rg -n --glob '!node_modules/**' --glob '!.git/**' --glob '!.mnemazine/**' --glob '!scripts/mnemazine-audit-local.sh' 'StrictHostKeyChecking=(no|accept-new)|root@[a-z0-9][A-Za-z0-9._-]*|(^|[^A-Za-z0-9_])--dangerously-skip-permissions([^A-Za-z0-9_]|$)|https?://[^/[:space:]'\''"]+@' .; then
|
||||
echo "audit:local failed: dangerous flag or credential URL pattern found." >&2
|
||||
# Pick a scanner. Prefer ripgrep; fall back to POSIX grep -E so the scan still
|
||||
# runs on machines without rg. A missing scanner must HARD-FAIL, never silently
|
||||
# pass — same rule as check-public-release.sh:18-26. Without this: `rg` absent
|
||||
# returns 127 inside the `if`, `set -euo pipefail` does NOT fire in that context,
|
||||
# the body is skipped, and the script printed "audit:local passed" WITHOUT scanning.
|
||||
if command -v rg >/dev/null 2>&1; then
|
||||
SCANNER=rg
|
||||
elif command -v grep >/dev/null 2>&1; then
|
||||
SCANNER=grep
|
||||
else
|
||||
echo "audit:local errored: neither 'rg' nor 'grep' is available to scan." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if rg -n "fetch\\([^\\n]*(169\\.254\\.169\\.254|metadata\\.google|metadata\\.azure)" scripts webapp; then
|
||||
DANGEROUS_PATTERN='StrictHostKeyChecking=(no|accept-new)|root@[a-z0-9][A-Za-z0-9._-]*|(^|[^A-Za-z0-9_])--dangerously-skip-permissions([^A-Za-z0-9_]|$)|https?://[^/[:space:]'\''"]+@'
|
||||
# `.*` (not `[^\n]*`): both scanners are line-based, so this matches identically,
|
||||
# and it avoids grep-ERE reading `[^\n]` as the class "not backslash or n".
|
||||
METADATA_PATTERN='fetch\(.*(169\.254\.169\.254|metadata\.google|metadata\.azure)'
|
||||
|
||||
scan_dangerous() {
|
||||
if [ "$SCANNER" = rg ]; then
|
||||
rg -n --glob '!node_modules/**' --glob '!.git/**' --glob '!.mnemazine/**' --glob '!scripts/mnemazine-audit-local.sh' "$DANGEROUS_PATTERN" .
|
||||
else
|
||||
grep -rEn --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=.mnemazine --exclude=mnemazine-audit-local.sh "$DANGEROUS_PATTERN" .
|
||||
fi
|
||||
}
|
||||
status=0; scan_dangerous || status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo "audit:local failed: dangerous flag or credential URL pattern found." >&2
|
||||
exit 1
|
||||
elif [ "$status" -ge 2 ]; then
|
||||
echo "audit:local errored: scanner '$SCANNER' failed (exit $status) on dangerous-pattern scan." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
scan_metadata() {
|
||||
if [ "$SCANNER" = rg ]; then
|
||||
rg -n "$METADATA_PATTERN" scripts webapp
|
||||
else
|
||||
grep -rEn "$METADATA_PATTERN" scripts webapp
|
||||
fi
|
||||
}
|
||||
status=0; scan_metadata || status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
echo "audit:local failed: metadata/private fetch pattern found." >&2
|
||||
exit 1
|
||||
elif [ "$status" -ge 2 ]; then
|
||||
echo "audit:local errored: scanner '$SCANNER' failed (exit $status) on metadata scan." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "audit:local passed"
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
#!/usr/bin/env node
|
||||
// Проверка, что проверки живы (план П11, приём 34 — молчание конвейера ≠ исправность).
|
||||
//
|
||||
// - реестр checks из mnemazine-release-check.mjs печатается и сверяется: каждая
|
||||
// зарегистрированная проверка ссылается на определённую функцию, и каждый новый скрипт
|
||||
// волны 2 (пять мета-приборов П11; model-pin — когда П09 закрыт) зарегистрирован;
|
||||
// - задания launchd com.mnemazine.*: последний код возврата из launchctl list; состояние в
|
||||
// .mnemazine/state/checks-inventory.json с first_red_at; красным становится задание,
|
||||
// висящее с ненулевым кодом дольше N дней (по умолчанию 1).
|
||||
// - стык с П01: он выгружает задания на время работ. При .mnemazine/state/rebuild/П01.done.json
|
||||
// без restored:true отсутствие задания — quarantined, не провал; после restored:true — провал.
|
||||
//
|
||||
// Коды: 0 — всё живо; 1 — мёртвая ссылка/незарегистрированный прибор/задание красное дольше N
|
||||
// дней/пропавшее задание вне карантина; 2 — ноль найденных проверок в реестре.
|
||||
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const RELEASE_CHECK = path.join(ROOT, 'scripts', 'mnemazine-release-check.mjs')
|
||||
const INVENTORY = path.join(ROOT, 'config', 'checks-inventory.json')
|
||||
const STATE = path.join(ROOT, '.mnemazine', 'state', 'checks-inventory.json')
|
||||
const TELEGRAM_BLOCKED = path.join(ROOT, '.mnemazine', 'state', 'telegram-blocked.json')
|
||||
const REBUILD = path.join(ROOT, '.mnemazine', 'state', 'rebuild')
|
||||
const REQUIRED_WAVE2 = ['rules-inventory', 'doc-contract-check', 'single-truth-check', 'lesson-gate', 'checks-inventory']
|
||||
const RED_DAYS = Number(process.env.MNEMAZINE_CHECK_RED_DAYS || 1)
|
||||
|
||||
// --- реестр release-check ---
|
||||
function evaluateRegistry(source, required) {
|
||||
const failures = []
|
||||
const block = source.match(/const checks\s*=\s*\[([\s\S]*?)\n\s*\]/)
|
||||
if (!block) return { code: 2, names: [], failures: ['реестр checks не найден в release-check'] }
|
||||
const names = []
|
||||
for (const m of block[1].matchAll(/\[\s*'([^']+)'\s*,\s*([A-Za-z0-9_]+)\s*\]/g)) {
|
||||
const [, name, fn] = m
|
||||
names.push(name)
|
||||
const defined = new RegExp(`(?:async\\s+)?function\\s+${fn}\\b|const\\s+${fn}\\s*=`).test(source)
|
||||
if (!defined) failures.push(`проверка '${name}' ссылается на неопределённую функцию ${fn}`)
|
||||
}
|
||||
if (names.length === 0) return { code: 2, names, failures: ['ноль найденных проверок в реестре'] }
|
||||
for (const r of required) if (!names.includes(r)) failures.push(`прибор волны 2 не зарегистрирован в release-check: ${r}`)
|
||||
return { code: failures.length ? 1 : 0, names, failures }
|
||||
}
|
||||
|
||||
// --- задания launchd ---
|
||||
// Признак машины владельца: маркер П01-перестройки. Он gitignored (в клон/форк/CI
|
||||
// не попадает по построению), поэтому его НАЛИЧИЕ детерминированно отличает живую
|
||||
// машину владельца от постороннего клона. Есть маркер → задания launchd обязаны быть
|
||||
// живы (dead-man's switch владельца, проверки строги). Нет → это форк/CI, где
|
||||
// launchd-конвейера Mnemazine нет по построению: owner-ops проверки не применимы —
|
||||
// skipped-as-not-applicable с явной строкой, НЕ красное и НЕ молчаливый пропуск (П22).
|
||||
function ownerMachine() {
|
||||
return existsSync(path.join(REBUILD, 'П01.done.json'))
|
||||
}
|
||||
|
||||
function quarantineActive() {
|
||||
const marker = path.join(REBUILD, 'П01.done.json')
|
||||
if (!existsSync(marker)) return false
|
||||
try { return JSON.parse(readFileSync(marker, 'utf8')).restored !== true } catch { return true }
|
||||
}
|
||||
|
||||
function expectedJobs() {
|
||||
if (existsSync(INVENTORY)) {
|
||||
try {
|
||||
const labels = JSON.parse(readFileSync(INVENTORY, 'utf8')).launchd_labels
|
||||
if (Array.isArray(labels) && labels.length) return labels
|
||||
} catch {}
|
||||
}
|
||||
const before = path.join(REBUILD, 'launchd-before.json')
|
||||
if (existsSync(before)) {
|
||||
try {
|
||||
const labels = JSON.parse(readFileSync(before, 'utf8')).labels
|
||||
if (Array.isArray(labels) && labels.length) return labels
|
||||
} catch {}
|
||||
}
|
||||
return ['com.mnemazine.kb-lint', 'com.mnemazine.kb-yt-watch', 'com.mnemazine.telegram-sync']
|
||||
}
|
||||
|
||||
function launchAgentsDir() {
|
||||
return path.join(process.env.HOME || '', 'Library', 'LaunchAgents')
|
||||
}
|
||||
|
||||
function plistPath(label) {
|
||||
return path.join(launchAgentsDir(), `${label}.plist`)
|
||||
}
|
||||
|
||||
function livePlistLabels() {
|
||||
const dir = launchAgentsDir()
|
||||
if (!dir || !existsSync(dir)) return []
|
||||
const r = spawnSync('find', [dir, '-maxdepth', '1', '-name', 'com.mnemazine.*.plist', '-print'], { encoding: 'utf8' })
|
||||
if (r.status !== 0) return []
|
||||
return r.stdout.split(/\r?\n/).filter(Boolean).map((p) => path.basename(p, '.plist'))
|
||||
}
|
||||
|
||||
function telegramFirstSeen() {
|
||||
if (!existsSync(TELEGRAM_BLOCKED)) return null
|
||||
try {
|
||||
const first = JSON.parse(readFileSync(TELEGRAM_BLOCKED, 'utf8')).first_seen
|
||||
return Number.isFinite(Date.parse(first)) ? first : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// label → last exit code (number) или null если не загружено
|
||||
function launchdExitCodes() {
|
||||
const map = new Map()
|
||||
if (process.platform !== 'darwin') return map
|
||||
const r = spawnSync('launchctl', ['list'], { encoding: 'utf8' })
|
||||
if (r.status !== 0) return map
|
||||
for (const line of r.stdout.split(/\r?\n/)) {
|
||||
const cols = line.split(/\t/)
|
||||
if (cols.length >= 3 && cols[2].startsWith('com.mnemazine.')) {
|
||||
const code = Number(cols[1])
|
||||
map.set(cols[2], Number.isFinite(code) ? code : null)
|
||||
}
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
function loadState() {
|
||||
if (!existsSync(STATE)) return { jobs: {} }
|
||||
try { return JSON.parse(readFileSync(STATE, 'utf8')) } catch { return { jobs: {} } }
|
||||
}
|
||||
|
||||
function saveState(state) {
|
||||
try { mkdirSync(path.dirname(STATE), { recursive: true }); writeFileSync(STATE, JSON.stringify(state, null, 2)) } catch {}
|
||||
}
|
||||
|
||||
function evaluateLaunchd(nowMs) {
|
||||
const failures = []
|
||||
const notes = []
|
||||
if (!ownerMachine()) {
|
||||
notes.push('owner-ops launchd: не применимо — нет .mnemazine/state/rebuild/П01.done.json (форк/CI, не машина владельца)')
|
||||
return { failures, notes }
|
||||
}
|
||||
if (process.platform !== 'darwin') { notes.push('не darwin: задания launchd не проверяются'); return { failures, notes } }
|
||||
const quarantined = quarantineActive()
|
||||
const loaded = launchdExitCodes()
|
||||
const state = loadState()
|
||||
const expected = expectedJobs()
|
||||
const expectedSet = new Set(expected)
|
||||
state.jobs = state.jobs || {}
|
||||
for (const label of livePlistLabels()) {
|
||||
if (!expectedSet.has(label)) failures.push(`${label}: plist есть в ~/Library/LaunchAgents, но метки нет в config/checks-inventory.json`)
|
||||
}
|
||||
for (const label of expected) {
|
||||
if (!loaded.has(label)) {
|
||||
if (quarantined) { notes.push(`${label}: отсутствует — quarantined (П01)`); delete state.jobs[label] }
|
||||
else if (existsSync(plistPath(label))) failures.push(`${label}: plist есть, но задание не загружено после restored:true`)
|
||||
else failures.push(`${label}: нет plist и нет задания после restored:true`)
|
||||
continue
|
||||
}
|
||||
const code = loaded.get(label)
|
||||
if (code === 0 || code == null) { delete state.jobs[label]; notes.push(`${label}: код ${code}`); continue }
|
||||
const rec = state.jobs[label] || { first_red_at: label === 'com.mnemazine.telegram-sync' ? (telegramFirstSeen() || new Date(nowMs).toISOString()) : new Date(nowMs).toISOString() }
|
||||
state.jobs[label] = rec
|
||||
const ageDays = (nowMs - Date.parse(rec.first_red_at)) / 86400000
|
||||
if (ageDays > RED_DAYS) failures.push(`${label}: код ${code} держится ${ageDays.toFixed(1)} дн (> ${RED_DAYS})`)
|
||||
else notes.push(`${label}: код ${code}, красное ${ageDays.toFixed(1)} дн (порог ${RED_DAYS}, пока grace)`)
|
||||
}
|
||||
saveState(state)
|
||||
return { failures, notes }
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
// Красный кролик: реестр без обязательного прибора обязан покраснеть.
|
||||
const fake = "const checks = [\n ['syntax', checkSyntax],\n]\nfunction checkSyntax(){}\n"
|
||||
const r = evaluateRegistry(fake, REQUIRED_WAVE2)
|
||||
if (r.code === 0) { console.error('selftest FAILED: реестр без мета-приборов прошёл зелёным'); return 1 }
|
||||
console.log('selftest ok: незарегистрированный прибор волны 2 краснит')
|
||||
return 0
|
||||
}
|
||||
|
||||
function main() {
|
||||
const argv = process.argv.slice(2)
|
||||
if (argv.includes('--selftest')) process.exit(selftest())
|
||||
if (!existsSync(RELEASE_CHECK)) { console.error('release-check не найден'); process.exit(2) }
|
||||
const reg = evaluateRegistry(readFileSync(RELEASE_CHECK, 'utf8'), REQUIRED_WAVE2)
|
||||
if (reg.code === 2) { console.error(reg.failures.join('\n')); process.exit(2) }
|
||||
const jobs = evaluateLaunchd(Date.now())
|
||||
|
||||
console.log(`реестр проверок: ${reg.names.length} (${reg.names.join(', ')})`)
|
||||
for (const n of jobs.notes) console.log(` ${n}`)
|
||||
const failures = [...reg.failures, ...jobs.failures]
|
||||
if (failures.length) {
|
||||
console.error('ПРОВАЛЫ:')
|
||||
for (const f of failures) console.error(` - ${f}`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log('все проверки живы')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,207 @@
|
||||
#!/usr/bin/env node
|
||||
// CLI availability probe with a CLOSED set of six outcomes. Ported concept from
|
||||
// Фемида's cli_probe.py (замысел, not code): the probe answers a fixed enum so
|
||||
// the caller decides by exit code alone (0 = ok), never by parsing prose.
|
||||
//
|
||||
// ok · no_binary · no_auth · no_quota · no_write · timeout ← ровно шесть
|
||||
//
|
||||
// Exit code is 0 ONLY on `ok`. Any other outcome exits 1 — the router does not
|
||||
// have to read JSON to decide whether to route here.
|
||||
//
|
||||
// Refusals are cached under an inter-process lock so a dead CLI is not re-probed
|
||||
// on every call. `no_quota` expires after 5h (quota heals itself; a permanent
|
||||
// ban would cut a live CLI forever); every other refusal after 15 minutes. A
|
||||
// revived CLI (probe now ok) is dropped from the cache immediately. The probe's
|
||||
// environment is scrubbed of ambient tokens so it tests the CLI's own stored
|
||||
// auth (keychain/config), not a transient env var.
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, writeFileSync, unlinkSync, readFileSync, openSync, closeSync, statSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
export const OUTCOMES = ['ok', 'no_binary', 'no_auth', 'no_quota', 'no_write', 'timeout']
|
||||
const QUOTA_RE = /quota|rate.?limit|too many requests|\b429\b|insufficient|billing|exceeded|out of (credit|token)/i
|
||||
const DEFAULT_TIMEOUT_SEC = 45
|
||||
const TTL_QUOTA_MS = 5 * 60 * 60 * 1000 // 5 hours
|
||||
const TTL_OTHER_MS = 15 * 60 * 1000 // 15 minutes
|
||||
|
||||
// Ambient secrets never leak into the probe: it must exercise the CLI's durable
|
||||
// auth, not whatever token happens to sit in this process's environment.
|
||||
function cleanEnv() {
|
||||
const out = {}
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (/^ANTHROPIC_/i.test(key) || /^OPENAI_/i.test(key)) continue
|
||||
if (/_TOKEN$/i.test(key) || /_API_KEY$/i.test(key)) continue
|
||||
out[key] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function ttlFor(outcome) {
|
||||
return outcome === 'no_quota' ? TTL_QUOTA_MS : TTL_OTHER_MS
|
||||
}
|
||||
|
||||
// --- cache under an inter-process lock ---------------------------------------
|
||||
function withCacheLock(cachePath, fn) {
|
||||
if (!cachePath) return fn(null) // no cache: run without lock, no persistence
|
||||
const lock = `${cachePath}.lock`
|
||||
const spin = new Int32Array(new SharedArrayBuffer(4))
|
||||
let held = false
|
||||
for (let attempt = 0; attempt < 100 && !held; attempt++) {
|
||||
try {
|
||||
closeSync(openSync(lock, 'wx'))
|
||||
held = true
|
||||
} catch (err) {
|
||||
if (err.code !== 'EEXIST') throw err
|
||||
// Steal a stale lock (crashed holder) after 10s.
|
||||
try { if (Date.now() - statSync(lock).mtimeMs > 10000) { unlinkSync(lock); continue } } catch {}
|
||||
Atomics.wait(spin, 0, 0, 50)
|
||||
}
|
||||
}
|
||||
try {
|
||||
return fn(readCache(cachePath))
|
||||
} finally {
|
||||
if (held) { try { unlinkSync(lock) } catch {} }
|
||||
}
|
||||
}
|
||||
|
||||
function readCache(cachePath) {
|
||||
try { return JSON.parse(readFileSync(cachePath, 'utf8')) } catch { return {} }
|
||||
}
|
||||
|
||||
function writeCache(cachePath, data) {
|
||||
writeFileSync(cachePath, `${JSON.stringify(data, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
// --- the probe itself --------------------------------------------------------
|
||||
// Runs the probe command and maps the result onto exactly one outcome. Never
|
||||
// throws for a normal failure — a failure is an outcome, not an exception.
|
||||
export function probeCli({ cli, probeCmd, workdir, timeoutSec, cachePath, now }) {
|
||||
const nowMs = Number.isFinite(now) ? now : Date.now()
|
||||
if (!Array.isArray(probeCmd) || !probeCmd.length || !probeCmd.every(s => typeof s === 'string' && s)) {
|
||||
throw new Error(`${cli}: probe-cmd must be a non-empty list of non-empty strings`)
|
||||
}
|
||||
|
||||
return withCacheLock(cachePath, cache => {
|
||||
// 1. A fresh cached refusal short-circuits — no spawn, no wasted CLI call.
|
||||
if (cache && cache[cli] && (nowMs - cache[cli].at) < ttlFor(cache[cli].outcome)) {
|
||||
return { cli, outcome: cache[cli].outcome, detail: cache[cli].detail || '', cached: true }
|
||||
}
|
||||
|
||||
const result = runProbe(cli, probeCmd, workdir, timeoutSec)
|
||||
|
||||
if (cache) {
|
||||
if (result.outcome === 'ok') delete cache[cli] // revived CLI leaves the cache at once
|
||||
else cache[cli] = { outcome: result.outcome, detail: result.detail, at: nowMs }
|
||||
writeCache(cachePath, cache)
|
||||
}
|
||||
return { ...result, cached: false }
|
||||
})
|
||||
}
|
||||
|
||||
function runProbe(cli, probeCmd, workdir, timeoutSec) {
|
||||
// 2. Workdir must be writable — a CLI that cannot write its working dir is
|
||||
// no_write, decided before we spend a spawn.
|
||||
const dir = workdir || os.tmpdir()
|
||||
const canary = path.join(dir, `.cli-probe-${process.pid}-${cli}`)
|
||||
try { writeFileSync(canary, 'x'); unlinkSync(canary) }
|
||||
catch { return { cli, outcome: 'no_write', detail: `workdir not writable: ${dir}` } }
|
||||
|
||||
// 3. Spawn with scrubbed env and a hard timeout.
|
||||
const timeoutMs = Math.max(1, Number(timeoutSec || DEFAULT_TIMEOUT_SEC)) * 1000
|
||||
const res = spawnSync(probeCmd[0], probeCmd.slice(1), {
|
||||
cwd: dir, env: cleanEnv(), encoding: 'utf8', timeout: timeoutMs
|
||||
})
|
||||
const out = `${res.stdout || ''}\n${res.stderr || ''}`.trim()
|
||||
const tail = out.slice(-300)
|
||||
|
||||
if (res.error?.code === 'ENOENT') return { cli, outcome: 'no_binary', detail: `binary not found: ${probeCmd[0]}` }
|
||||
if (res.error?.code === 'ETIMEDOUT' || res.signal === 'SIGTERM') return { cli, outcome: 'timeout', detail: `no answer within ${timeoutSec || DEFAULT_TIMEOUT_SEC}s` }
|
||||
if (res.error) return { cli, outcome: 'no_auth', detail: String(res.error.message).slice(-300) }
|
||||
if (QUOTA_RE.test(out)) return { cli, outcome: 'no_quota', detail: tail }
|
||||
if (res.status !== 0) return { cli, outcome: 'no_auth', detail: `exit ${res.status}: ${tail}` }
|
||||
return { cli, outcome: 'ok', detail: '' }
|
||||
}
|
||||
|
||||
// --- selftest ----------------------------------------------------------------
|
||||
function selftest() {
|
||||
const assert = (cond, msg) => { if (!cond) throw new Error(`selftest: ${msg}`) }
|
||||
const tmp = os.tmpdir()
|
||||
|
||||
assert(probeCli({ cli: 't', probeCmd: ['true'], workdir: tmp }).outcome === 'ok', 'true → ok')
|
||||
assert(probeCli({ cli: 'f', probeCmd: ['false'], workdir: tmp }).outcome === 'no_auth', 'false → no_auth')
|
||||
assert(probeCli({ cli: 'n', probeCmd: ['mnemazine-no-such-binary-9000'], workdir: tmp }).outcome === 'no_binary', 'missing → no_binary')
|
||||
assert(probeCli({ cli: 's', probeCmd: ['sh', '-c', 'sleep 3'], timeoutSec: 1, workdir: tmp }).outcome === 'timeout', 'sleep → timeout')
|
||||
assert(probeCli({ cli: 'q', probeCmd: ['sh', '-c', 'echo you exceeded your quota >&2; exit 1'], workdir: tmp }).outcome === 'no_quota', 'quota → no_quota')
|
||||
|
||||
// no_write: a read-only workdir.
|
||||
const ro = path.join(tmp, `cli-probe-ro-${process.pid}`)
|
||||
spawnSync('mkdir', ['-p', ro]); spawnSync('chmod', ['500', ro])
|
||||
assert(probeCli({ cli: 'w', probeCmd: ['true'], workdir: ro }).outcome === 'no_write', 'ro workdir → no_write')
|
||||
spawnSync('chmod', ['700', ro]); spawnSync('rm', ['-rf', ro])
|
||||
|
||||
// Cache: a refusal is remembered, then expires by --now, then a revived CLI is
|
||||
// dropped from the cache the moment it probes ok.
|
||||
const cache = path.join(tmp, `cli-probe-cache-${process.pid}.json`)
|
||||
try { unlinkSync(cache) } catch {}
|
||||
const t0 = 1_000_000_000_000
|
||||
assert(probeCli({ cli: 'z', probeCmd: ['false'], cachePath: cache, now: t0 }).outcome === 'no_auth', 'seed refusal')
|
||||
assert(probeCli({ cli: 'z', probeCmd: ['true'], cachePath: cache, now: t0 + 60_000 }).cached === true, 'fresh refusal cached (true probe not run)')
|
||||
const expired = probeCli({ cli: 'z', probeCmd: ['true'], cachePath: cache, now: t0 + TTL_OTHER_MS + 1 })
|
||||
assert(expired.cached === false && expired.outcome === 'ok', 'expired refusal re-probed → ok')
|
||||
assert(readCache(cache).z === undefined, 'revived CLI dropped from cache')
|
||||
// no_quota keeps its longer TTL.
|
||||
assert(probeCli({ cli: 'v', probeCmd: ['sh', '-c', 'echo rate limit >&2; exit 1'], cachePath: cache, now: t0 }).outcome === 'no_quota', 'seed quota')
|
||||
assert(probeCli({ cli: 'v', probeCmd: ['true'], cachePath: cache, now: t0 + TTL_OTHER_MS + 1 }).cached === true, 'quota still cached past 15min')
|
||||
try { unlinkSync(cache) } catch {}
|
||||
|
||||
console.log(JSON.stringify({ ok: true, selftest: 'cli-probe', outcomes: OUTCOMES }))
|
||||
return 0
|
||||
}
|
||||
|
||||
function main() {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
cli: { type: 'string' },
|
||||
'probe-cmd': { type: 'string' },
|
||||
workdir: { type: 'string' },
|
||||
timeout: { type: 'string' },
|
||||
cache: { type: 'string' },
|
||||
now: { type: 'string' },
|
||||
json: { type: 'boolean', default: false },
|
||||
selftest: { type: 'boolean', default: false }
|
||||
},
|
||||
allowPositionals: false
|
||||
})
|
||||
if (values.selftest) return selftest()
|
||||
if (!values.cli || !values['probe-cmd']) {
|
||||
console.error('usage: --cli <name> --probe-cmd <json-array> [--workdir d] [--timeout sec] [--cache f] [--now epochMs] [--json]')
|
||||
return 2
|
||||
}
|
||||
let probeCmd
|
||||
try { probeCmd = JSON.parse(values['probe-cmd']) } catch (e) { console.error(`--probe-cmd is not JSON: ${e.message}`); return 2 }
|
||||
|
||||
let answer
|
||||
try {
|
||||
answer = probeCli({
|
||||
cli: values.cli,
|
||||
probeCmd,
|
||||
workdir: values.workdir,
|
||||
timeoutSec: values.timeout ? Number(values.timeout) : undefined,
|
||||
cachePath: values.cache,
|
||||
now: values.now ? Number(values.now) : undefined
|
||||
})
|
||||
} catch (e) {
|
||||
console.error(String(e.message || e))
|
||||
return 2
|
||||
}
|
||||
if (values.json) console.log(JSON.stringify(answer))
|
||||
else console.log(`${answer.cli}: ${answer.outcome}${answer.detail ? ` — ${answer.detail}` : ''}${answer.cached ? ' (cached)' : ''}`)
|
||||
return answer.outcome === 'ok' ? 0 : 1
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exit(main())
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
#!/usr/bin/env node
|
||||
// Single point of CLI selection: registry (data) → overlay (narrows, never
|
||||
// widens) → data class → capability → cost tier → availability probe → chain.
|
||||
// Ported concept from Фемида's cli_router.py (замысел, not code). Adding a new
|
||||
// CLI is one JSON entry in the registry or overlay and zero code edits here —
|
||||
// the code branches on declared CAPABILITY, never on a CLI name.
|
||||
//
|
||||
// Exit codes: 0 executor chosen · 1 selection refused (broken entry, empty
|
||||
// registry, class without carrier, capability without carrier, none available)
|
||||
// · 2 registry physically not read. Every refusal names its cause — never
|
||||
// "выбрано 0" (the Фемида lesson: an empty selection is an error, not a success).
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { probeCli } from './mnemazine-cli-probe.mjs'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
export const DEFAULT_REGISTRY = path.join(HERE, '..', 'config', 'cli-registry.json')
|
||||
export const DEFAULT_OVERLAY = path.join(HERE, '..', 'config', 'cli-registry.local.json')
|
||||
export const DEFAULT_TAXONOMY = path.join(HERE, '..', 'config', 'data-classes.json')
|
||||
|
||||
// Mnemazine data classes (Фемида had one, `pd`). `pd` never leaves the device:
|
||||
// its chain is a local engine only. The class taxonomy of a NOTE lives in
|
||||
// config/data-classes.json (П24) — this list is only the router's admission axis.
|
||||
export const DATA_CLASSES = ['pd', 'personal', 'text', 'public', 'infra']
|
||||
export const COST_TIERS = ['cheap', 'standard', 'premium']
|
||||
const COST_RANK = { cheap: 0, standard: 1, premium: 2 }
|
||||
// Schema mechanisms are three adapters, chosen by capability, never by name.
|
||||
export const SCHEMA_ADAPTERS = ['json_schema_inline', 'json_schema_file', 'json_in_prompt']
|
||||
// A base CLI's harness (what makes it that tool) cannot be repinned by the overlay.
|
||||
const LOCKED_KEYS = ['probe', 'invoke', 'data_classes', 'capabilities', 'local']
|
||||
const OVERLAY_TWEAKABLE = ['model', 'effort', 'cost_tier']
|
||||
|
||||
const ASCII_NAME_RE = /^[a-z0-9._-]+$/
|
||||
// Cyrillic homoglyphs folded to Latin so "clаude" (Cyrillic а) is caught.
|
||||
const CONFUSABLES = {
|
||||
а: 'a', с: 'c', е: 'e', о: 'o', р: 'p', х: 'x', у: 'y', н: 'h',
|
||||
т: 't', м: 'm', в: 'b', к: 'k', з: '3', ч: '4', и: 'u'
|
||||
}
|
||||
|
||||
// A name folded to the harness canon: NFKD drops diacritics ("cláude"→claude),
|
||||
// spaces and zero-width (Cf) marks removed, homoglyphs mapped, case dropped.
|
||||
// Everything a base name can be faked with in a log, and not caught by eye.
|
||||
function fold(name) {
|
||||
const nfkd = name.normalize('NFKD')
|
||||
let out = ''
|
||||
for (const ch of nfkd) {
|
||||
if (/\s/.test(ch)) continue
|
||||
const cat = ch.charCodeAt(0)
|
||||
// Strip combining marks (already split by NFKD) and zero-width format chars.
|
||||
if (/\p{Mn}|\p{Cf}/u.test(ch)) continue
|
||||
out += CONFUSABLES[ch] || ch
|
||||
}
|
||||
return out.toLowerCase()
|
||||
}
|
||||
|
||||
function isDoubleOf(name, baseName) {
|
||||
return name !== baseName && fold(name) === fold(baseName)
|
||||
}
|
||||
|
||||
function validateEntry(name, entry) {
|
||||
if (!name || typeof name !== 'string' || !entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
throw taggedError(1, `${name}: запись реестра должна быть объектом`)
|
||||
}
|
||||
for (const key of ['probe', 'invoke', 'data_classes', 'capabilities']) {
|
||||
const value = entry[key]
|
||||
if (!Array.isArray(value) || !value.length || !value.every(v => typeof v === 'string' && v)) {
|
||||
throw taggedError(1, `${name}: ${key} должен быть непустым списком непустых строк`)
|
||||
}
|
||||
}
|
||||
for (const key of ['model', 'effort']) {
|
||||
if (typeof entry[key] !== 'string' || !entry[key]) throw taggedError(1, `${name}: ${key} должен быть непустой строкой`)
|
||||
}
|
||||
if (!COST_TIERS.includes(entry.cost_tier)) throw taggedError(1, `${name}: cost_tier должен быть одним из ${COST_TIERS.join('|')}`)
|
||||
if (typeof entry.local !== 'boolean') throw taggedError(1, `${name}: local должен быть булевым`)
|
||||
return entry
|
||||
}
|
||||
|
||||
function taggedError(exit, message) {
|
||||
const err = new Error(message)
|
||||
err.exit = exit
|
||||
return err
|
||||
}
|
||||
|
||||
// Overlay narrows, never widens (rule 5). It may add a NEW CLI and tweak
|
||||
// model/effort/cost_tier of an existing one. It may NOT: grant `pd` (cut by
|
||||
// force; if the cut empties the class list the load is REFUSED, exit 1 — not a
|
||||
// silent drop), repin a base CLI's invoke/probe/data_classes/capabilities/local,
|
||||
// or introduce a name outside ^[a-z0-9._-]+$ or a look-alike of a base name.
|
||||
export function mergeRegistry(base, overlay) {
|
||||
if (!base || typeof base !== 'object' || Array.isArray(base)) throw taggedError(2, 'реестр не прочитан: не объект')
|
||||
if (!overlay || typeof overlay !== 'object' || Array.isArray(overlay)) throw taggedError(1, 'оверлей не прочитан: не объект')
|
||||
const baseNames = Object.keys(base)
|
||||
const merged = {}
|
||||
for (const [name, entry] of Object.entries(base)) merged[name] = { ...entry }
|
||||
for (const [name, entry] of Object.entries(overlay)) {
|
||||
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) throw taggedError(1, `${name}: оверлей должен быть объектом`)
|
||||
if (baseNames.includes(name)) {
|
||||
// Existing CLI: only model/effort/cost_tier move; harness stays locked.
|
||||
for (const key of OVERLAY_TWEAKABLE) if (key in entry) merged[name][key] = entry[key]
|
||||
continue
|
||||
}
|
||||
// New CLI: force-cut pd, then structural gates.
|
||||
const next = { ...entry }
|
||||
if (Array.isArray(next.data_classes)) {
|
||||
next.data_classes = next.data_classes.filter(c => c !== 'pd')
|
||||
// pd cut; if nothing survives, REFUSE (§16.4) — a silent drop leaves the
|
||||
// router green on a CLI it never chained. Distinct from "неизвестный класс".
|
||||
if (!next.data_classes.length) throw taggedError(1, `${name}: запрещённый класс вырезан, запись пуста`)
|
||||
}
|
||||
merged[name] = next
|
||||
}
|
||||
// Drop names outside the ASCII class and look-alikes of any base name — such a
|
||||
// name is indistinguishable from the real one in a log, so it never enters.
|
||||
for (const name of Object.keys(merged)) {
|
||||
if (baseNames.includes(name)) continue
|
||||
if (!ASCII_NAME_RE.test(name)) { delete merged[name]; continue }
|
||||
if (baseNames.some(b => isDoubleOf(name, b))) { delete merged[name]; continue }
|
||||
}
|
||||
for (const [name, entry] of Object.entries(merged)) validateEntry(name, entry)
|
||||
return merged
|
||||
}
|
||||
|
||||
function readJsonFile(file, exitOnFail) {
|
||||
let raw
|
||||
try { raw = readFileSync(file, 'utf8') } catch (e) { throw taggedError(exitOnFail, `реестр физически не прочитан (${path.basename(file)}): ${e.code || e.message}`) }
|
||||
try { return JSON.parse(raw) } catch (e) { throw taggedError(exitOnFail, `реестр не разобран (${path.basename(file)}): ${e.message}`) }
|
||||
}
|
||||
|
||||
// Single truth for the class list (П24): the router's admission classes must be
|
||||
// exactly the taxonomy's classes in config/data-classes.json, or the two borders
|
||||
// drift within a month. A data_classes value absent there drops the load (exit 1).
|
||||
function loadTaxonomyClassSet(file = DEFAULT_TAXONOMY) {
|
||||
try { return new Set(Object.keys(JSON.parse(readFileSync(file, 'utf8')).classes)) }
|
||||
catch { return null } // taxonomy absent (pre-П24) → skip; router's own axis stays fail-closed
|
||||
}
|
||||
function validateTaxonomy(registry, classSet) {
|
||||
if (!classSet) return registry
|
||||
for (const [name, entry] of Object.entries(registry)) {
|
||||
for (const c of entry.data_classes) {
|
||||
if (!classSet.has(c)) throw taggedError(1, `${name}: неизвестный класс данных «${c}» (нет в config/data-classes.json)`)
|
||||
}
|
||||
}
|
||||
return registry
|
||||
}
|
||||
|
||||
export function loadRegistry({ registryPath = DEFAULT_REGISTRY, overlayPath = process.env.MNEMAZINE_CLI_REGISTRY_LOCAL || DEFAULT_OVERLAY } = {}) {
|
||||
const base = readJsonFile(registryPath, 2) // base missing/garbage → exit 2
|
||||
const explicitOverlay = Boolean(process.env.MNEMAZINE_CLI_REGISTRY_LOCAL)
|
||||
const overlay = overlayPath && existsSync(overlayPath)
|
||||
? readJsonFile(overlayPath, 1)
|
||||
: explicitOverlay
|
||||
? readJsonFile(overlayPath, 1)
|
||||
: {}
|
||||
return validateTaxonomy(mergeRegistry(base, overlay), loadTaxonomyClassSet())
|
||||
}
|
||||
|
||||
// Static ordering (no probe): class → capability → cost tier. Returns either a
|
||||
// non-empty ordered candidate list or a NAMED reason for the empty selection.
|
||||
export function orderCandidates(registry, { dataClass = 'text', capabilities = [], tier } = {}) {
|
||||
const names = Object.keys(registry)
|
||||
if (!names.length) return { candidates: [], reason: 'реестр пуст' }
|
||||
if (!DATA_CLASSES.includes(dataClass)) return { candidates: [], reason: `неизвестный класс данных: ${dataClass}` }
|
||||
|
||||
let pool
|
||||
if (dataClass === 'pd') {
|
||||
pool = names.filter(n => registry[n].local === true && registry[n].data_classes.includes('pd'))
|
||||
if (!pool.length) return { candidates: [], reason: 'класс pd: нет локальной CLI в реестре (pd не покидает устройство)' }
|
||||
} else {
|
||||
pool = names.filter(n => registry[n].data_classes.includes(dataClass))
|
||||
if (!pool.length) return { candidates: [], reason: `класс ${dataClass}: нет CLI в реестре` }
|
||||
}
|
||||
|
||||
if (capabilities.length) {
|
||||
for (const cap of capabilities) {
|
||||
if (!pool.some(n => registry[n].capabilities.includes(cap))) {
|
||||
return { candidates: [], reason: `нет носителя возможности ${cap}` }
|
||||
}
|
||||
}
|
||||
const withAll = pool.filter(n => capabilities.every(cap => registry[n].capabilities.includes(cap)))
|
||||
if (!withAll.length) return { candidates: [], reason: `нет CLI со всеми возможностями: ${capabilities.join(',')}` }
|
||||
pool = withAll
|
||||
}
|
||||
|
||||
if (tier) {
|
||||
if (!COST_TIERS.includes(tier)) return { candidates: [], reason: `неизвестный тир: ${tier}` }
|
||||
const capped = pool.filter(n => COST_RANK[registry[n].cost_tier] <= COST_RANK[tier])
|
||||
if (!capped.length) return { candidates: [], reason: `нет CLI тира <= ${tier}` }
|
||||
pool = capped
|
||||
}
|
||||
|
||||
// Ascending cost: cheap first, chain ends at the most expensive available CLI
|
||||
// of the class. On --tier the cheap one already leads. Stable by name.
|
||||
const ordered = pool
|
||||
.sort((a, b) => COST_RANK[registry[a].cost_tier] - COST_RANK[registry[b].cost_tier] || a.localeCompare(b))
|
||||
.map(n => ({ name: n, ...registry[n] }))
|
||||
return { candidates: ordered, reason: null }
|
||||
}
|
||||
|
||||
// Which schema adapter an entry uses — first declared mechanism wins.
|
||||
export function pickSchemaAdapter(entry) {
|
||||
return SCHEMA_ADAPTERS.find(cap => (entry.capabilities || []).includes(cap)) || null
|
||||
}
|
||||
|
||||
// Full decision with availability probing. `probeFn(name, entry) => boolean`.
|
||||
export function decide(registry, opts = {}, probeFn) {
|
||||
const { candidates, reason } = orderCandidates(registry, opts)
|
||||
if (reason) return { executor: null, chain: [], skipped: [], reason }
|
||||
const available = []
|
||||
const skipped = []
|
||||
for (const cand of candidates) {
|
||||
const ok = probeFn ? probeFn(cand.name, cand) : true
|
||||
if (ok === true) available.push(cand)
|
||||
else skipped.push({ name: cand.name, reason: typeof ok === 'string' ? ok : 'недоступна' })
|
||||
}
|
||||
if (!available.length) {
|
||||
const detail = skipped.map(s => `${s.name}:${s.reason}`).join(', ')
|
||||
return { executor: null, chain: [], skipped, reason: `ни одна CLI класса ${opts.dataClass || 'text'} не доступна (${detail})` }
|
||||
}
|
||||
return { executor: available[0], chain: available.map(c => c.name), skipped, reason: null }
|
||||
}
|
||||
|
||||
function realProbe(cachePath) {
|
||||
return (name, entry) => probeCli({ cli: name, probeCmd: entry.probe, cachePath }).outcome === 'ok'
|
||||
}
|
||||
|
||||
// --- selftest (pure: no disk, no network) ------------------------------------
|
||||
function selftest() {
|
||||
const assert = (cond, msg) => { if (!cond) throw new Error(`selftest: ${msg}`) }
|
||||
const okProbe = () => true
|
||||
const entry = (over = {}) => ({
|
||||
probe: ['true'], invoke: ['true'], model: 'm', effort: 'max',
|
||||
data_classes: ['text', 'public', 'infra'], capabilities: ['json_in_prompt'],
|
||||
cost_tier: 'standard', local: false, ...over
|
||||
})
|
||||
const BASE = {
|
||||
claude: entry({ data_classes: ['personal', 'text', 'public', 'infra'], capabilities: ['json_schema_inline', 'json_in_prompt', 'web_search', 'stdin_prompt', 'long_context'], cost_tier: 'premium' }),
|
||||
codex: entry({ capabilities: ['json_schema_file', 'json_in_prompt', 'web_search', 'stdin_prompt'], cost_tier: 'standard' }),
|
||||
kimi: entry({ capabilities: ['json_in_prompt', 'long_context'], cost_tier: 'cheap' })
|
||||
}
|
||||
|
||||
// merge + validation
|
||||
let reg = mergeRegistry(BASE, {})
|
||||
assert(Object.keys(reg).sort().join(',') === 'claude,codex,kimi', 'three base entries')
|
||||
assert(pickSchemaAdapter(reg.claude) === 'json_schema_inline', 'claude → inline')
|
||||
assert(pickSchemaAdapter(reg.codex) === 'json_schema_file', 'codex → file')
|
||||
assert(pickSchemaAdapter(reg.kimi) === 'json_in_prompt', 'kimi → in_prompt')
|
||||
|
||||
// broken entry names itself
|
||||
try { mergeRegistry({ bad: entry({ invoke: [] }) }, {}); assert(false, 'no invoke must throw') }
|
||||
catch (e) { assert(/bad/.test(e.message) && e.exit === 1, 'broken entry names bad, exit 1') }
|
||||
try { mergeRegistry({ x: entry({ data_classes: [] }) }, {}); assert(false, 'empty classes must throw') }
|
||||
catch (e) { assert(/x/.test(e.message) && e.exit === 1, 'empty data_classes exit 1') }
|
||||
|
||||
// empty registry → named reason, never "выбрано 0"
|
||||
assert(orderCandidates({}, { dataClass: 'text' }).reason === 'реестр пуст', 'empty → реестр пуст')
|
||||
|
||||
// overlay grants pd-only → cut empties list → REFUSED, not a silent drop (§16.4)
|
||||
try { mergeRegistry(BASE, { zloy: entry({ data_classes: ['pd'] }) }); assert(false, 'pd-only overlay must throw') }
|
||||
catch (e) { assert(/zloy/.test(e.message) && e.exit === 1 && /запись пуста/.test(e.message), 'pd-only overlay refused exit 1') }
|
||||
// overlay hijacks base invoke → refused (base invoke preserved)
|
||||
reg = mergeRegistry(BASE, { claude: { invoke: ['/tmp/evil'], effort: 'low' } })
|
||||
assert(JSON.stringify(reg.claude.invoke) === JSON.stringify(BASE.claude.invoke), 'base invoke locked')
|
||||
assert(reg.claude.effort === 'low', 'overlay may tweak effort')
|
||||
// look-alikes and non-ASCII dropped, real harness kept
|
||||
reg = mergeRegistry(BASE, {
|
||||
Claude: entry({ capabilities: ['json_in_prompt'] }),
|
||||
'clаude': entry({ capabilities: ['json_in_prompt'] }),
|
||||
'claude ': entry({ capabilities: ['json_in_prompt'] }),
|
||||
'clαude': entry({ capabilities: ['json_in_prompt'] })
|
||||
})
|
||||
assert(!('Claude' in reg) && !('clаude' in reg) && !('claude ' in reg) && !('clαude' in reg), 'doubles dropped')
|
||||
assert('claude' in reg, 'real harness kept')
|
||||
assert(!isDoubleOf('claude-fast', 'claude') && !isDoubleOf('claude-code', 'claude'), 'legit suffixes not doubles')
|
||||
|
||||
// capability with no carrier → named refusal (replaces the old per-provider literal)
|
||||
const kimiOnly = { kimi: BASE.kimi }
|
||||
assert(orderCandidates(kimiOnly, { dataClass: 'text', capabilities: ['web_search'] }).reason === 'нет носителя возможности web_search', 'web_search no carrier')
|
||||
// pd on base registry → no local carrier
|
||||
assert(/pd/.test(orderCandidates(BASE, { dataClass: 'pd' }).reason), 'pd fail-closed named')
|
||||
|
||||
// cost ordering: cheap first
|
||||
const order = orderCandidates(mergeRegistry(BASE, {}), { dataClass: 'text' }).candidates.map(c => c.name)
|
||||
assert(order.join(',') === 'kimi,codex,claude', `cheap-first order, got ${order}`)
|
||||
|
||||
// decide skips an unavailable CLI, chain not empty, reason named on total miss
|
||||
const chainReg = {
|
||||
fake: entry({ cost_tier: 'cheap' }),
|
||||
good: entry({ cost_tier: 'standard' })
|
||||
}
|
||||
const decision = decide(mergeRegistry(chainReg, {}), { dataClass: 'text' }, name => name !== 'fake')
|
||||
assert(decision.executor?.name === 'good', 'fake skipped, good chosen')
|
||||
const dead = decide(mergeRegistry(chainReg, {}), { dataClass: 'text' }, () => false)
|
||||
assert(dead.executor === null && /не доступна/.test(dead.reason), 'all dead → named refusal')
|
||||
|
||||
// П24: if an overlay is provided via env, additionally validate the LIVE
|
||||
// registry+overlay against the taxonomy on disk. A poisoned class (e.g. an
|
||||
// overlay declaring data_classes:["secret"]) drops the load with exit 1 —
|
||||
// this is where the two borders are welded shut.
|
||||
if (process.env.MNEMAZINE_CLI_REGISTRY_LOCAL) {
|
||||
loadRegistry({ overlayPath: process.env.MNEMAZINE_CLI_REGISTRY_LOCAL })
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ ok: true, selftest: 'cli-router' }))
|
||||
return 0
|
||||
}
|
||||
|
||||
function main() {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
class: { type: 'string' },
|
||||
capability: { type: 'string' },
|
||||
tier: { type: 'string' },
|
||||
registry: { type: 'string' },
|
||||
overlay: { type: 'string' },
|
||||
cache: { type: 'string' },
|
||||
json: { type: 'boolean', default: false },
|
||||
selftest: { type: 'boolean', default: false }
|
||||
},
|
||||
allowPositionals: false
|
||||
})
|
||||
if (values.selftest) {
|
||||
try { return selftest() }
|
||||
catch (e) { console.error(`ОТКАЗ: ${e.message}`); return e.exit || 1 }
|
||||
}
|
||||
|
||||
let registry
|
||||
try {
|
||||
registry = loadRegistry({
|
||||
registryPath: values.registry || DEFAULT_REGISTRY,
|
||||
overlayPath: values.overlay || DEFAULT_OVERLAY
|
||||
})
|
||||
} catch (e) {
|
||||
console.error(`ОТКАЗ: ${e.message}`)
|
||||
return e.exit || 1
|
||||
}
|
||||
|
||||
const opts = {
|
||||
dataClass: values.class || 'text',
|
||||
capabilities: values.capability ? values.capability.split(',').map(s => s.trim()).filter(Boolean) : [],
|
||||
tier: values.tier
|
||||
}
|
||||
const decision = decide(registry, opts, realProbe(values.cache))
|
||||
if (values.json) console.log(JSON.stringify(decision))
|
||||
else if (decision.executor) console.log(`${opts.dataClass} → ${decision.executor.name} [chain: ${decision.chain.join(' → ')}]`)
|
||||
else console.error(`ОТКАЗ: ${decision.reason}`)
|
||||
return decision.executor ? 0 : 1
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exit(main())
|
||||
}
|
||||
@@ -1,13 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
// Back-compat shim. The engine is now provider-abstracted in mnemazine-llm.mjs
|
||||
// (Claude primary, Codex parity). This file keeps the old codex-named exports
|
||||
// working; it always targets the codex provider.
|
||||
// Back-compat shim. The engine is provider-abstracted in mnemazine-llm.mjs and
|
||||
// the CLIs live as DATA in config/cli-registry.json. These codex-named exports
|
||||
// stay for old importers, but they no longer pin a provider — the registry
|
||||
// default and its fallback chain decide. No provider literal, no branch here.
|
||||
import { llmJson, llmAvailable, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
|
||||
export { fenceUntrusted }
|
||||
export function codexAvailable() {
|
||||
return llmAvailable('codex')
|
||||
}
|
||||
export { fenceUntrusted, llmAvailable as codexAvailable }
|
||||
export async function codexJson(prompt, schema, opts = {}) {
|
||||
return llmJson(prompt, schema, { ...opts, provider: 'codex' })
|
||||
return llmJson(prompt, schema, opts)
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { spawn, spawnSync } from 'node:child_process'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
@@ -20,6 +20,26 @@ function arg(name, fallback = '') {
|
||||
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 REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
|
||||
// Удаление протухшего маркера графа — только по этому явному флагу.
|
||||
// Без него маркер остаётся на месте и ложится в warnings/failures (план П08).
|
||||
const PRUNE_GRAPH_MARKER = argv.includes('--prune-graph-marker')
|
||||
|
||||
if (argv.includes('--help')) {
|
||||
console.log(`mnemazine-complete-check.mjs — сводный гейт «конвейер завершён честно»:
|
||||
инбокс пуст, coverage/качество/отчёт/человеческий слой зелёные, маркер графа учтён.
|
||||
|
||||
Использование: node scripts/mnemazine-complete-check.mjs [флаги]
|
||||
--vault <путь> корпус (иначе MNEMAZINE_VAULT, last-run.vault или repo-local vault)
|
||||
--require-deep требовать deep-прогон в last-run (или MNEMAZINE_REQUIRE_DEEP=1)
|
||||
--strict-graph маркер needs_update — failure, а не warning
|
||||
--needs-update-max-days N возраст маркера до failure (по умолчанию 1)
|
||||
--prune-graph-marker удалить протухший маркер graphify-out/needs_update
|
||||
(по умолчанию НИЧЕГО не удаляется — только verdict)
|
||||
--help эта справка
|
||||
|
||||
Коды возврата: 0 — все проверки зелёные; 1 — есть failures или ошибка.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
function run(command, args, env = {}) {
|
||||
return new Promise(resolve => {
|
||||
@@ -61,10 +81,21 @@ async function latestReport() {
|
||||
return (visual.length ? visual : reports).sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.file || ''
|
||||
}
|
||||
|
||||
// fail-closed: нечитаемый инбокс (EACCES и пр.) не должен быть неотличим от
|
||||
// пустого. ENOENT — легитимно «нет папки = пусто»; любая другая ошибка readdir —
|
||||
// это провал «inbox unreadable», а не «инбокс пуст».
|
||||
async function activeInboxFiles() {
|
||||
return (await fs.readdir(INBOX, { withFileTypes: true }).catch(() => []))
|
||||
.filter(item => item.isFile() && !item.name.startsWith('.'))
|
||||
.map(item => item.name)
|
||||
let entries
|
||||
try {
|
||||
entries = await fs.readdir(INBOX, { withFileTypes: true })
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOENT') return { files: [], error: null }
|
||||
return { files: [], error: err.code || String(err.message) }
|
||||
}
|
||||
return {
|
||||
files: entries.filter(item => item.isFile() && !item.name.startsWith('.')).map(item => item.name),
|
||||
error: null
|
||||
}
|
||||
}
|
||||
|
||||
async function readJson(file, fallback = null) {
|
||||
@@ -85,6 +116,7 @@ function deepFailures(lastRun) {
|
||||
const failures = []
|
||||
if (!lastRun) return ['last run state missing']
|
||||
if (!lastRun.ok) failures.push(`last run failed: ${(lastRun.failures || [lastRun.failure || 'unknown']).join('; ')}`)
|
||||
if (lastRun.draft_only) failures.push('last run was draft-only')
|
||||
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.synthesize || lastRun.synthesize.skipped) {
|
||||
@@ -100,19 +132,41 @@ function deepFailures(lastRun) {
|
||||
async function main() {
|
||||
const failures = []
|
||||
const warnings = []
|
||||
const inboxFiles = await activeInboxFiles()
|
||||
const inbox = await activeInboxFiles()
|
||||
if (inbox.error) failures.push(`inbox unreadable: ${inbox.error}`)
|
||||
const inboxFiles = inbox.files
|
||||
if (inboxFiles.length) failures.push(`inbox not empty: ${inboxFiles.length}`)
|
||||
|
||||
const lastRunFile = path.join(STATE, 'last-run.json')
|
||||
const lastRun = await readJson(lastRunFile)
|
||||
const VAULT = resolveVault({ cli: arg('vault'), env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
|
||||
const gateEnv = { MNEMAZINE_VAULT: VAULT }
|
||||
const coverageArgs = ['scripts/mnemazine-coverage-check.mjs', '--vault', VAULT, '--inbox', INBOX, '--json']
|
||||
if (inboxFiles.length === 0) coverageArgs.push('--allow-empty')
|
||||
const coverage = spawnSync(process.execPath, coverageArgs, { cwd: ROOT, env: { ...process.env, ...gateEnv }, encoding: 'utf8' })
|
||||
const coverageCode = coverage.status ?? 1
|
||||
if (coverageCode === 1) failures.push(`coverage failed: ${(coverage.stderr || coverage.stdout || '').trim()}`)
|
||||
else if (coverageCode !== 0) failures.push(`coverage check error: ${(coverage.stderr || coverage.stdout || coverage.error?.message || '').trim()}`)
|
||||
const lastRunStartedMs = lastRun?.started_at ? Date.parse(lastRun.started_at) : 0
|
||||
const qualityArgs = ['scripts/mnemazine-vault-quality-gate.mjs', '--vault', VAULT, '--max-failures', '50']
|
||||
if (lastRunStartedMs) qualityArgs.push('--changed-since', lastRun.started_at)
|
||||
if (Number(lastRun?.processed || 0) === 0) qualityArgs.push('--allow-empty')
|
||||
const quality = await run(process.execPath, qualityArgs, gateEnv)
|
||||
if (!quality.ok) failures.push(`vault quality failed: ${quality.stderr || quality.stdout}`)
|
||||
|
||||
// Потолок провалов спеки в продовом пути (план П06 шаг 6): гейт --spec виден
|
||||
// приёмке, а не только вручную. Ненулевой код прибора потолка → в failures.
|
||||
const specCeilingFile = path.join(STATE, 'spec-ceiling.json')
|
||||
if (!existsSync(specCeilingFile)) {
|
||||
// Свежая установка: потолок спеки — per-machine runtime (план П16, .mnemazine/state
|
||||
// gitignored), на чистом клоне его нет и сравнивать не с чем. Это «нет данных», а не
|
||||
// провал: ratchet без базы — no-op. doctor распознаёт эту строку как no-data (degraded, не fatal).
|
||||
failures.push('spec ceiling has no baseline yet')
|
||||
} else {
|
||||
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}`)
|
||||
}
|
||||
|
||||
const report = await latestReport()
|
||||
if (!report) failures.push('weekly report missing')
|
||||
else {
|
||||
@@ -136,15 +190,24 @@ async function main() {
|
||||
|
||||
const needsUpdate = path.join(VAULT, 'graphify-out', 'needs_update')
|
||||
if (existsSync(needsUpdate)) {
|
||||
const markerText = await fs.readFile(needsUpdate, 'utf8').catch(() => '')
|
||||
const deferredSemantic = /deferred:/i.test(markerText)
|
||||
const graphPath = path.join(VAULT, 'graphify-out', 'graph.json')
|
||||
const graphMs = await graphMtime(graphPath)
|
||||
const newestSemantic = await newestChangedFileMtime(VAULT, 0, isGraphSemanticFile)
|
||||
const staleMarker = graphMs && newestSemantic && graphMs >= newestSemantic
|
||||
if (staleMarker) {
|
||||
await fs.rm(needsUpdate, { force: true }).catch(() => {})
|
||||
if (staleMarker && !deferredSemantic) {
|
||||
if (PRUNE_GRAPH_MARKER) {
|
||||
await fs.rm(needsUpdate, { force: true }).catch(() => {})
|
||||
} else {
|
||||
const ageDays = (Date.now() - (await fs.stat(needsUpdate)).mtimeMs) / 86400000
|
||||
const msg = `semantic graph marker stale (${ageDays.toFixed(2)} days; graph.json covers the newest semantic file — marker kept, prune explicitly with --prune-graph-marker)`
|
||||
if (STRICT_GRAPH || ageDays > NEEDS_UPDATE_MAX_DAYS) failures.push(msg)
|
||||
else warnings.push(msg)
|
||||
}
|
||||
} else {
|
||||
const ageDays = (Date.now() - (await fs.stat(needsUpdate)).mtimeMs) / 86400000
|
||||
const msg = `semantic graph pending (${ageDays.toFixed(2)} days)`
|
||||
const msg = `semantic graph pending (${ageDays.toFixed(2)} days; run npm run graph:semantic:async)`
|
||||
if (STRICT_GRAPH || ageDays > NEEDS_UPDATE_MAX_DAYS) failures.push(msg)
|
||||
else warnings.push(msg)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env node
|
||||
// ВОРОТА ПОЛНОТЫ — кодом, а не суждением агента.
|
||||
//
|
||||
// Зачем: 2026-07-25 прогон kb-20260725201732 закрылся маркером «ПОКРЫТИЕ ПОЛНОЕ ✓», ledger
|
||||
// unaccounted=0, archived=73 — при том что на диске файл `tmpImage_8B654E2A-…JPG` не имел НИ ноты,
|
||||
// НИ OCR-сайдкара, НИ записи причины (а Apple Vision читает его: 1193 символа про OmniRoute), и 72 из 73
|
||||
// файлов остались в инбоксе неархивированными. Сверщик — LLM, которая сама грепает и сама выносит
|
||||
// вердикт; в том же прогоне она ещё и чинила собственный баг грепа по ходу проверки. Это generator≈verifier
|
||||
// на самом важном гейте системы.
|
||||
//
|
||||
// Подсчёт покрытия — не суждение, а греп. Значит его место в коде с кодом возврата. LLM остаётся то,
|
||||
// что действительно требует головы: КАКАЯ причина у дыры (дубль/шум/нечитаемо) — но только после того,
|
||||
// как список дыр посчитан детерминированно.
|
||||
//
|
||||
// Контракт: exit 0 = каждый файл НЕПУСТОЙ переписи покрыт; exit 1 = есть дыры (список в JSON);
|
||||
// exit 2 = ошибка ввода ИЛИ пустая перепись без --allow-empty. Пустая перепись — не «сдано 0/0 ✓»:
|
||||
// ворота полноты, написанные после инцидента 25.07, обязаны краснеть на нулевом входе, иначе
|
||||
// возвращают ровно тот зелёный, что мастер-план §8 запрещает прибору оркестрации.
|
||||
// Покрытым считается файл, чей basename встречается в теле или frontmatter хотя бы одной ноты vault —
|
||||
// та же семантика, что у сверщика (`source:`/`sources:`), но без права ошибиться в регулярке.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const arg = (name, fallback = '') => {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
/** Ноты vault одним чтением: корпус мал (< 20 МБ), а N грепов по файлу — это N спавнов и гонка. */
|
||||
async function readCorpus(vault) {
|
||||
const chunks = []
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
const p = path.join(dir, item.name)
|
||||
if (item.isDirectory()) await walk(p)
|
||||
else if (item.isFile() && p.endsWith('.md')) chunks.push(await fs.readFile(p, 'utf8'))
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
return chunks.join('\n')
|
||||
}
|
||||
|
||||
/**
|
||||
* Файл покрыт, если его basename дословно встречается в корпусе.
|
||||
* NFC-нормализация обязательна: macOS отдаёт имена файлов в NFD («й» = «и»+U+0306), а нота пишется из
|
||||
* контекста агента в NFC — без выравнивания кириллическое имя даёт ложную дыру на каждом прогоне.
|
||||
*/
|
||||
export function isCovered(corpusNfc, filePath) {
|
||||
return corpusNfc.includes(path.basename(filePath).normalize('NFC'))
|
||||
}
|
||||
|
||||
if (argv.includes('--selftest')) {
|
||||
const { strictEqual: eq } = await import('node:assert')
|
||||
// «й» и «ё» — единственные кириллические буквы, которые NFD реально расщепляет (и + U+0306). Имя без
|
||||
// них делает NFD-проверку пустой: первая версия этого теста брала «Заметка Кирилла», где NFD == NFC,
|
||||
// и мутация «убрать normalize» проходила незамеченной. Тест обязан содержать расщепляемую букву.
|
||||
const nfdName = 'Андрей — ёлка.md'
|
||||
const corpus = ['source: IMG_1.PNG', 'sources:', ' - ' + nfdName].join('\n').normalize('NFC')
|
||||
eq(nfdName.normalize('NFD') !== nfdName.normalize('NFC'), true) // страховка: имя действительно расщепляется
|
||||
eq(isCovered(corpus, '/inbox/IMG_1.PNG'), true)
|
||||
eq(isCovered(corpus, '/inbox/IMG_2.PNG'), false) // отсутствующий файл обязан считаться дырой
|
||||
// NFD-имя с диска против NFC-корпуса: без нормализации это ложная дыра.
|
||||
eq(isCovered(corpus, '/inbox/' + nfdName.normalize('NFD')), true)
|
||||
eq(isCovered('', '/inbox/IMG_1.PNG'), false) // пустой корпус не покрывает ничего
|
||||
console.log('selftest ok')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
// Перепись: либо --census <json-файл со списком путей>, либо все файлы инбокса верхнего уровня.
|
||||
const censusFile = arg('census')
|
||||
let census
|
||||
if (censusFile) {
|
||||
const raw = JSON.parse(await fs.readFile(censusFile, 'utf8'))
|
||||
census = Array.isArray(raw) ? raw : (raw.files || raw.paths || [])
|
||||
if (!Array.isArray(census)) { console.error('census: ожидался массив путей'); process.exit(2) }
|
||||
} else {
|
||||
const inbox = arg('inbox', path.join(process.env.HOME || '', 'Desktop', 'Mnemazine Inbox'))
|
||||
const items = await fs.readdir(inbox, { withFileTypes: true }).catch(() => null)
|
||||
if (!items) { console.error(`инбокс не найден: ${inbox}`); process.exit(2) }
|
||||
// Только обычные файлы верхнего уровня: _archive/_work/.ocr/.staging — служебные каталоги прогона,
|
||||
// они не материал и не обязаны иметь ноту.
|
||||
census = items.filter(i => i.isFile() && !i.name.startsWith('.')).map(i => path.join(inbox, i.name))
|
||||
}
|
||||
|
||||
if (census.length === 0 && !argv.includes('--allow-empty')) {
|
||||
console.error('перепись пуста: 0 файлов на проверку покрытия (--allow-empty чтобы разрешить)')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const corpus = (await readCorpus(VAULT)).normalize('NFC')
|
||||
const uncovered = census.filter(f => !isCovered(corpus, f))
|
||||
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))
|
||||
else {
|
||||
console.log(`перепись ${report.census} · покрыто ${report.covered} · дыр ${uncovered.length}`)
|
||||
for (const f of uncovered) console.log(` ДЫРА ${path.basename(f)}`)
|
||||
}
|
||||
process.exit(uncovered.length ? 1 : 0)
|
||||
@@ -0,0 +1,231 @@
|
||||
#!/usr/bin/env node
|
||||
// Кампания по СУЩЕСТВУЮЩИМ дублям vault — режим только-отчёт.
|
||||
// Гонит kb-embed query (заголовок + первые строки ноты) против общего индекса,
|
||||
// собирает кластеры зон merge/flag, пишет отчёт в «99 Система/_lint/».
|
||||
// НИЧЕГО не мержит: мерж-вердикт — суждение, его исполняет Кими-рой по отчёту.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const SECTIONS = arg('sections', '01,07,08').split(',').map(s => s.trim()).filter(Boolean)
|
||||
const INDEX = arg('index', path.join(VAULT, '99 Система', '_embeddings.json'))
|
||||
const OUT = arg('out', path.join(VAULT, '99 Система', '_lint', `dedup-report-${new Date().toISOString().slice(0, 10)}.md`))
|
||||
const TOPK = Number(arg('topk', '8'))
|
||||
const JOBS = Number(arg('jobs', '4'))
|
||||
const LIMIT = Number(arg('limit', '0')) // 0 = все ноты; >0 — смоук-прогон
|
||||
const PYTHON = arg('python', path.join(os.homedir(), '.venvs', 'kb-embed', 'bin', 'python'))
|
||||
const KB_EMBED = arg('kb-embed', path.join(os.homedir(), '.claude', 'skills', 'mnemazina', 'kb-embed.py'))
|
||||
const QUERY_BODY_CHARS = 1200 // «первые строки»: меньше — самосовпадение ноты падает ниже merge-зоны
|
||||
// Взаимность: ребро идёт в кластеризацию, только если оба конца входят в топ-M партнёров друг друга.
|
||||
// Без этого flag-транзитивность через хабы-подборки сшила 603 из 917 нот раздела 08 в один кластер
|
||||
// (замер 2026-07-25). M=4: Camofox ×4 в одном кластере, макс кластер 249; M=3 рвёт Camofox на 3+1.
|
||||
const MUTUAL_TOP = Number(arg('mutual-top', '4'))
|
||||
|
||||
const nfc = s => s.normalize('NFC')
|
||||
|
||||
function stripFrontmatter(text) {
|
||||
if (!text.startsWith('---')) return text.trim()
|
||||
const end = text.indexOf('\n---', 3)
|
||||
return end === -1 ? text.trim() : text.slice(end + 4).trim()
|
||||
}
|
||||
|
||||
function noteTitle(p) {
|
||||
return path.basename(p, '.md').replace(/^\d{4}-\d{2}-\d{2}\s*[—–-]\s*/u, '')
|
||||
}
|
||||
|
||||
async function sectionDirs() {
|
||||
const entries = await fs.readdir(VAULT, { withFileTypes: true })
|
||||
const dirs = entries.filter(e => e.isDirectory()).map(e => e.name)
|
||||
const picked = new Set()
|
||||
for (const want of SECTIONS) {
|
||||
for (const dir of dirs) {
|
||||
const exact = nfc(dir) === nfc(want)
|
||||
const prefix = /^\d\d$/.test(want) && dir.startsWith(`${want} `)
|
||||
if (exact || prefix) picked.add(dir)
|
||||
}
|
||||
}
|
||||
if (!picked.size) throw new Error(`Ни один раздел не совпал с --sections "${SECTIONS.join(',')}" в ${VAULT}`)
|
||||
return [...picked].map(d => path.join(VAULT, d))
|
||||
}
|
||||
|
||||
async function collectNotes(dirs) {
|
||||
const notes = []
|
||||
async function walk(folder) {
|
||||
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
|
||||
if (item.name.startsWith('_') || item.name.startsWith('.')) continue
|
||||
const file = path.join(folder, item.name)
|
||||
if (item.isDirectory()) await walk(file)
|
||||
else if (item.isFile() && item.name.endsWith('.md')) notes.push(file)
|
||||
}
|
||||
}
|
||||
for (const dir of dirs) await walk(dir)
|
||||
notes.sort()
|
||||
return LIMIT > 0 ? notes.slice(0, LIMIT) : notes
|
||||
}
|
||||
|
||||
function runQuery(text) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(PYTHON, [KB_EMBED, 'query', INDEX, text, String(TOPK)], { stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
child.stdout.on('data', c => { stdout += String(c) })
|
||||
child.stderr.on('data', c => { stderr += String(c) })
|
||||
child.on('close', code => resolve({ code: code ?? 1, stdout: stdout.trim(), stderr: stderr.trim() }))
|
||||
child.on('error', error => resolve({ code: 1, stdout, stderr: error.message }))
|
||||
})
|
||||
}
|
||||
|
||||
async function noteMeta(p) {
|
||||
const raw = await fs.readFile(p, 'utf8').catch(() => null)
|
||||
if (raw === null) return { exists: false, date: '', chars: 0, body: '' }
|
||||
const body = stripFrontmatter(raw)
|
||||
const date = (raw.match(/^updated:\s*(\S+)/m)?.[1]
|
||||
|| raw.match(/^created:\s*(\S+)/m)?.[1]
|
||||
|| path.basename(p).match(/^(\d{4}-\d{2}-\d{2})/)?.[1]
|
||||
|| new Date((await fs.stat(p)).mtimeMs).toISOString().slice(0, 10)).replace(/["']/g, '')
|
||||
return { exists: true, date, chars: body.length, body }
|
||||
}
|
||||
|
||||
// union-find: кластер = связная компонента по рёбрам merge/flag
|
||||
const parent = new Map()
|
||||
function find(x) {
|
||||
if (!parent.has(x)) parent.set(x, x)
|
||||
let r = x
|
||||
while (parent.get(r) !== r) r = parent.get(r)
|
||||
while (parent.get(x) !== x) { const n = parent.get(x); parent.set(x, r); x = n }
|
||||
return r
|
||||
}
|
||||
function union(a, b) { parent.set(find(a), find(b)) }
|
||||
|
||||
async function main() {
|
||||
if (!existsSync(INDEX)) throw new Error(`Индекс не найден: ${INDEX} — сначала kb-embed build`)
|
||||
if (!existsSync(KB_EMBED)) throw new Error(`kb-embed не найден: ${KB_EMBED}`)
|
||||
const dirs = await sectionDirs()
|
||||
const notes = await collectNotes(dirs)
|
||||
console.error(`Разделы: ${dirs.map(d => path.basename(d)).join(' · ')} — ${notes.length} нот, jobs=${JOBS}`)
|
||||
|
||||
const edges = new Map() // "a\0b" (упорядоченно) → лучшее ребро пары
|
||||
const failures = []
|
||||
let done = 0
|
||||
let cursor = 0
|
||||
|
||||
async function worker() {
|
||||
while (cursor < notes.length) {
|
||||
const note = notes[cursor++]
|
||||
const meta = await noteMeta(note)
|
||||
if (!meta.body) { done++; continue }
|
||||
const text = `${noteTitle(note)}\n${meta.body.slice(0, QUERY_BODY_CHARS)}`
|
||||
const res = await runQuery(text)
|
||||
done++
|
||||
if (done % 50 === 0) console.error(` ...${done}/${notes.length}`)
|
||||
let parsed
|
||||
try { parsed = JSON.parse(res.stdout) } catch { parsed = null }
|
||||
if (res.code !== 0 || !parsed || parsed.error) {
|
||||
failures.push({ note, detail: parsed?.error || res.stderr.slice(0, 200) || `exit ${res.code}` })
|
||||
continue
|
||||
}
|
||||
for (const m of parsed.matches || []) {
|
||||
if (nfc(m.note) === nfc(note)) continue // самосовпадение — не дубль
|
||||
if (m.zone !== 'merge' && m.zone !== 'flag') continue
|
||||
// служебные плоскости (_archive и пр.) — страховка на случай индекса, собранного старым build
|
||||
if (m.note.split(path.sep).some(seg => seg.startsWith('_'))) continue
|
||||
const [a, b] = [note, m.note].sort()
|
||||
const key = `${a}\0${b}`
|
||||
const prev = edges.get(key)
|
||||
if (!prev || m.combined > prev.combined) edges.set(key, { a, b, ...m })
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.max(1, JOBS) }, worker))
|
||||
|
||||
if (failures.length) {
|
||||
console.error(`kb-embed query упал на ${failures.length} нотах, отчёт не пишу (fail-closed):`)
|
||||
for (const f of failures.slice(0, 10)) console.error(` ${f.note}: ${f.detail}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// взаимный фильтр рёбер → union-find → сборка кластеров
|
||||
const partners = new Map() // нота → её рёбра по убыванию combined
|
||||
for (const e of edges.values()) {
|
||||
for (const n of [e.a, e.b]) {
|
||||
if (!partners.has(n)) partners.set(n, [])
|
||||
partners.get(n).push(e)
|
||||
}
|
||||
}
|
||||
for (const list of partners.values()) list.sort((x, y) => y.combined - x.combined)
|
||||
const inTop = (n, e) => partners.get(n).slice(0, MUTUAL_TOP).includes(e)
|
||||
const kept = [...edges.values()].filter(e => inTop(e.a, e) && inTop(e.b, e))
|
||||
for (const e of kept) union(e.a, e.b)
|
||||
const byRoot = new Map()
|
||||
for (const e of kept) {
|
||||
const root = find(e.a)
|
||||
if (!byRoot.has(root)) byRoot.set(root, { members: new Set(), edges: [] })
|
||||
const c = byRoot.get(root)
|
||||
c.members.add(e.a); c.members.add(e.b); c.edges.push(e)
|
||||
}
|
||||
const clusters = []
|
||||
for (const c of byRoot.values()) {
|
||||
const members = []
|
||||
for (const p of c.members) {
|
||||
const meta = await noteMeta(p)
|
||||
const best = c.edges.filter(e => e.a === p || e.b === p)
|
||||
.reduce((x, e) => (!x || e.combined > x.combined ? e : x), null)
|
||||
members.push({ path: p, ...meta, best })
|
||||
}
|
||||
// канон: свежее побеждает, при равной дате — полнее (объём тела)
|
||||
members.sort((x, y) => y.date.localeCompare(x.date) || y.chars - x.chars)
|
||||
const zone = c.edges.some(e => e.zone === 'merge') ? 'merge' : 'flag'
|
||||
clusters.push({ zone, members, edges: c.edges })
|
||||
}
|
||||
clusters.sort((x, y) => (x.zone === y.zone ? y.members.length - x.members.length : x.zone === 'merge' ? -1 : 1))
|
||||
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
const mergeCount = clusters.filter(c => c.zone === 'merge').length
|
||||
const lines = [
|
||||
`# Dedup-отчёт Мнемозины — ${today}`,
|
||||
'',
|
||||
'Режим только-отчёт: ничего не слито. Мерж-вердикт — суждение, его исполняет Кими-рой по этому отчёту.',
|
||||
'',
|
||||
`- Разделы: ${dirs.map(d => path.basename(d)).join(' · ')} — просканировано ${notes.length} нот`,
|
||||
`- Индекс: ${INDEX}`,
|
||||
`- Зоны (kb-embed): merge ≥ 0.90 · flag ≥ 0.72 по combined = cosine + 0.3×title_sim (title_sim ≥ 0.5)`,
|
||||
`- Кластеризация: только взаимные рёбра (оба конца в топ-${MUTUAL_TOP} партнёров друг друга) — против сшивания через хабы-подборки`,
|
||||
`- Кластеров: ${clusters.length} (merge: ${mergeCount}, flag: ${clusters.length - mergeCount})`,
|
||||
'',
|
||||
]
|
||||
clusters.forEach((c, i) => {
|
||||
lines.push(`## Кластер ${i + 1} — ${c.zone} (${c.members.length} нот)`)
|
||||
const canon = c.members[0]
|
||||
lines.push(`Кандидат-канон: **${path.relative(VAULT, canon.path)}** (${canon.date}, ${canon.chars} симв — свежее/полнее остальных)`)
|
||||
lines.push('')
|
||||
lines.push('| нота | зона | combined | cosine | title_sim | дата | симв |')
|
||||
lines.push('|---|---|---|---|---|---|---|')
|
||||
for (const m of c.members) {
|
||||
const rel = path.relative(VAULT, m.path) + (m.exists ? '' : ' ⚠️ файла нет — индекс отстал')
|
||||
lines.push(`| ${rel} | ${m.best.zone} | ${m.best.combined} | ${m.best.score} | ${m.best.title_sim} | ${m.date || '?'} | ${m.chars} |`)
|
||||
}
|
||||
lines.push('')
|
||||
})
|
||||
if (!clusters.length) lines.push('Дублей в зонах merge/flag не найдено.')
|
||||
|
||||
await fs.mkdir(path.dirname(OUT), { recursive: true })
|
||||
await fs.writeFile(OUT, lines.join('\n') + '\n', 'utf8')
|
||||
console.log(JSON.stringify({ report: OUT, scanned: notes.length, clusters: clusters.length, merge: mergeCount, flag: clusters.length - mergeCount }))
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(error.message)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -12,12 +12,27 @@ DRY_RUN=0
|
||||
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
|
||||
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
|
||||
|
||||
CONFIG_VAULT=""
|
||||
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)"
|
||||
fi
|
||||
DEFAULT_VAULT="$REPO/vault"
|
||||
|
||||
export MNEMAZINE_ROOT="$REPO"
|
||||
BASE_INBOX="${ENV_INBOX:-${MNEMAZINE_INBOX:-$HOME/Desktop/Mnemazine Inbox}}"
|
||||
export MNEMAZINE_VAULT="${ENV_VAULT:-${MNEMAZINE_VAULT:-$HOME/Мозг}}"
|
||||
export MNEMAZINE_DEEP="${ENV_DEEP:-${MNEMAZINE_DEEP:-1}}"
|
||||
export MNEMAZINE_VAULT="${ENV_VAULT:-${MNEMAZINE_VAULT:-${CONFIG_VAULT:-$DEFAULT_VAULT}}}"
|
||||
if [ -n "$ENV_DEEP" ]; then
|
||||
export MNEMAZINE_DEEP="$ENV_DEEP"
|
||||
fi
|
||||
export MNEMAZINE_REQUIRE_DEEP="${ENV_REQUIRE_DEEP:-${MNEMAZINE_REQUIRE_DEEP:-1}}"
|
||||
|
||||
# Draft mode writes nothing to the vault and never archives. Silent draft runs
|
||||
# look like успешный прогон, so say it out loud before any work starts.
|
||||
if [ "${MNEMAZINE_DRAFT_ONLY:-0}" = "1" ]; then
|
||||
echo "WARNING: MNEMAZINE_DRAFT_ONLY=1 — draft only: заметки в vault НЕ пишутся, инбокс НЕ архивируется." >&2
|
||||
echo " Снять в .mnemazine/config.local.sh или запустить: MNEMAZINE_DRAFT_ONLY=0 npm start" >&2
|
||||
fi
|
||||
|
||||
active_count() {
|
||||
find "$1" -maxdepth 1 -type f ! -name '.*' 2>/dev/null | wc -l | tr -d ' '
|
||||
}
|
||||
@@ -29,10 +44,13 @@ run_inbox() {
|
||||
[ "$count" = "0" ] && return 0
|
||||
echo "Mnemazine protocol: $inbox ($count files)" >&2
|
||||
ran=1
|
||||
MNEMAZINE_INBOX="${inbox%/}" npm run run -- --deep --require-deep
|
||||
MNEMAZINE_INBOX="${inbox%/}" npm run run -- --require-deep
|
||||
}
|
||||
|
||||
mkdir -p "$BASE_INBOX" "$MNEMAZINE_VAULT"
|
||||
mkdir -p "$BASE_INBOX"
|
||||
if [ "$MNEMAZINE_VAULT" = "$DEFAULT_VAULT" ]; then
|
||||
mkdir -p "$MNEMAZINE_VAULT"
|
||||
fi
|
||||
|
||||
if [ "$DRY_RUN" = "1" ]; then
|
||||
tmp="$(mktemp -d "${TMPDIR:-/tmp}/mnemazine-desktop-dry-run.XXXXXX")"
|
||||
@@ -66,9 +84,10 @@ if [ -d "$NESTED" ]; then
|
||||
run_inbox "$NESTED"
|
||||
fi
|
||||
|
||||
# An empty inbox is no reason to skip the final gates — that exact hole let 20.08
|
||||
# close green with nothing verified. Say it, then still run completion.
|
||||
if [ "$ran" = "0" ]; then
|
||||
echo "Mnemazine protocol: no active inbox files" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MNEMAZINE_INBOX="${BASE_INBOX%/}" npm run complete -- --require-deep
|
||||
|
||||
@@ -11,6 +11,7 @@ import { promises as fs, readFileSync, existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { preservationCheck } from './mnemazine-humanize-gate.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
@@ -84,14 +85,18 @@ ${fenceUntrusted('ЗАМЕТКА', noteText.slice(0, 12000))}`
|
||||
const MAX_CONNECTIONS = 6
|
||||
async function loadConnections() {
|
||||
const byNote = new Map()
|
||||
const notes = [] // { rel, cluster, hosts:Set }
|
||||
const titleByNote = new Map()
|
||||
const notes = [] // { rel, title, cluster, hosts:Set }
|
||||
for (const file of await walk(VAULT)) {
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
if (!text) continue
|
||||
const title = titleOf(text, file)
|
||||
const cluster = text.match(/^cluster_id:\s*"?([^"\n]+)"?/m)?.[1]?.trim() || null
|
||||
const hosts = new Set()
|
||||
for (const m of text.matchAll(/https?:\/\/([^/\s)]+)/g)) hosts.add(m[1].replace(/^www\./, ''))
|
||||
notes.push({ rel: path.relative(VAULT, file), cluster, hosts })
|
||||
const rel = path.relative(VAULT, file)
|
||||
titleByNote.set(rel, title)
|
||||
notes.push({ rel, title, cluster, hosts })
|
||||
}
|
||||
for (const a of notes) {
|
||||
const siblings = [], related = []
|
||||
@@ -103,7 +108,7 @@ async function loadConnections() {
|
||||
const list = [...siblings, ...related].slice(0, MAX_CONNECTIONS)
|
||||
if (list.length) byNote.set(a.rel, list)
|
||||
}
|
||||
return byNote
|
||||
return { byNote, titleByNote }
|
||||
}
|
||||
|
||||
async function walk(dir) {
|
||||
@@ -122,6 +127,16 @@ function titleOf(text, file) {
|
||||
return text.match(/^title:\s*"([^"]+)"/m)?.[1] || text.match(/^#\s+(.+)$/m)?.[1]?.trim() || path.basename(file, '.md')
|
||||
}
|
||||
|
||||
function linkAlias(rel, title) {
|
||||
const raw = title || path.basename(rel, '.md')
|
||||
const cleaned = String(raw).replace(/[\]\|\n\r]+/g, ' ').replace(/\s+/g, ' ').trim()
|
||||
return /[А-Яа-яЁё]/.test(cleaned) ? cleaned : `Заметка: ${cleaned}`
|
||||
}
|
||||
|
||||
function wikiLink(rel, title) {
|
||||
return `[[${rel.replace(/\.md$/, '')}|${linkAlias(rel, title)}]]`
|
||||
}
|
||||
|
||||
function clean(text, max = 420) {
|
||||
return String(text || '')
|
||||
.replace(/```[\s\S]*?```/g, '')
|
||||
@@ -153,8 +168,8 @@ function deterministicDigest(noteText, file) {
|
||||
}
|
||||
}
|
||||
|
||||
function spravkaBlock(d, connections) {
|
||||
const conns = connections.length ? connections.map(c => `- [[${c.replace(/\.md$/, '')}]]`).join('\n') : '- (отдельных связей не найдено)'
|
||||
function spravkaBlock(d, connections, titleByNote) {
|
||||
const conns = connections.length ? connections.map(c => `- ${wikiLink(c, titleByNote.get(c))}`).join('\n') : '- (отдельных связей не найдено)'
|
||||
return `${SPRAVKA}
|
||||
|
||||
**${d.zagolovok}**
|
||||
@@ -170,9 +185,10 @@ ${conns}
|
||||
|
||||
async function main() {
|
||||
const modelAvailable = !DETERMINISTIC && llmAvailable(PROVIDER)
|
||||
const connByNote = await loadConnections()
|
||||
const { byNote: connByNote, titleByNote } = await loadConnections()
|
||||
const files = await walk(VAULT)
|
||||
const summary = []
|
||||
const lostNotes = []
|
||||
let written = 0
|
||||
for (const file of files) {
|
||||
if (LIMIT && written >= LIMIT) break
|
||||
@@ -195,8 +211,22 @@ async function main() {
|
||||
// (No `m` flag: a per-line `$` would stop at the first newline and leave the old
|
||||
// Справка in place, duplicating it on every --force run.)
|
||||
const stripped = FORCE ? text.replace(new RegExp(`\\n*${SPRAVKA}[\\s\\S]*$`), '\n') : text
|
||||
const block = spravkaBlock(d, connections)
|
||||
await fs.writeFile(file, `${stripped.trimEnd()}\n\n${block}`, 'utf8')
|
||||
const block = spravkaBlock(d, connections, titleByNote)
|
||||
const newText = `${stripped.trimEnd()}\n\n${block}`
|
||||
// План П13 шаг 5: --force вырезает всё от первого ## Справка до EOF — готовый путь
|
||||
// потери фактов. Перед записью гейт сохранности сверяет инварианты (числа/ссылки/
|
||||
// пути/код/frontmatter/заголовки; clean:false — читаемость не при чём, дайджест лишь
|
||||
// дописывает Справку). Потеря → файл не переписывается, расхождение в отчёт, прогон
|
||||
// падает через run.mjs (digest.status !== 0).
|
||||
let guard
|
||||
try { guard = preservationCheck(text, newText, { clean: false }) }
|
||||
catch (err) { guard = { code: 2, lost: [{ kind: 'input', sample: String(err.message).slice(0, 120) }] } }
|
||||
if (guard.code !== 0) {
|
||||
lostNotes.push({ rel, code: guard.code, lost: guard.lost.slice(0, 8) })
|
||||
console.error(JSON.stringify({ digest_preservation_fail: rel, code: guard.code, lost: guard.lost.slice(0, 8) }))
|
||||
continue
|
||||
}
|
||||
await fs.writeFile(file, newText, 'utf8')
|
||||
summary.push({ rel, title: titleOf(text, file), zagolovok: d.zagolovok, connections })
|
||||
written += 1
|
||||
}
|
||||
@@ -213,14 +243,17 @@ async function main() {
|
||||
`## Как использовать\n\n- Открыть связанные заметки из списка ниже.\n- Взять сильные next actions в работу.\n- Проверить слабые или неподтверждённые связи перед публикацией.\n`,
|
||||
`## Источник\n\n- source_ref: digest:${SESSION}\n- processed_notes: ${summary.length}\n`,
|
||||
`## Проверка\n\nСводка построена локально из заметок vault и связей digest-этапа. Не является внешней факт-проверкой.\n`,
|
||||
`## Связанные заметки\n\n- [[Mnemazine Protocol]]\n`,
|
||||
`## Связанные заметки\n\n- [[Mnemazine Protocol|Протокол Mnemazine]]\n`,
|
||||
`## Повторное использование\n\nОбработано заметок: ${summary.length}. Ниже — что узнано и как связано.\n`,
|
||||
...summary.map(s => `## ${s.zagolovok}\n\n- Заметка: [[${s.rel.replace(/\.md$/, '')}]]\n- Связи: ${s.connections.length ? s.connections.map(c => `[[${c.replace(/\.md$/, '')}]]`).join(', ') : '—'}\n`)
|
||||
...summary.map(s => `## ${s.zagolovok}\n\n- Заметка: ${wikiLink(s.rel, s.zagolovok || s.title)}\n- Связи: ${s.connections.length ? s.connections.map(c => wikiLink(c, titleByNote.get(c))).join(', ') : '—'}\n`)
|
||||
].join('\n')
|
||||
await fs.writeFile(path.join(dir, `Сводка-${SESSION}.md`), body, 'utf8')
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ ok: true, provider: PROVIDER, model_available: modelAvailable, written, summary: summary.length, linked: connByNote.size }, null, 2))
|
||||
const ok = lostNotes.length === 0
|
||||
console.log(JSON.stringify({ ok, provider: PROVIDER, model_available: modelAvailable, written, summary: summary.length, linked: connByNote.size, preservation_failures: lostNotes.length, lost: lostNotes }, null, 2))
|
||||
// Ненулевой код роняет прогон (run.mjs: digest.status !== 0 → failRunState).
|
||||
if (!ok) process.exitCode = 1
|
||||
}
|
||||
|
||||
main().catch(err => { console.error(err.message || err); process.exit(1) })
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env node
|
||||
// Документация отвечает за свои слова (план П11, метод-правило 12 — честная граница).
|
||||
//
|
||||
// Выводимая часть (всегда блокирующая):
|
||||
// - каждая `npm run <target>` из README.md/README.ru.md/docs/*.md существует в package.json,
|
||||
// и файл, на который цель указывает, отслеживается git. Извлекается любой непробельный
|
||||
// токен цели (кириллица/юникод тоже, не только латиница) с обрезкой оправы по краям;
|
||||
// несуществующая цель → провал с именем цели и файлом:строкой. Легальные плейсхолдеры —
|
||||
// только через явный PLACEHOLDER_TARGETS, не смягчением regex;
|
||||
// - каждый упомянутый scripts/<file> существует и отслеживается git;
|
||||
// - путь vault из README сходится с DEFAULT_VAULT (scripts/mnemazine-paths.mjs).
|
||||
// Объявленная часть: config/doc-claims.json — {claim, command, expect_exit, enforcement}.
|
||||
// Блокирующий claim с несходящимся кодом → провал; warn → предупреждение. Claim с
|
||||
// execute:false не исполняется (например doctor: он сам гоняет release-check — рекурсия).
|
||||
//
|
||||
// Коды: 2 — ноль извлечённых утверждений; 1 — любой блокирующий провал; 0 — иначе.
|
||||
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { DEFAULT_VAULT } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const CLAIMS = path.join(ROOT, 'config', 'doc-claims.json')
|
||||
|
||||
function gitTracked() {
|
||||
const r = spawnSync('git', ['ls-files'], { cwd: ROOT, encoding: 'utf8' })
|
||||
if (r.status !== 0) throw new Error(`git ls-files failed: ${r.stderr}`)
|
||||
return new Set(r.stdout.split(/\r?\n/).map(s => s.trim()).filter(Boolean))
|
||||
}
|
||||
|
||||
function docSources() {
|
||||
const files = []
|
||||
for (const rel of ['README.md', 'README.ru.md']) {
|
||||
const p = path.join(ROOT, rel)
|
||||
if (existsSync(p)) files.push({ name: rel, text: readFileSync(p, 'utf8') })
|
||||
}
|
||||
// Только отслеживаемые docs/*.md (git ls-files исключает игнорируемые PLAN-*.md).
|
||||
const r = spawnSync('git', ['ls-files', 'docs/*.md'], { cwd: ROOT, encoding: 'utf8' })
|
||||
if (r.status === 0) {
|
||||
for (const rel of r.stdout.split(/\r?\n/).map(s => s.trim()).filter(Boolean)) {
|
||||
const p = path.join(ROOT, rel)
|
||||
if (existsSync(p)) files.push({ name: rel, text: readFileSync(p, 'utf8') })
|
||||
}
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
function pkgScripts() {
|
||||
return JSON.parse(readFileSync(path.join(ROOT, 'package.json'), 'utf8')).scripts || {}
|
||||
}
|
||||
|
||||
function targetFile(command) {
|
||||
const m = String(command).match(/(scripts|tests)\/[A-Za-z0-9_.-]+\.(mjs|js|py|sh)/)
|
||||
return m ? m[0] : null
|
||||
}
|
||||
|
||||
// Легальные плейсхолдеры-примеры: явный список с причиной, НЕ regex-помягчение.
|
||||
// Пусто — в проверяемых доках (README*, tracked docs/*.md) реальных плейсхолдеров нет.
|
||||
// Появится `npm run <foo>` как пример — вписать сюда цель + причину, не расширять regex.
|
||||
const PLACEHOLDER_TARGETS = new Map(/* [target, reason] */)
|
||||
|
||||
// Захват любого непробельного токена после `npm run ` (ловит кириллицу/юникод, не только латиницу),
|
||||
// затем обрезка «оправы» — бэктиков, кавычек, скобок, знаков препинания — по краям.
|
||||
// Внутренние `:`/`-`/`.`/`_` (audit:vault, graph:semantic:async, last-run) сохраняются.
|
||||
const EDGE = /^[`"'([{<.,;:)\]}>»«]+|[`"'([{<.,;:)\]}>»«]+$/g
|
||||
function normTarget(raw) {
|
||||
return raw.replace(EDGE, '')
|
||||
}
|
||||
|
||||
function lineOf(text, index) {
|
||||
return text.slice(0, index).split('\n').length
|
||||
}
|
||||
|
||||
// Выводимая часть. Возвращает {checked, failures}.
|
||||
function checkOutput({ docs, scripts, tracked }) {
|
||||
const failures = []
|
||||
let checked = 0
|
||||
for (const { name, text } of docs) {
|
||||
for (const m of text.matchAll(/npm run (\S+)/g)) {
|
||||
const target = normTarget(m[1])
|
||||
if (!target) continue
|
||||
checked++
|
||||
if (PLACEHOLDER_TARGETS.has(target)) continue
|
||||
const at = `${name}:${lineOf(text, m.index)}`
|
||||
if (!(target in scripts)) { failures.push(`${at}: npm run ${target} — цели нет в package.json`); continue }
|
||||
const file = targetFile(scripts[target])
|
||||
if (file && !tracked.has(file)) failures.push(`${at}: npm run ${target} → ${file} не отслеживается git`)
|
||||
}
|
||||
for (const m of text.matchAll(/(?:scripts|tests)\/[A-Za-z0-9_.-]+\.(?:mjs|js|py|sh)/g)) {
|
||||
checked++
|
||||
const file = m[0]
|
||||
if (!tracked.has(file)) failures.push(`${name}:${lineOf(text, m.index)}: упомянут ${file}, не отслеживается git`)
|
||||
}
|
||||
}
|
||||
return { checked, failures }
|
||||
}
|
||||
|
||||
function checkVaultPath(docs) {
|
||||
const failures = []
|
||||
const readme = docs.find(d => d.name === 'README.md')
|
||||
if (!readme) return { checked: 0, failures }
|
||||
const m = readme.text.match(/~\/[^\s`"'\n]*\/vault\b/)
|
||||
if (!m) return { checked: 0, failures }
|
||||
const declared = path.basename(m[0])
|
||||
const expected = path.basename(DEFAULT_VAULT)
|
||||
if (declared !== expected) {
|
||||
failures.push(`README путь vault "${m[0]}" (basename ${declared}) расходится с DEFAULT_VAULT (basename ${expected})`)
|
||||
}
|
||||
return { checked: 1, failures }
|
||||
}
|
||||
|
||||
function runClaims(claimsCfg) {
|
||||
const claims = Array.isArray(claimsCfg?.claims) ? claimsCfg.claims : []
|
||||
const failures = []
|
||||
const warnings = []
|
||||
let checked = 0
|
||||
for (const c of claims) {
|
||||
if (c.execute === false) continue
|
||||
checked++
|
||||
const [cmd, ...args] = c.command
|
||||
const r = spawnSync(cmd, args, { cwd: ROOT, encoding: 'utf8' })
|
||||
const code = r.status == null ? 1 : r.status
|
||||
if (code !== c.expect_exit) {
|
||||
const line = `claim "${c.claim}" → код ${code}, ожидался ${c.expect_exit}`
|
||||
if (c.enforcement === 'warn') warnings.push(line)
|
||||
else failures.push(line)
|
||||
}
|
||||
}
|
||||
return { checked, failures, warnings }
|
||||
}
|
||||
|
||||
function loadClaims() {
|
||||
if (!existsSync(CLAIMS)) return { claims: [] }
|
||||
try { return JSON.parse(readFileSync(CLAIMS, 'utf8')) } catch (e) { return { claims: [], _error: e.message } }
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
// Красные кролики: несуществующая npm-цель обязана покраснеть — латинская И кириллическая
|
||||
// (кириллица — тот самый пропуск, что дал ложный зелёный до фикса), с именем цели и строкой.
|
||||
const scripts = pkgScripts()
|
||||
const tracked = gitTracked()
|
||||
const cases = [
|
||||
{ label: 'латиница', target: 'totally-nonexistent-target-xyz' },
|
||||
{ label: 'кириллица', target: 'несуществующая-цель-п11' },
|
||||
]
|
||||
for (const { label, target } of cases) {
|
||||
const docs = [{ name: 'README.md', text: `# X\nline2\nRun \`npm run ${target}\` to break.\n` }]
|
||||
const { failures } = checkOutput({ docs, scripts, tracked })
|
||||
const hit = failures.find(f => f.includes(target))
|
||||
if (!hit) {
|
||||
console.error(`selftest FAILED: красный кролик (${label}: ${target}) прошёл зелёным`)
|
||||
return 1
|
||||
}
|
||||
if (!/README\.md:\d+:/.test(hit)) {
|
||||
console.error(`selftest FAILED: провал без файла:строки — "${hit}"`)
|
||||
return 1
|
||||
}
|
||||
}
|
||||
console.log('selftest ok: несуществующая npm-цель (латиница+кириллица) краснит с файлом:строкой')
|
||||
return 0
|
||||
}
|
||||
|
||||
function main() {
|
||||
const argv = process.argv.slice(2)
|
||||
if (argv.includes('--selftest')) process.exit(selftest())
|
||||
|
||||
const docs = docSources()
|
||||
const scripts = pkgScripts()
|
||||
const tracked = gitTracked()
|
||||
const claims = loadClaims()
|
||||
|
||||
const out = checkOutput({ docs, scripts, tracked })
|
||||
const vault = checkVaultPath(docs)
|
||||
const declared = runClaims(claims)
|
||||
|
||||
const totalChecked = out.checked + vault.checked + declared.checked
|
||||
if (totalChecked === 0) { console.error('ноль извлечённых утверждений'); process.exit(2) }
|
||||
|
||||
const failures = [...out.failures, ...vault.failures, ...declared.failures]
|
||||
for (const w of declared.warnings) console.error(`warn: ${w}`)
|
||||
if (claims._error) console.error(`warn: config/doc-claims.json нечитаем: ${claims._error}`)
|
||||
|
||||
if (failures.length) {
|
||||
console.error('ПРОВАЛЫ:')
|
||||
for (const f of failures) console.error(` - ${f}`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`doc-contract ok: проверено утверждений ${totalChecked}, предупреждений ${declared.warnings.length}`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
main()
|
||||
+275
-11
@@ -9,7 +9,77 @@ const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
|
||||
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
|
||||
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
|
||||
const REBUILD = path.join(STATE, 'rebuild')
|
||||
const JSON_OUT = process.argv.includes('--json')
|
||||
const STRICT_GRAPH = process.argv.includes('--strict-graph') || process.env.MNEMAZINE_DOCTOR_STRICT_GRAPH === '1'
|
||||
const FULL_VAULT = process.argv.includes('--full-vault') || process.env.MNEMAZINE_DOCTOR_FULL_VAULT === '1'
|
||||
const SELFTEST = process.argv.includes('--selftest')
|
||||
const WATCH = process.argv.includes('--watch')
|
||||
|
||||
if (process.argv.includes('--help')) {
|
||||
console.log(`mnemazine-doctor.mjs — сводная диагностика: последний прогон, гейты корпуса,
|
||||
маркеры графа, состояние semantic-задачи, дымовые пробы. Только читает корпус:
|
||||
последовательность complete / last-run / graph:smoke / release-check ничего в нём не меняет.
|
||||
|
||||
Использование: node scripts/mnemazine-doctor.mjs [флаги]
|
||||
--json результат в JSON
|
||||
--strict-graph маркеры needs_update — failures, а не warnings
|
||||
--full-vault добавить полный аудит корпуса (human-layer + vault-final-audit)
|
||||
--watch следить за semantic-задачей до её остановки (только human-вывод)
|
||||
--watch-interval-seconds N интервал watch (по умолчанию 10)
|
||||
--selftest селф-тест во временном каталоге
|
||||
--help эта справка
|
||||
|
||||
Коды возврата: 0 — всё зелёное; 2 — провалов нет, но есть предупреждения; 1 — есть провалы или ошибка.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// Каждая красная строка несёт команду починки: доктор не только называет провал,
|
||||
// но и говорит, чем его лечить (приём эталона setup_doctor.py:501-503).
|
||||
const DOCTOR_FIX = {
|
||||
complete: 'npm run complete -- --require-deep',
|
||||
'human-layer': 'npm run human-layer:quality',
|
||||
'human-layer-full': 'npm run doctor:full',
|
||||
'vault-final-audit': 'npm run audit:vault',
|
||||
'last-run': 'npm start # сделай прогон, затем npm run last-run -- --require-ok',
|
||||
'graph-smoke': 'npm run graph:smoke',
|
||||
'release-check': 'npm run release-check',
|
||||
inbox: 'npm start # обработай входящие, потом повтори проверку'
|
||||
}
|
||||
function fixFor(name) {
|
||||
return DOCTOR_FIX[name] || 'npm run doctor -- --json # смотри детали и повтори шаг'
|
||||
}
|
||||
function failureLine(name, label) {
|
||||
return `${label} — как починить: ${fixFor(name)}`
|
||||
}
|
||||
|
||||
const COMPLETE_NO_DATA_FAILURES = new Set([
|
||||
'last run state missing',
|
||||
'weekly report missing',
|
||||
'action brief missing',
|
||||
'weekly report older than newest vault note',
|
||||
'action brief older than newest vault note',
|
||||
// Свежая установка: потолок спеки — per-machine runtime, на чистом клоне его нет.
|
||||
// Ratchet без базы — не провал, а «ещё не прогонял» (см. complete-check spec-ceiling).
|
||||
'spec ceiling has no baseline yet'
|
||||
])
|
||||
|
||||
const LAST_RUN_NO_DATA_FAILURES = new Set([
|
||||
'last-run.json missing',
|
||||
'last-action-brief.md missing',
|
||||
'HTML report missing'
|
||||
])
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = process.argv.find(item => item === `--${name}` || item.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : process.argv[process.argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
function watchIntervalMs() {
|
||||
const seconds = Number(arg('watch-interval-seconds', process.env.MNEMAZINE_DOCTOR_WATCH_INTERVAL_SECONDS || '10'))
|
||||
return Math.max(1000, (Number.isFinite(seconds) && seconds > 0 ? seconds : 10) * 1000)
|
||||
}
|
||||
|
||||
async function readJson(file, fallback = null) {
|
||||
try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
|
||||
@@ -43,6 +113,43 @@ function run(name, command, args, env = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
function parseJsonObject(text) {
|
||||
const raw = String(text || '').trim()
|
||||
if (!raw) return null
|
||||
try { return JSON.parse(raw) } catch {}
|
||||
const start = raw.indexOf('{')
|
||||
const end = raw.lastIndexOf('}')
|
||||
if (start === -1 || end <= start) return null
|
||||
try { return JSON.parse(raw.slice(start, end + 1)) } catch { return null }
|
||||
}
|
||||
|
||||
function lineFailures(text) {
|
||||
const match = String(text || '').match(/^Failures:\s*(.+)$/m)
|
||||
return match ? match[1].split(';').map(item => item.trim()).filter(Boolean) : []
|
||||
}
|
||||
|
||||
function onlyKnownNoData(failures, allowed) {
|
||||
return failures.length > 0 && failures.every(item => allowed.has(String(item)))
|
||||
}
|
||||
|
||||
function ownerMachine() {
|
||||
return existsSync(path.join(REBUILD, 'П01.done.json'))
|
||||
}
|
||||
|
||||
function noDataWarning(result, { ownerOps = ownerMachine() } = {}) {
|
||||
if (result.ok) return ''
|
||||
const text = [result.stdout, result.stderr].filter(Boolean).join('\n')
|
||||
const json = parseJsonObject(text)
|
||||
if (result.name === 'complete' && onlyKnownNoData(json?.failures || [], COMPLETE_NO_DATA_FAILURES)) {
|
||||
return `complete has no last-run data yet — как починить: ${fixFor('last-run')}`
|
||||
}
|
||||
const liveFailures = json?.failures || lineFailures(text)
|
||||
if (!ownerOps && result.name === 'last-run' && json?.last_run === null && onlyKnownNoData(liveFailures, LAST_RUN_NO_DATA_FAILURES)) {
|
||||
return `last run state missing — как починить: ${fixFor('last-run')}`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
async function activeInboxFiles(dir) {
|
||||
return (await fs.readdir(dir, { withFileTypes: true }).catch(() => []))
|
||||
.filter(item => item.isFile() && !item.name.startsWith('.'))
|
||||
@@ -66,19 +173,143 @@ async function graphMarkers(vault) {
|
||||
]
|
||||
const out = []
|
||||
for (const file of [...new Set(candidates.map(item => path.resolve(item)))]) {
|
||||
const stat = existsSync(file) ? await fs.stat(file) : null
|
||||
out.push({
|
||||
file,
|
||||
exists: existsSync(file),
|
||||
content: existsSync(file) ? (await fs.readFile(file, 'utf8')).trim() : ''
|
||||
content: existsSync(file) ? (await fs.readFile(file, 'utf8')).trim() : '',
|
||||
age_days: stat ? (Date.now() - stat.mtimeMs) / 86400000 : null
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function semanticTaskStatus(stateDir = STATE) {
|
||||
const file = path.join(stateDir, 'semantic-graph-task.json')
|
||||
const state = await readJson(file, { status: 'never-run' })
|
||||
let running = false
|
||||
if (state.status === 'running' && Number(state.pid) > 0) {
|
||||
try {
|
||||
process.kill(Number(state.pid), 0)
|
||||
running = true
|
||||
} catch {
|
||||
running = false
|
||||
}
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
running,
|
||||
state_file: file,
|
||||
log_file: path.join(stateDir, 'semantic-graph-task.log')
|
||||
}
|
||||
}
|
||||
|
||||
async function semanticTaskPretty(env = {}) {
|
||||
return run('semantic-status-pretty', process.execPath, ['scripts/mnemazine-semantic-graph-task.mjs', '--status', '--pretty'], env)
|
||||
}
|
||||
|
||||
function tail(text, lines = 16) {
|
||||
return String(text || '').split('\n').slice(-lines).join('\n')
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function semanticTaskHumanLines(semanticTask, semanticPretty) {
|
||||
if (semanticTask.status === 'never-run') return []
|
||||
const lines = [`Semantic task: ${semanticTask.status}${semanticTask.running ? ' (running)' : ''}`]
|
||||
if (semanticPretty) {
|
||||
lines.push('Semantic task detail:')
|
||||
lines.push(semanticPretty?.ok ? semanticPretty.stdout : tail(semanticPretty?.stderr || semanticPretty?.stdout || 'semantic status unavailable'))
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
function needsSemanticDetail(semanticTask) {
|
||||
return semanticTask.status !== 'never-run' && (
|
||||
semanticTask.running ||
|
||||
['pending', 'failed', 'running'].includes(String(semanticTask.status || ''))
|
||||
)
|
||||
}
|
||||
|
||||
async function semanticWatchTick(env = {}, stateDir = STATE) {
|
||||
const status = await semanticTaskStatus(stateDir)
|
||||
const pretty = await semanticTaskPretty(env)
|
||||
return {
|
||||
status,
|
||||
pretty,
|
||||
done: !status.running,
|
||||
ok: status.status !== 'failed' && !(status.status === 'running' && !status.running),
|
||||
lines: [
|
||||
`Semantic watch ${new Date().toISOString()}:`,
|
||||
pretty.ok ? pretty.stdout : tail(pretty.stderr || pretty.stdout || 'semantic status unavailable')
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
async function watchSemanticTask(env = {}) {
|
||||
const interval = watchIntervalMs()
|
||||
console.log(`\nSemantic watch: every ${Math.round(interval / 1000)}s until task stops.`)
|
||||
while (true) {
|
||||
await sleep(interval)
|
||||
const tick = await semanticWatchTick(env)
|
||||
console.log('')
|
||||
for (const line of tick.lines) console.log(line)
|
||||
if (tick.done) return tick.ok
|
||||
}
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const temp = await fs.mkdtemp(path.join('/tmp', 'mnemazine-doctor-'))
|
||||
await fs.writeFile(path.join(temp, 'semantic-graph-task.json'), JSON.stringify({
|
||||
status: 'running',
|
||||
pid: process.pid,
|
||||
started_at: new Date(Date.now() - 65000).toISOString(),
|
||||
vault: '/tmp/vault',
|
||||
strategy: 'swarm'
|
||||
}, null, 2), 'utf8')
|
||||
const pretty = await semanticTaskPretty({ MNEMAZINE_STATE: temp })
|
||||
if (!pretty.ok) throw new Error(`doctor selftest failed: pretty status command failed\n${pretty.stderr || pretty.stdout}`)
|
||||
if (!pretty.stdout.includes('Task: running yes')) throw new Error('doctor selftest failed: running detail missing')
|
||||
if (!pretty.stdout.includes(`PID ${process.pid}`)) throw new Error('doctor selftest failed: PID missing')
|
||||
if (!pretty.stdout.includes('elapsed')) throw new Error('doctor selftest failed: elapsed missing')
|
||||
if (!pretty.stdout.includes(`Log: ${path.join(temp, 'semantic-graph-task.log')}`)) throw new Error('doctor selftest failed: log path missing')
|
||||
const human = semanticTaskHumanLines({ status: 'running', running: true }, pretty).join('\n')
|
||||
if (!human.includes('Semantic task detail:')) throw new Error('doctor selftest failed: detail header missing')
|
||||
if (!human.includes('Task: running yes')) throw new Error('doctor selftest failed: pretty block missing from human output')
|
||||
const pendingHuman = semanticTaskHumanLines({ status: 'pending', running: false }, pretty).join('\n')
|
||||
if (!pendingHuman.includes('Semantic task detail:')) throw new Error('doctor selftest failed: pending detail missing')
|
||||
if (!needsSemanticDetail({ status: 'pending', running: false })) throw new Error('doctor selftest failed: pending should need detail')
|
||||
if (needsSemanticDetail({ status: 'succeeded', running: false })) throw new Error('doctor selftest failed: succeeded should not need detail')
|
||||
if (!noDataWarning({ name: 'complete', ok: false, stdout: JSON.stringify({ failures: ['last run state missing'] }) })) throw new Error('doctor selftest failed: complete no-data not warning')
|
||||
if (noDataWarning({ name: 'complete', ok: false, stdout: JSON.stringify({ failures: ['last run state missing', 'vault quality failed'] }) })) throw new Error('doctor selftest failed: complete disease hidden as no-data')
|
||||
const noOwnerLastRun = { name: 'last-run', ok: false, stdout: JSON.stringify({ last_run: null, failures: ['last-run.json missing'] }) }
|
||||
if (!noDataWarning(noOwnerLastRun, { ownerOps: false })) throw new Error('doctor selftest failed: last-run no-data not warning')
|
||||
if (noDataWarning(noOwnerLastRun, { ownerOps: true })) throw new Error('doctor selftest failed: owner last-run no-data hidden as warning')
|
||||
const tick = await semanticWatchTick({ MNEMAZINE_STATE: temp }, temp)
|
||||
if (tick.done) throw new Error('doctor selftest failed: running watch tick marked done')
|
||||
if (!tick.lines.join('\n').includes('Task: running yes')) throw new Error('doctor selftest failed: watch tick missing pretty output')
|
||||
await fs.writeFile(path.join(temp, 'semantic-graph-task.json'), JSON.stringify({
|
||||
status: 'succeeded',
|
||||
pid: process.pid,
|
||||
started_at: new Date(Date.now() - 65000).toISOString(),
|
||||
finished_at: new Date().toISOString(),
|
||||
vault: '/tmp/vault',
|
||||
strategy: 'swarm'
|
||||
}, null, 2), 'utf8')
|
||||
const doneTick = await semanticWatchTick({ MNEMAZINE_STATE: temp }, temp)
|
||||
if (!doneTick.done || !doneTick.ok) throw new Error('doctor selftest failed: finished watch tick not ok')
|
||||
await fs.rm(temp, { recursive: true, force: true })
|
||||
// Утверждение: критичная строка несёт команду починки (три кода бесполезны, если
|
||||
// красная строка не говорит, чем лечить).
|
||||
const line = failureLine('release-check', 'release-check failed')
|
||||
if (!line.includes('как починить')) throw new Error('doctor selftest failed: failure line carries no fix')
|
||||
if (!/npm run|npm start/.test(fixFor('release-check'))) throw new Error('doctor selftest failed: fix is not a runnable command')
|
||||
if (!/npm/.test(fixFor('unknown-check-name'))) throw new Error('doctor selftest failed: default fix missing')
|
||||
console.log(JSON.stringify({ ok: true }, null, 2))
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const lastRun = await readJson(path.join(STATE, 'last-run.json'))
|
||||
const vault = resolveVault({ env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
|
||||
@@ -89,7 +320,11 @@ async function main() {
|
||||
const commands = [
|
||||
['complete', 'npm', ['run', 'complete', '--', '--require-deep']],
|
||||
...(report && since ? [['human-layer', 'npm', ['run', 'human-layer:quality', '--', '--changed-since', since, '--report', path.relative(ROOT, report)]]] : []),
|
||||
['last-run', 'npm', ['run', 'last-run', '--', '--require-ok']],
|
||||
...(FULL_VAULT ? [
|
||||
['human-layer-full', 'npm', ['run', 'human-layer:quality', '--', '--vault', vault, '--changed-since', '1', '--notes-only', '--max-failures', '100']],
|
||||
['vault-final-audit', 'npm', ['run', 'audit:vault', '--', '--vault', vault, '--max-failures', '100']]
|
||||
] : []),
|
||||
['last-run', 'npm', ['run', 'last-run', '--', '--json', '--require-ok']],
|
||||
['graph-smoke', 'npm', ['run', 'graph:smoke']],
|
||||
['release-check', 'npm', ['run', 'release-check']]
|
||||
]
|
||||
@@ -98,20 +333,35 @@ async function main() {
|
||||
for (const [name, command, args] of commands) results.push(await run(name, command, args, env))
|
||||
const inbox = await activeInboxFiles(INBOX)
|
||||
const markers = await graphMarkers(vault)
|
||||
const semanticTask = await semanticTaskStatus()
|
||||
const semanticPretty = needsSemanticDetail(semanticTask) ? await semanticTaskPretty(env) : null
|
||||
const noDataWarnings = results.map(item => [item.name, noDataWarning(item)]).filter(([, warning]) => warning)
|
||||
const noDataByName = new Map(noDataWarnings)
|
||||
const markerWarnings = markers
|
||||
.filter(item => item.exists)
|
||||
.map(item => `semantic graph pending: ${item.file}${item.age_days !== null ? ` (${item.age_days.toFixed(2)} days)` : ''}; run npm run graph:semantic:monitor`)
|
||||
const failures = [
|
||||
...results.filter(item => !item.ok).map(item => `${item.name} failed`),
|
||||
...(inbox.length ? [`inbox not empty: ${inbox.length}`] : []),
|
||||
...markers.filter(item => item.exists).map(item => `graph marker exists: ${item.file}`)
|
||||
...results.filter(item => !item.ok && !noDataByName.has(item.name)).map(item => failureLine(item.name, `${item.name} failed`)),
|
||||
...(inbox.length ? [failureLine('inbox', `inbox not empty: ${inbox.length}`)] : []),
|
||||
...(STRICT_GRAPH ? markerWarnings : [])
|
||||
]
|
||||
const warnings = [
|
||||
...noDataWarnings.map(([, warning]) => warning),
|
||||
...(STRICT_GRAPH ? [] : markerWarnings)
|
||||
]
|
||||
|
||||
const output = {
|
||||
ok: failures.length === 0,
|
||||
failures,
|
||||
warnings,
|
||||
full_vault: FULL_VAULT,
|
||||
vault,
|
||||
inbox: inbox.length,
|
||||
report: report ? path.relative(ROOT, report) : null,
|
||||
graph_markers: markers,
|
||||
commands: results.map(item => ({ name: item.name, ok: item.ok, code: item.code }))
|
||||
semantic_graph_task: semanticTask,
|
||||
semantic_graph_pretty: semanticPretty?.ok ? semanticPretty.stdout : null,
|
||||
commands: results.map(item => ({ name: item.name, ok: item.ok, code: item.code, no_data: noDataByName.has(item.name) }))
|
||||
}
|
||||
|
||||
if (JSON_OUT) {
|
||||
@@ -119,25 +369,39 @@ async function main() {
|
||||
} else {
|
||||
console.log(output.ok ? 'Mnemazine doctor: ok' : 'Mnemazine doctor: failed')
|
||||
console.log(`Vault: ${vault}`)
|
||||
if (FULL_VAULT) console.log('Full vault audit: enabled')
|
||||
console.log(`Inbox: ${inbox.length}`)
|
||||
console.log(`Report: ${output.report || 'missing'}`)
|
||||
for (const item of results) console.log(`${item.ok ? 'ok' : 'fail'} ${item.name}`)
|
||||
for (const marker of markers) console.log(`${marker.exists ? 'fail' : 'ok'} marker ${marker.file}`)
|
||||
for (const item of results) console.log(`${item.ok ? 'ok' : noDataByName.has(item.name) ? 'warn' : 'fail'} ${item.name}${noDataByName.has(item.name) ? ' (no data)' : ''}`)
|
||||
for (const marker of markers) console.log(`${marker.exists ? 'warn' : 'ok'} marker ${marker.file}`)
|
||||
for (const line of semanticTaskHumanLines(semanticTask, semanticPretty)) console.log(line)
|
||||
if (warnings.length) {
|
||||
console.log('\nWarnings:')
|
||||
for (const warning of warnings) console.log(`- ${warning}`)
|
||||
}
|
||||
if (failures.length) {
|
||||
console.log('\nFailures:')
|
||||
for (const failure of failures) console.log(`- ${failure}`)
|
||||
const failed = results.find(item => !item.ok)
|
||||
const failed = results.find(item => !item.ok && !noDataByName.has(item.name))
|
||||
if (failed) {
|
||||
console.log(`\n${failed.name} output:`)
|
||||
console.log(tail(failed.stderr || failed.stdout))
|
||||
console.log(tail([failed.stderr, failed.stdout].filter(Boolean).join('\n'), 80))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (WATCH && output.ok && semanticTask.running) {
|
||||
if (JSON_OUT) console.error('doctor --watch is human-output only; printed one JSON snapshot and skipped watch')
|
||||
else if (!await watchSemanticTask(env)) process.exit(1)
|
||||
}
|
||||
|
||||
// Три кода вместо двух: провалы → 1; провалов нет, но есть предупреждения → 2; иначе 0.
|
||||
if (!output.ok) process.exit(1)
|
||||
if (warnings.length) process.exit(2)
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
const entrypoint = SELFTEST ? selftest : main
|
||||
entrypoint().catch(error => {
|
||||
console.error(error.message || error)
|
||||
process.exit(1)
|
||||
})
|
||||
|
||||
Executable
+407
@@ -0,0 +1,407 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
THEMIS_ROOT="${THEMIS_ROOT:-../themis}"
|
||||
OUT="$ROOT/.mnemazine/state/rebuild/femida-baseline.json"
|
||||
MD_OUT="$ROOT/.mnemazine/state/rebuild/femida-baseline.md"
|
||||
VERIFY=0
|
||||
|
||||
usage() {
|
||||
cat <<'USAGE'
|
||||
Usage:
|
||||
bash scripts/mnemazine-femida-baseline.sh [--out PATH] [--md PATH]
|
||||
bash scripts/mnemazine-femida-baseline.sh --verify [--out PATH]
|
||||
USAGE
|
||||
}
|
||||
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--out)
|
||||
OUT="${2:?--out needs path}"
|
||||
shift 2
|
||||
;;
|
||||
--md)
|
||||
MD_OUT="${2:?--md needs path}"
|
||||
shift 2
|
||||
;;
|
||||
--verify)
|
||||
VERIFY=1
|
||||
shift
|
||||
;;
|
||||
--help|-h)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
echo "unknown arg: $1" >&2
|
||||
usage >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ ! -d "$THEMIS_ROOT" ]; then
|
||||
echo "missing themis repo: $THEMIS_ROOT" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [ "$VERIFY" = "1" ] && [ ! -s "$OUT" ]; then
|
||||
echo "missing baseline: $OUT" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
owner_launchd_json() {
|
||||
local count plist mtime uid label print last_exit_code
|
||||
uid="$(id -u)"
|
||||
label="themis.morning-briefing"
|
||||
count="$(/bin/launchctl list 2>/dev/null | grep -c themis || true)"
|
||||
print="$(/bin/launchctl print "gui/$uid/$label" 2>/dev/null || true)"
|
||||
if [ "$count" = "0" ] && [ -n "$print" ]; then
|
||||
count=1
|
||||
fi
|
||||
last_exit_code="$(printf '%s\n' "$print" | awk -F'= ' '/last exit code = / {print $2; exit}')"
|
||||
plist="$HOME/Library/LaunchAgents/themis.morning-briefing.plist"
|
||||
if [ -e "$plist" ]; then
|
||||
mtime="$(/usr/bin/stat -f %m "$plist")"
|
||||
else
|
||||
mtime=""
|
||||
fi
|
||||
node -e 'const count=Number(process.argv[1]||0); const raw=process.argv[2]||""; const label=process.argv[3]||null; const last=process.argv[4]||""; process.stdout.write(JSON.stringify({count, plist_mtime: raw === "" ? null : Number(raw), label: count ? label : null, last_exit_code: last === "" ? null : Number(last)}));' "$count" "$mtime" "$label" "$last_exit_code"
|
||||
}
|
||||
|
||||
make_sandbox() {
|
||||
local sbx
|
||||
sbx="$(mktemp -d)"
|
||||
mkdir -p "$sbx/home" "$sbx/shim" "$sbx/themis"
|
||||
git -C "$THEMIS_ROOT" archive HEAD | tar -x -C "$sbx/themis"
|
||||
|
||||
for name in pip3 pip launchctl brew xcode-select; do
|
||||
cat > "$sbx/shim/$name" <<SHIM
|
||||
#!/usr/bin/env bash
|
||||
printf '%s %s\n' "\$(basename "\$0")" "\$*" >> "$sbx/trace.log"
|
||||
exit 0
|
||||
SHIM
|
||||
chmod +x "$sbx/shim/$name"
|
||||
done
|
||||
|
||||
cat > "$sbx/shim/swiftc" <<SHIM
|
||||
#!/usr/bin/env bash
|
||||
printf '%s %s\n' "\$(basename "\$0")" "\$*" >> "$sbx/trace.log"
|
||||
out=""
|
||||
prev=""
|
||||
for arg in "\$@"; do
|
||||
if [ "\$prev" = "-o" ]; then
|
||||
out="\$arg"
|
||||
break
|
||||
fi
|
||||
prev="\$arg"
|
||||
done
|
||||
if [ -n "\$out" ]; then
|
||||
mkdir -p "\$(dirname "\$out")"
|
||||
printf '#!/usr/bin/env sh\nexit 0\n' > "\$out"
|
||||
fi
|
||||
exit 0
|
||||
SHIM
|
||||
chmod +x "$sbx/shim/swiftc"
|
||||
|
||||
if [ -n "${MNEMAZINE_FEMIDA_BASELINE_DROP_SHIM:-}" ]; then
|
||||
case "$MNEMAZINE_FEMIDA_BASELINE_DROP_SHIM" in
|
||||
pip3|pip|launchctl|swiftc|brew|xcode-select)
|
||||
rm -f "$sbx/shim/$MNEMAZINE_FEMIDA_BASELINE_DROP_SHIM"
|
||||
;;
|
||||
*)
|
||||
echo "unknown shim for drop probe: $MNEMAZINE_FEMIDA_BASELINE_DROP_SHIM" >&2
|
||||
return 2
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
printf '%s\n' "$sbx"
|
||||
}
|
||||
|
||||
require_shims() {
|
||||
local sbx="$1" name resolved
|
||||
for name in pip3 pip launchctl swiftc brew xcode-select; do
|
||||
if [ ! -x "$sbx/shim/$name" ]; then
|
||||
echo "нет шима на $name" >&2
|
||||
return 1
|
||||
fi
|
||||
resolved="$(PATH="$sbx/shim:$PATH" command -v "$name" 2>/dev/null || true)"
|
||||
if [ "$resolved" != "$sbx/shim/$name" ]; then
|
||||
echo "нет шима на $name: PATH резолвит ${resolved:-ничего}" >&2
|
||||
return 1
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
write_stub_doctor() {
|
||||
local sbx="$1" rc="$2"
|
||||
cat > "$sbx/themis/scripts/setup_doctor.py" <<PY
|
||||
#!/usr/bin/env python3
|
||||
print("stub doctor rc=$rc")
|
||||
raise SystemExit($rc)
|
||||
PY
|
||||
chmod +x "$sbx/themis/scripts/setup_doctor.py"
|
||||
}
|
||||
|
||||
run_install() {
|
||||
local sbx="$1" output="$2"
|
||||
require_shims "$sbx"
|
||||
set +e
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" THEMIS_YES=1 bash install.sh
|
||||
) > "$output" 2>&1
|
||||
local rc=$?
|
||||
set -e
|
||||
printf '%s\n' "$rc"
|
||||
}
|
||||
|
||||
measure_once() {
|
||||
local owner_json sbx original_doctor help_rc silent_rc red_rc warn_rc doctor_rc selftest_rc
|
||||
local help_before warn_form warnings_without_fix linux_replacements install_lines themis_head themis_has_ci
|
||||
owner_json="$(owner_launchd_json)"
|
||||
sbx="$(make_sandbox)"
|
||||
cp "$sbx/themis/scripts/setup_doctor.py" "$sbx/original_setup_doctor.py"
|
||||
|
||||
require_shims "$sbx"
|
||||
set +e
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" bash install.sh --help
|
||||
) > "$sbx/help.txt" 2>&1
|
||||
help_rc=$?
|
||||
set -e
|
||||
help_before="$(awk 'index($0, "bash install.sh [") {print NR - 1; found=1; exit} END {if (!found) print "null"}' "$sbx/help.txt")"
|
||||
|
||||
require_shims "$sbx"
|
||||
set +e
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" bash install.sh </dev/null
|
||||
) > "$sbx/silent.txt" 2>&1
|
||||
silent_rc=$?
|
||||
set -e
|
||||
find "$sbx/home" -mindepth 1 -print | sed "s|^$sbx/home/||" | LC_ALL=C sort > "$sbx/home_paths.txt"
|
||||
|
||||
write_stub_doctor "$sbx" 1
|
||||
red_rc="$(run_install "$sbx" "$sbx/install_red.txt")"
|
||||
|
||||
write_stub_doctor "$sbx" 2
|
||||
warn_rc="$(run_install "$sbx" "$sbx/install_warn.txt")"
|
||||
if grep -q "УСТАНОВКА НЕ ЗАВЕРШЕНА" "$sbx/install_warn.txt"; then
|
||||
warn_form="УСТАНОВКА НЕ ЗАВЕРШЕНА"
|
||||
elif grep -q "Готово. Дальше:" "$sbx/install_warn.txt"; then
|
||||
warn_form="Готово. Дальше:"
|
||||
else
|
||||
warn_form="не найдено"
|
||||
fi
|
||||
|
||||
cp "$sbx/original_setup_doctor.py" "$sbx/themis/scripts/setup_doctor.py"
|
||||
set +e
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" python3 scripts/setup_doctor.py
|
||||
) > "$sbx/doctor.txt" 2>&1
|
||||
doctor_rc=$?
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" python3 scripts/setup_doctor.py --selftest
|
||||
) > "$sbx/selftest.txt" 2>&1
|
||||
selftest_rc=$?
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" python3 scripts/setup_doctor.py --json --offline
|
||||
) > "$sbx/doctor.json" 2>/dev/null
|
||||
(
|
||||
cd "$sbx/themis" || exit 99
|
||||
HOME="$sbx/home" PATH="$sbx/shim:$PATH" python3 scripts/setup_doctor.py --platform linux --offline --json
|
||||
) > "$sbx/linux.json" 2>/dev/null
|
||||
set -e
|
||||
|
||||
warnings_without_fix="$(node - "$sbx/doctor.json" <<'NODE'
|
||||
const fs = require('fs');
|
||||
const p = process.argv[2];
|
||||
const rep = JSON.parse(fs.readFileSync(p, 'utf8'));
|
||||
const checks = rep['проверки'] || [];
|
||||
const n = checks.filter(c => c['статус'] !== 'ок' && !String(c['как починить'] || '').trim()).length;
|
||||
process.stdout.write(String(n));
|
||||
NODE
|
||||
)"
|
||||
linux_replacements="$(node - "$sbx/linux.json" <<'NODE'
|
||||
const fs = require('fs');
|
||||
const rep = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
||||
const notes = rep['платформенные особенности'] || [];
|
||||
const text = notes.join('\n').toLowerCase();
|
||||
const ok = {
|
||||
apple_vision: text.includes('apple vision') && text.includes('markitdown'),
|
||||
scheduler: text.includes('systemd'),
|
||||
cyrillic_paths: text.includes('utf-8')
|
||||
};
|
||||
process.stdout.write(JSON.stringify(ok));
|
||||
NODE
|
||||
)"
|
||||
|
||||
install_lines="$(wc -l < "$sbx/themis/install.sh" | tr -d ' ')"
|
||||
themis_head="$(git -C "$THEMIS_ROOT" rev-parse --short HEAD)"
|
||||
if [ -d "$sbx/themis/.github" ]; then
|
||||
themis_has_ci=true
|
||||
else
|
||||
themis_has_ci=false
|
||||
fi
|
||||
|
||||
node - "$sbx" "$owner_json" "$themis_head" "$themis_has_ci" "$install_lines" \
|
||||
"$help_rc" "$help_before" "$silent_rc" "$red_rc" "$warn_rc" "$doctor_rc" "$selftest_rc" \
|
||||
"$warn_form" "$warnings_without_fix" "$linux_replacements" <<'NODE'
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const [
|
||||
sbx, ownerRaw, themisHead, themisHasCiRaw, installLinesRaw, helpRcRaw,
|
||||
helpBeforeRaw, silentRcRaw, redRcRaw, warnRcRaw, doctorRcRaw, selfRcRaw,
|
||||
warnForm, warningsWithoutFixRaw, linuxReplacementsRaw
|
||||
] = process.argv.slice(2);
|
||||
const readLines = p => fs.existsSync(p)
|
||||
? fs.readFileSync(p, 'utf8').split(/\r?\n/).filter(Boolean)
|
||||
: [];
|
||||
const lastNonEmpty = p => {
|
||||
const lines = readLines(p);
|
||||
return lines.length ? lines[lines.length - 1] : '';
|
||||
};
|
||||
const installLines = readLines(path.join(sbx, 'install_warn.txt')).concat(readLines(path.join(sbx, 'install_red.txt')));
|
||||
const steps = [];
|
||||
for (const line of installLines) {
|
||||
const m = line.match(/^\[(.+?)\]/);
|
||||
if (m) {
|
||||
const step = `[${m[1]}]`;
|
||||
if (!steps.includes(step)) steps.push(step);
|
||||
}
|
||||
}
|
||||
const trace = readLines(path.join(sbx, 'trace.log')).map(line => line.split(sbx).join('<SBX>'));
|
||||
const helpBefore = helpBeforeRaw === 'null' ? null : Number(helpBeforeRaw);
|
||||
const obj = {
|
||||
taken_at: new Date().toISOString(),
|
||||
themis_head: themisHead,
|
||||
themis_has_ci: themisHasCiRaw === 'true',
|
||||
install_lines: Number(installLinesRaw),
|
||||
help_rc: Number(helpRcRaw),
|
||||
help_lines_before_usage: helpBefore,
|
||||
silent_rc: Number(silentRcRaw),
|
||||
home_paths_created_on_silence: readLines(path.join(sbx, 'home_paths.txt')),
|
||||
install_rc_when_doctor_red: Number(redRcRaw),
|
||||
install_rc_when_doctor_warn: Number(warnRcRaw),
|
||||
doctor_rc: Number(doctorRcRaw),
|
||||
doctor_selftest_rc: Number(selfRcRaw),
|
||||
steps_seen: steps,
|
||||
shim_calls: trace,
|
||||
warnings_without_fix: Number(warningsWithoutFixRaw),
|
||||
owner_launchd_before: JSON.parse(ownerRaw)
|
||||
};
|
||||
obj._observations = {
|
||||
doctor_red_last_line: lastNonEmpty(path.join(sbx, 'install_red.txt')),
|
||||
doctor_warn_result_phrase: warnForm,
|
||||
linux_replacements_named: JSON.parse(linuxReplacementsRaw)
|
||||
};
|
||||
process.stdout.write(JSON.stringify(obj, null, 2) + '\n');
|
||||
NODE
|
||||
}
|
||||
|
||||
write_markdown() {
|
||||
local path="$1"
|
||||
mkdir -p "$(dirname "$path")"
|
||||
cat > "$path" <<'MD'
|
||||
НАСЛЕДУЕМ:
|
||||
- ${THEMIS_ROOT}/install.sh:300-354 — смета до первого действия.
|
||||
- ${THEMIS_ROOT}/install.sh:356-385 — гейт согласия читает `/dev/tty`, а текст отказа называет обход `THEMIS_YES=1 bash install.sh`.
|
||||
- ${THEMIS_ROOT}/install.sh:401 — нумерация шага со знаменателем `[1/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:429 — нумерация шага со знаменателем `[2/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:451 — нумерация шага со знаменателем `[3/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:462 — нумерация шага со знаменателем `[4/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:468 — нумерация шага со знаменателем `[5/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:474 — нумерация шага со знаменателем `[6/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:488 — промежуточный шаг `[6.5]` явно назван.
|
||||
- ${THEMIS_ROOT}/install.sh:498 — промежуточный шаг `[6.6]` явно назван.
|
||||
- ${THEMIS_ROOT}/install.sh:521 — финальная проверка `[7/7]`.
|
||||
- ${THEMIS_ROOT}/install.sh:445 — предупреждение даёт копируемую команду `xcode-select --install` / `swiftc ...`.
|
||||
- ${THEMIS_ROOT}/install.sh:455 — предупреждение даёт копируемую команду `brew install ffmpeg`.
|
||||
- ${THEMIS_ROOT}/install.sh:507 — предупреждение даёт копируемую команду `launchctl load ...`.
|
||||
- ${THEMIS_ROOT}/install.sh:540 — доктор вызывается последним проверочным шагом.
|
||||
- ${THEMIS_ROOT}/scripts/setup_doctor.py:30-31 — контракт трёх кодов возврата.
|
||||
- ${THEMIS_ROOT}/scripts/setup_doctor.py:486 — selftest доктора есть отдельным режимом.
|
||||
- ${THEMIS_ROOT}/scripts/setup_doctor.py:446-450 — чужая платформа подставляется флагом `--platform`.
|
||||
- ${THEMIS_ROOT}/scripts/update.sh:29-30 — обновление перечисляет только системные пути, `cases/` и `knowledge/` не трогает.
|
||||
|
||||
НЕ НАСЛЕДУЕМ:
|
||||
- ${THEMIS_ROOT}/install.sh:554 — нет `exit` кодом доктора; последняя команда `echo`, поэтому красный доктор не становится кодом установщика.
|
||||
- ${THEMIS_ROOT}/install.sh:544 — код 2 доктора трактуется как «Готово», потому что сравнение есть только со строкой `1`.
|
||||
- ${THEMIS_ROOT}/install.sh:283-292 — `--help` разбирается после длинной прозы.
|
||||
- ${THEMIS_ROOT}/install.sh:13-276 — приветственный блок печатается до `--help`.
|
||||
- ${THEMIS_ROOT}/install.sh:402-406 — `pip3` ставит зависимости мимо venv.
|
||||
- ${THEMIS_ROOT}/install.sh:3 — есть только `set -e`, нет `set -u` и `pipefail`.
|
||||
- ${THEMIS_ROOT}/scripts/pd_guard.py:581-592 — git-хуки перезаписываются без бэкапа.
|
||||
- ${THEMIS_ROOT}/install.sh:8-11 — RU/EN выбирается по локали, но паритет текстов ничем не проверяется.
|
||||
- ${THEMIS_ROOT}/scripts/setup_doctor.py:474 — число проверок печатается из фактического списка, но заявленное «118 проверок» нигде не считается и отдельным инвариантом не держится.
|
||||
- ${THEMIS_ROOT}/install.sh:540 — приёмка числа проверок доктора не подключена к установке.
|
||||
- ${THEMIS_ROOT}/scripts/pd_guard.py:627 — приёмка числа проверок доктора не подключена к git-хукам.
|
||||
MD
|
||||
}
|
||||
|
||||
compare_json() {
|
||||
local expected="$1" actual="$2"
|
||||
node - "$expected" "$actual" <<'NODE'
|
||||
const fs = require('fs');
|
||||
const [aPath, bPath] = process.argv.slice(2);
|
||||
const a = JSON.parse(fs.readFileSync(aPath, 'utf8'));
|
||||
const b = JSON.parse(fs.readFileSync(bPath, 'utf8'));
|
||||
const mandatory = [
|
||||
'taken_at',
|
||||
'themis_head',
|
||||
'themis_has_ci',
|
||||
'install_lines',
|
||||
'help_rc',
|
||||
'help_lines_before_usage',
|
||||
'silent_rc',
|
||||
'home_paths_created_on_silence',
|
||||
'install_rc_when_doctor_red',
|
||||
'install_rc_when_doctor_warn',
|
||||
'doctor_rc',
|
||||
'doctor_selftest_rc',
|
||||
'steps_seen',
|
||||
'shim_calls',
|
||||
'warnings_without_fix',
|
||||
'owner_launchd_before'
|
||||
];
|
||||
const diffs = [];
|
||||
for (const key of mandatory) {
|
||||
if (!(key in a)) diffs.push(`missing baseline key: ${key}`);
|
||||
if (!(key in b)) diffs.push(`missing actual key: ${key}`);
|
||||
}
|
||||
if (a.themis_has_ci !== false) {
|
||||
diffs.push(`themis_has_ci must be false, got ${JSON.stringify(a.themis_has_ci)}`);
|
||||
}
|
||||
for (const key of Object.keys(a)) {
|
||||
if (key === 'taken_at') continue;
|
||||
const av = JSON.stringify(a[key]);
|
||||
const bv = JSON.stringify(b[key]);
|
||||
if (av !== bv) diffs.push(`${key}: expected ${av}, got ${bv}`);
|
||||
}
|
||||
if (diffs.length) {
|
||||
console.error(diffs.join('\n'));
|
||||
process.exit(1);
|
||||
}
|
||||
NODE
|
||||
}
|
||||
|
||||
if [ "$VERIFY" = "1" ]; then
|
||||
tmp="$(mktemp)"
|
||||
measure_once > "$tmp"
|
||||
compare_json "$OUT" "$tmp"
|
||||
echo "femida baseline verify ok"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
measure_once > "$OUT"
|
||||
write_markdown "$MD_OUT"
|
||||
echo "wrote $OUT"
|
||||
echo "wrote $MD_OUT"
|
||||
@@ -3,6 +3,7 @@ import { promises as fs } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { SPEC_TYPES } from './mnemazine-note-spec.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
@@ -100,6 +101,20 @@ function latinCount(text) {
|
||||
return (String(text || '').match(/[A-Za-z]/g) || []).length
|
||||
}
|
||||
|
||||
function languageLayerText(text) {
|
||||
return String(text || '')
|
||||
.replace(/^---\s*\n[\s\S]*?\n---\s*\n?/, '\n')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`[^`]*`/g, ' ')
|
||||
.replace(/!\[[^\]]*\]\([^)]+\)/g, ' ')
|
||||
.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
|
||||
.replace(/\[\[[^\]|]+\|([^\]]+)\]\]/g, '$1')
|
||||
.replace(/\[\[[^\]]+\]\]/g, ' ')
|
||||
.replace(/https?:\/\/\S+/g, ' ')
|
||||
.replace(/\b(?:source_ref|source_hash|cluster_id|processor_model|verification_status|local-media|processed_notes):\S*/gi, ' ')
|
||||
.replace(/\b[a-f0-9]{16,}\b/gi, ' ')
|
||||
}
|
||||
|
||||
const rawMarkers = [
|
||||
['english-section', /^##\s+(What This Is|Why It Matters|How To Use It|Source|Verification|Related Notes|Reuse)\b/gm],
|
||||
['github-metadata-en', /\bGitHub metadata:/g],
|
||||
@@ -131,8 +146,10 @@ function markerFailures(text) {
|
||||
function noteFailures(text) {
|
||||
const failures = markerFailures(text)
|
||||
const type = text.match(/^type:\s*"?([^"\n]+)"?/m)?.[1]?.trim() || ''
|
||||
// Состав типов знания — из единого модуля П05, а не литерала: переименование типа
|
||||
// в спеке не должно молча ослеплять этот гейт (план П16 шаг 2).
|
||||
const isDigest = type === 'knowledge-digest'
|
||||
const isKnowledge = type === 'knowledge-note' || /^#\s+/.test(text)
|
||||
const isKnowledge = SPEC_TYPES.has(type) || /^#\s+/.test(text)
|
||||
if (!isDigest && !isKnowledge) return failures
|
||||
|
||||
const required = isDigest
|
||||
@@ -145,8 +162,11 @@ function noteFailures(text) {
|
||||
failures.push({ rule: 'missing-use-section', details: ['Как использовать / Что добавила Mnemazine / Зачем это нужно'] })
|
||||
}
|
||||
|
||||
if (cyrillicCount(text) < 120) failures.push({ rule: 'weak-russian-layer', details: `cyrillic_chars=${cyrillicCount(text)}` })
|
||||
if (latinCount(text) > cyrillicCount(text) * 2.2) failures.push({ rule: 'english-dominant-layer', details: `latin=${latinCount(text)}, cyrillic=${cyrillicCount(text)}` })
|
||||
const languageText = languageLayerText(text)
|
||||
const cyrillic = cyrillicCount(languageText)
|
||||
const latin = latinCount(languageText)
|
||||
if (cyrillic < 120) failures.push({ rule: 'weak-russian-layer', details: `cyrillic_chars=${cyrillic}` })
|
||||
if (latin > cyrillic * 2.2) failures.push({ rule: 'english-dominant-layer', details: `latin=${latin}, cyrillic=${cyrillic}` })
|
||||
return failures
|
||||
}
|
||||
|
||||
@@ -174,11 +194,21 @@ function reportFailures(text) {
|
||||
return failures
|
||||
}
|
||||
|
||||
// Служебная секция vault — сервис, не знание: человеческий слой её не судит (П22).
|
||||
// «99 Система» — живой корпус владельца, «00 System» — публичный близнец, куда
|
||||
// install.sh кладёт «Mnemazine Protocol.md». Ровно то же исключение, что в
|
||||
// vault-quality-gate.isServicePath.
|
||||
function isVaultServiceNote(file) {
|
||||
const rel = path.relative(VAULT, file).replace(/\\/g, '/')
|
||||
return /^99 Система\//.test(rel) || /^00 System\//.test(rel)
|
||||
}
|
||||
|
||||
async function listNotes() {
|
||||
if (!existsSync(VAULT)) return []
|
||||
const files = await walk(VAULT, file => file.endsWith('.md'))
|
||||
const out = []
|
||||
for (const file of files) {
|
||||
if (isVaultServiceNote(file)) continue
|
||||
const stat = await fs.stat(file)
|
||||
if (CHANGED_SINCE_MS && stat.mtimeMs >= CHANGED_SINCE_MS) {
|
||||
out.push(file)
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env node
|
||||
// План П13 шаг 8 — кампания очеловечивания корпуса партиями по 50 нот.
|
||||
// Каждая партия: git-коммит vault ДО, рерайт нот, гейт сохранности на КАЖДОЙ ноте,
|
||||
// git-коммит ПОСЛЕ. Не прошедший гейт вариант отбрасывается — в vault остаётся
|
||||
// исходник (ни одна нота не удаляется). Первая партия — худшие по cleanliness из
|
||||
// базового замера (--worst-first). СТОП: три партии подряд без роста медианы → разбор.
|
||||
//
|
||||
// node scripts/mnemazine-humanize-campaign.mjs --limit 50 --worst-first # dry-run: план
|
||||
// node scripts/mnemazine-humanize-campaign.mjs --limit 50 --apply # рерайт + коммиты
|
||||
//
|
||||
// БЕЗ --apply НИЧЕГО не пишет и не коммитит. --apply требует доступного LLM и
|
||||
// точки отката П15 (live vault уже под контролем версий).
|
||||
import { promises as fs, existsSync, readFileSync } from 'node:fs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { preservationCheck } from './mnemazine-humanize-gate.mjs'
|
||||
import { activeProvider, llmAvailable, llmText, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(HERE, '..')
|
||||
const argv = process.argv.slice(2)
|
||||
function arg(name, fb = '') {
|
||||
const i = argv.indexOf(`--${name}`)
|
||||
if (i === -1) return fb
|
||||
const v = argv[i + 1]
|
||||
return (v && !v.startsWith('--')) ? v : fb
|
||||
}
|
||||
const has = name => argv.includes(`--${name}`)
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const BASELINE = arg('baseline', '.mnemazine/state/humanize-baseline.json')
|
||||
const LIMIT = Number(arg('limit', '50'))
|
||||
const APPLY = has('apply')
|
||||
const REPORT_DIR = arg('report-dir', 'reports/campaigns')
|
||||
|
||||
// Рерайт одной ноты: только проза блоков 1-7, неприкасаемые зоны — дословно.
|
||||
// Гейт всё равно проверит; промпт лишь повышает шанс пройти.
|
||||
function humanizePrompt(text) {
|
||||
return `Ты очеловечиваешь заметку знаний на РУССКОМ. Верни ВЕСЬ текст заметки целиком, без преамбул и без обёртки в тройные кавычки.
|
||||
|
||||
Правь ТОЛЬКО прозу тела. НЕ трогай (переноси дословно, байт в байт):
|
||||
- YAML-frontmatter между --- ... ---;
|
||||
- блоки кода в тройных кавычках и инлайн-код в одиночных обратных кавычках;
|
||||
- раздел «## Достоверность» целиком;
|
||||
- таблицы и цитаты (строки, начинающиеся с > );
|
||||
- все числа, ссылки http(s)://, пути, [[wikilinks]], версии, даты, латинские названия инструментов.
|
||||
|
||||
Сделай прозу живой и ясной: убери канцелярит, номинализации, воду. Никаких длинных тире «—» (используй дефис или запятую), никакого «является», «в современном мире», «комплексный подход». Не добавляй фактов сверх заметки.
|
||||
|
||||
Заметка:
|
||||
${fenceUntrusted('НОТА', text)}`
|
||||
}
|
||||
|
||||
async function humanizeNote(text) {
|
||||
const out = await llmText(humanizePrompt(text), { provider: activeProvider() })
|
||||
// Снять возможную обёртку в тройные кавычки.
|
||||
return out.replace(/^```(?:markdown|md)?\n([\s\S]*)\n```\s*$/m, '$1').trim() + '\n'
|
||||
}
|
||||
|
||||
function git(args) { return spawnSync('git', ['-C', VAULT, ...args], { encoding: 'utf8' }) }
|
||||
|
||||
function loadBatch() {
|
||||
if (!existsSync(BASELINE)) throw new Error(`нет базового замера: ${BASELINE} (сними --baseline у гейта)`)
|
||||
const b = JSON.parse(readFileSync(BASELINE, 'utf8'))
|
||||
const worst = Array.isArray(b.worst) ? b.worst : []
|
||||
return worst.slice(0, LIMIT) // worst уже отсортирован по возрастанию score
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const batch = loadBatch()
|
||||
if (!batch.length) { console.error('пустая очередь: worst[] в базовом замере пуст'); return 1 }
|
||||
|
||||
if (!APPLY) {
|
||||
console.log(JSON.stringify({
|
||||
mode: 'dry-run', apply: false, vault: VAULT, batch_size: batch.length,
|
||||
worst_score_range: [batch[0]?.score, batch[batch.length - 1]?.score],
|
||||
note: 'без --apply ничего не пишется и не коммитится. Запуск кампании — крупная LLM-мутация vault, только по явному решению владельца и после точки отката П15.',
|
||||
first5: batch.slice(0, 5).map(x => ({ score: x.score, note: path.basename(x.path) }))
|
||||
}, null, 2))
|
||||
return 0
|
||||
}
|
||||
|
||||
// --apply: реальная мутация корпуса.
|
||||
if (!llmAvailable()) { console.error('нет доступного LLM-провайдера — рерайт невозможен'); return 2 }
|
||||
if (git(['rev-parse', '--is-inside-work-tree']).status !== 0) { console.error(`${VAULT} не под git — точки отката нет`); return 2 }
|
||||
|
||||
const stamp = arg('now', new Date().toISOString().slice(0, 19).replace(/[:T]/g, '-'))
|
||||
git(['add', '-A']); git(['commit', '-m', `humanize-campaign П13: до партии (${stamp})`])
|
||||
|
||||
const diffs = []; let rewritten = 0, kept = 0
|
||||
for (const item of batch) {
|
||||
const file = item.path
|
||||
if (!existsSync(file)) { kept += 1; continue }
|
||||
const before = await fs.readFile(file, 'utf8')
|
||||
let cand
|
||||
try { cand = await humanizeNote(before) } catch (err) { diffs.push({ note: path.basename(file), rejected: `llm: ${err.message}` }); kept += 1; continue }
|
||||
const g = preservationCheck(before, cand, { clean: true })
|
||||
if (g.code === 0) {
|
||||
await fs.writeFile(file, cand, 'utf8')
|
||||
rewritten += 1
|
||||
// приём 24: машинно снимаемый след правки — проза до/после в отчёт партии.
|
||||
diffs.push({ note: path.basename(file), score_before: item.score, score_after: g.cleanliness?.score, applied: true })
|
||||
} else {
|
||||
kept += 1
|
||||
diffs.push({ note: path.basename(file), rejected: g.dirty ? `грязь score=${g.cleanliness?.score}` : `потеря ${g.lost.length} инвариантов`, lost: g.lost.slice(0, 5) })
|
||||
}
|
||||
}
|
||||
|
||||
git(['add', '-A']); git(['commit', '-m', `humanize-campaign П13: после партии (${stamp}), переписано ${rewritten}, оставлено ${kept}`])
|
||||
|
||||
await fs.mkdir(path.resolve(REPORT_DIR), { recursive: true })
|
||||
const report = path.join(REPORT_DIR, `humanize-campaign-${stamp}.md`)
|
||||
await fs.writeFile(report, [
|
||||
`# Партия очеловечивания П13 — ${stamp}`,
|
||||
'', `Vault: \`${VAULT}\` · нот в партии: ${batch.length} · переписано: **${rewritten}** · оставлено исходником: **${kept}**.`,
|
||||
'', 'Гейт сохранности отверг варианты с потерей фактов — в vault остался исходник.',
|
||||
'', '## След правки (приём 24)', '', '```json', JSON.stringify(diffs, null, 2), '```'
|
||||
].join('\n') + '\n', 'utf8')
|
||||
|
||||
console.log(JSON.stringify({ mode: 'apply', batch: batch.length, rewritten, kept, report }, null, 2))
|
||||
console.error('НАПОМИНАНИЕ (стоп-критерий шаг 8): пересними базовый замер; если после трёх партий медиана не выросла — останови кампанию на разбор.')
|
||||
return 0
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
process.exit(await main().catch(err => { console.error(err.stack || err.message); return 2 }))
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
#!/usr/bin/env node
|
||||
// План П13 — гейт сохранности очеловечивания. Держит два условия кодом:
|
||||
// читаемость (сканер humanizer-ru) и сохранность фактов (инварианты «до» ⊆ «после»).
|
||||
//
|
||||
// Режимы:
|
||||
// --before A --after B [--json] [--no-clean] [--porog N] сверка одной пары
|
||||
// --selftest фикстуры (красный кролик)
|
||||
// --baseline --vault V --out O --report R распределение чистоты по корпусу
|
||||
// --sweep --vault V --changed-since ISO [--porog N] читаемость изменённых нот (розетка run.mjs)
|
||||
//
|
||||
// Коды: 0 — всё на месте; 1 — потерян инвариант / hard ban / грязь; 2 — ошибка входа
|
||||
// (нет файла, битый frontmatter, сканер не запустился). scan.py при hard bans выходит с 1,
|
||||
// но печатает валидный JSON — это НЕ ошибка входа, это грязный текст (наш код 1).
|
||||
import { promises as fs, existsSync } from 'node:fs'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { SPEC_BODY_HEADINGS, SPEC_UNTOUCHABLE_HEADINGS } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = path.resolve(HERE, '..')
|
||||
const SCANNER = path.join(ROOT, 'skills/humanizer-ru/scripts/scan.py')
|
||||
const CORPUS_SCANNER = path.join(ROOT, 'skills/humanizer-ru/scripts/scan_corpus.py')
|
||||
const VENV_PY = path.join(ROOT, '.venv/bin/python')
|
||||
const PY = existsSync(VENV_PY) ? VENV_PY : 'python3'
|
||||
// ponytail: порог — граница «рерайт» из scan.py:54 (<60 текст требует переписывания).
|
||||
const POROG_DEFAULT = Number(process.env.MNEMAZINE_HUMANIZE_POROG || 60)
|
||||
const EM_DASH_BAN = 'Длинное тире' // сквозной в корпусе (95% hard bans) — не слоп
|
||||
|
||||
class InputError extends Error {} // → exit 2
|
||||
|
||||
// ── сканер читаемости ────────────────────────────────────────────────────────
|
||||
// Возвращает {score, band, hard_ban_count}. Отличает «сканер сломан» (InputError→2)
|
||||
// от «текст грязный» (валидный JSON, hard_ban_count>0 → зовущий решает).
|
||||
function runScanner(prose) {
|
||||
if (!existsSync(SCANNER)) throw new InputError(`сканер не найден: ${SCANNER}`)
|
||||
const r = spawnSync(PY, [SCANNER, '-', '--json'], { input: prose, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
|
||||
if (r.error) throw new InputError(`сканер не запустился: ${r.error.message}`)
|
||||
if (r.stderr && /Traceback|ModuleNotFoundError/.test(r.stderr)) {
|
||||
throw new InputError(`сканер упал: ${r.stderr.trim().split('\n').pop()}`)
|
||||
}
|
||||
let json
|
||||
try { json = JSON.parse(r.stdout) } catch {
|
||||
throw new InputError(`сканер вернул не-JSON на stdout (${(r.stdout || '').slice(0, 80)})`)
|
||||
}
|
||||
if (!json.score || typeof json.score.score !== 'number') throw new InputError('в выдаче сканера нет score')
|
||||
const hardBans = Array.isArray(json.hard_bans) ? json.hard_bans : []
|
||||
// Длинное тире сквозное в корпусе (даты/заголовки) — считаем отдельно от слопа.
|
||||
const slop = hardBans.filter(([name]) => name !== EM_DASH_BAN).reduce((s, [, n]) => s + (n | 0), 0)
|
||||
return { score: json.score.score, band: json.score.band, hard_ban_count: json.hard_ban_count | 0, hard_bans: hardBans, slop_ban_count: slop }
|
||||
}
|
||||
|
||||
// ── неприкасаемые зоны (сверяются побайтово) ─────────────────────────────────
|
||||
function frontmatter(text) {
|
||||
if (!text.startsWith('---\n') && !text.startsWith('---\r\n')) return null
|
||||
const m = text.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/)
|
||||
if (!m) throw new InputError('битый frontmatter: нет закрывающего ---')
|
||||
return m[0]
|
||||
}
|
||||
function fences(text) { return text.match(/```[\s\S]*?```/g) || [] }
|
||||
function stripFences(text) { return text.replace(/```[\s\S]*?```/g, ' ') }
|
||||
function inlineCode(noFences) { return noFences.match(/`[^`\n]+`/g) || [] }
|
||||
|
||||
function sectionBlock(text, re) {
|
||||
const rx = new RegExp(re.source, 'm')
|
||||
const m = rx.exec(text)
|
||||
if (!m) return null
|
||||
const from = m.index
|
||||
const after = text.slice(from + m[0].length)
|
||||
const nx = after.search(/\n##\s+/)
|
||||
return nx === -1 ? text.slice(from) : text.slice(from, from + m[0].length + nx)
|
||||
}
|
||||
function untouchableSections(text) {
|
||||
return SPEC_UNTOUCHABLE_HEADINGS.map(h => sectionBlock(text, h.re)).filter(Boolean)
|
||||
}
|
||||
function lineBlocks(text, test) {
|
||||
const out = []; let cur = []
|
||||
for (const ln of text.split('\n')) {
|
||||
if (test(ln)) cur.push(ln)
|
||||
else { if (cur.length) out.push(cur.join('\n')); cur = [] }
|
||||
}
|
||||
if (cur.length) out.push(cur.join('\n'))
|
||||
return out
|
||||
}
|
||||
const numberTables = text => lineBlocks(text, ln => /^\s*\|/.test(ln)).filter(b => /\d/.test(b))
|
||||
const quoteBlocks = text => lineBlocks(text, ln => /^\s*>/.test(ln))
|
||||
|
||||
// ── токен-инварианты ─────────────────────────────────────────────────────────
|
||||
const RX = {
|
||||
url: /https?:\/\/[^\s)>\]"'`]+/g,
|
||||
wikilink: /\[\[[^\]]+\]\]/g,
|
||||
path: /(?:~|\.{0,2})\/[^\s`)>\]"']+|[\w.\-/]+\.(?:mjs|py|json|md|sh|ts|js|txt|yml|yaml)\b/g,
|
||||
number: /\d+(?:[.,]\d+)?/g,
|
||||
version: /\bv?\d+\.\d+(?:\.\d+)?\b/g,
|
||||
isoDate: /\b\d{4}-\d{2}-\d{2}\b/g,
|
||||
latin: /[A-Za-z][A-Za-z0-9_-]{2,}/g
|
||||
}
|
||||
const matchAll = (text, re) => text.match(re) || []
|
||||
function countMap(list) { const m = new Map(); for (const v of list) m.set(v, (m.get(v) || 0) + 1); return m }
|
||||
|
||||
// множества-инварианты: byte-blocks (verbatim) + токены (мультимножество/множество) + заголовки.
|
||||
function collectInvariants(before) {
|
||||
const fm = frontmatter(before)
|
||||
const nf = stripFences(before)
|
||||
const byteBlocks = [
|
||||
...(fm ? [fm] : []),
|
||||
...fences(before),
|
||||
...inlineCode(nf),
|
||||
...untouchableSections(before),
|
||||
...numberTables(before),
|
||||
...quoteBlocks(before)
|
||||
]
|
||||
const headings = SPEC_BODY_HEADINGS.filter(h => new RegExp(h.re.source, 'm').test(before))
|
||||
return {
|
||||
byteBlocks,
|
||||
headings,
|
||||
tokens: {
|
||||
url: countMap(matchAll(before, RX.url)),
|
||||
wikilink: countMap(matchAll(before, RX.wikilink)),
|
||||
path: countMap(matchAll(before, RX.path)),
|
||||
number: countMap(matchAll(before, RX.number)),
|
||||
version: countMap(matchAll(before, RX.version)),
|
||||
isoDate: countMap(matchAll(before, RX.isoDate)),
|
||||
latin: new Set(matchAll(before, RX.latin))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── MQM (приём 40): вердикт не бинарный — какая рубрика провалилась ───────────
|
||||
function mqm(lost, cleanliness) {
|
||||
const cat = k => lost.filter(l => l.kind === k)
|
||||
return {
|
||||
accuracy: cat('number').length + cat('url').length + cat('path').length + cat('wikilink').length +
|
||||
cat('version').length + cat('isoDate').length + cat('byte').length === 0,
|
||||
language: cleanliness ? cleanliness.hard_ban_count === 0 : null,
|
||||
style: cleanliness ? cleanliness.score >= POROG_DEFAULT : null,
|
||||
terminology: cat('latin').length + cat('heading').length === 0
|
||||
}
|
||||
}
|
||||
|
||||
// ── ядро: сверка одной пары ───────────────────────────────────────────────────
|
||||
// clean=false — только сохранность фактов (охрана дайджеста: он лишь дописывает Справку).
|
||||
export function preservationCheck(before, after, { clean = true, porog = POROG_DEFAULT } = {}) {
|
||||
const inv = collectInvariants(before) // бросит InputError на битом frontmatter
|
||||
const lost = []
|
||||
|
||||
for (const block of inv.byteBlocks) {
|
||||
if (!after.includes(block)) lost.push({ kind: 'byte', sample: block.slice(0, 60) })
|
||||
}
|
||||
for (const [kind, re] of [['url', RX.url], ['wikilink', RX.wikilink], ['path', RX.path], ['number', RX.number], ['version', RX.version], ['isoDate', RX.isoDate]]) {
|
||||
const afterCount = countMap(matchAll(after, re))
|
||||
for (const [val, n] of inv.tokens[kind]) {
|
||||
if ((afterCount.get(val) || 0) < n) lost.push({ kind, sample: val })
|
||||
}
|
||||
}
|
||||
const afterLatin = new Set(matchAll(after, RX.latin))
|
||||
for (const tok of inv.tokens.latin) if (!afterLatin.has(tok)) lost.push({ kind: 'latin', sample: tok })
|
||||
for (const h of inv.headings) {
|
||||
if (!new RegExp(h.re.source, 'm').test(after)) lost.push({ kind: 'heading', sample: h.title })
|
||||
}
|
||||
|
||||
let cleanliness = null
|
||||
if (clean) {
|
||||
let prose = after
|
||||
const fm = frontmatter(after)
|
||||
if (fm) prose = prose.slice(fm.length)
|
||||
prose = stripFences(prose).replace(/`[^`\n]+`/g, ' ')
|
||||
for (const s of untouchableSections(after)) prose = prose.replace(s, ' ')
|
||||
cleanliness = runScanner(prose) // InputError → 2 у зовущего
|
||||
}
|
||||
|
||||
const dirty = clean && cleanliness && (cleanliness.hard_ban_count > 0 || cleanliness.score < porog)
|
||||
const code = (lost.length || dirty) ? 1 : 0
|
||||
return { code, lost, cleanliness, dirty: !!dirty, mqm: mqm(lost, cleanliness) }
|
||||
}
|
||||
|
||||
// ── режимы CLI ────────────────────────────────────────────────────────────────
|
||||
function arg(name, fb = '') {
|
||||
const i = process.argv.indexOf(`--${name}`)
|
||||
if (i === -1) return fb
|
||||
const v = process.argv[i + 1]
|
||||
return (v && !v.startsWith('--')) ? v : fb
|
||||
}
|
||||
const has = name => process.argv.includes(`--${name}`)
|
||||
|
||||
async function readNote(file) {
|
||||
if (!existsSync(file)) throw new InputError(`нет файла: ${file}`)
|
||||
return fs.readFile(file, 'utf8')
|
||||
}
|
||||
|
||||
async function runPair() {
|
||||
const beforeF = arg('before'), afterF = arg('after')
|
||||
if (!beforeF || !afterF) throw new InputError('нужны --before <файл> --after <файл>')
|
||||
const before = await readNote(beforeF)
|
||||
const after = await readNote(afterF)
|
||||
const porog = Number(arg('porog', String(POROG_DEFAULT)))
|
||||
const res = preservationCheck(before, after, { clean: !has('no-clean'), porog })
|
||||
if (has('json')) console.log(JSON.stringify({ before: beforeF, after: afterF, ...res }, null, 2))
|
||||
else {
|
||||
if (res.code === 0) console.log(`✓ сохранность цела${res.cleanliness ? `, чистота ${res.cleanliness.score}/100` : ''}`)
|
||||
else {
|
||||
if (res.lost.length) console.error(`✗ потеряно инвариантов: ${res.lost.length} → ${res.lost.slice(0, 8).map(l => `${l.kind}:${l.sample}`).join(' · ')}`)
|
||||
if (res.dirty) console.error(`✗ грязный текст: score ${res.cleanliness.score}/100, hard bans ${res.cleanliness.hard_ban_count}`)
|
||||
}
|
||||
}
|
||||
return res.code
|
||||
}
|
||||
|
||||
const FIX = path.join(ROOT, 'tests/fixtures/humanize')
|
||||
async function runSelftest() {
|
||||
// Красный кролик (приём 2): битая фикстура гоняется в каждом прогоне.
|
||||
// Зелёный кролик (broken вернул 0) = провал самого гейта.
|
||||
const cases = [
|
||||
{ name: 'note-after-broken.md', expect: 1 },
|
||||
{ name: 'note-after-ok.md', expect: 0 }
|
||||
]
|
||||
const beforeF = path.join(FIX, 'note-before.md')
|
||||
if (!existsSync(beforeF)) { console.error(`нет фикстуры ${beforeF} (проба-украшение)`); return 1 }
|
||||
const before = await readNote(beforeF)
|
||||
let extracted = 0
|
||||
for (const c of cases) {
|
||||
const f = path.join(FIX, c.name)
|
||||
if (!existsSync(f)) { console.error(`нет фикстуры ${f}`); return 1 }
|
||||
extracted += 1
|
||||
const res = preservationCheck(before, await readNote(f), { clean: true }) // InputError (нет сканера) → 2
|
||||
if (res.code !== c.expect) {
|
||||
console.error(`✗ selftest: ${c.name} дал ${res.code}, ждали ${c.expect}` +
|
||||
(res.lost.length ? ` (потери: ${res.lost.map(l => l.kind).join(',')})` : '') +
|
||||
(res.dirty ? ` (грязь: ${res.cleanliness.score})` : ''))
|
||||
return 1
|
||||
}
|
||||
console.log(`✓ selftest: ${c.name} → ${res.code}`)
|
||||
}
|
||||
if (extracted === 0) { console.error('ноль извлечённых фикстур'); return 1 }
|
||||
console.log('✓ selftest: красный кролик красный, честный рерайт зелёный')
|
||||
|
||||
// deslop: снимает названный слоп, держит факты, НЕ трогает то, что не умеет.
|
||||
// Красный кролик против регрессии кириллического `\b` (JS `\b` — ASCII-only).
|
||||
const fixable = 'Это является ключевым паттерном v2. Видно не только как файл, но и как карта.'
|
||||
const cleaned = deslop(fixable)
|
||||
if (runScanner(cleaned).slop_ban_count !== 0) { console.error(`✗ selftest deslop: слоп не снят: ${cleaned}`); return 1 }
|
||||
if (!cleaned.includes('v2')) { console.error('✗ selftest deslop: потерян факт-токен v2'); return 1 }
|
||||
const unfixable = 'Это комплексный подход к памяти.'
|
||||
if (runScanner(deslop(unfixable)).slop_ban_count === 0) { console.error('✗ selftest deslop: незнакомый бан молча снят (сторож ослеп)'); return 1 }
|
||||
console.log('✓ selftest: deslop снимает названный слоп и держит факты, незнакомый бан оставляет')
|
||||
return 0
|
||||
}
|
||||
|
||||
function scanCorpus(vault) {
|
||||
if (!existsSync(CORPUS_SCANNER)) throw new InputError(`нет корпус-драйвера: ${CORPUS_SCANNER}`)
|
||||
const r = spawnSync(PY, [CORPUS_SCANNER, vault], { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024 })
|
||||
if (r.error) throw new InputError(`корпус-сканер не запустился: ${r.error.message}`)
|
||||
if (r.status === 2) throw new InputError(`корпус-сканер: ${(r.stderr || '').trim()}`)
|
||||
if (r.stderr && /Traceback|ModuleNotFoundError/.test(r.stderr)) throw new InputError(`корпус-сканер упал: ${r.stderr.trim().split('\n').pop()}`)
|
||||
const rows = r.stdout.split('\n').filter(Boolean).map(l => JSON.parse(l)).filter(x => typeof x.score === 'number')
|
||||
return rows
|
||||
}
|
||||
function pct(sorted, p) { if (!sorted.length) return null; const i = Math.min(sorted.length - 1, Math.floor(p / 100 * sorted.length)); return sorted[i] }
|
||||
|
||||
async function runBaseline() {
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const out = arg('out', '.mnemazine/state/humanize-baseline.json')
|
||||
const report = arg('report', '')
|
||||
const rows = scanCorpus(vault)
|
||||
if (rows.length < 1) throw new InputError('корпус пуст: 0 нот отсканировано')
|
||||
const scores = rows.map(r => r.score).sort((a, b) => a - b)
|
||||
const bands = {
|
||||
clean: rows.filter(r => r.score >= 85).length, // ≥85 чисто
|
||||
spot: rows.filter(r => r.score >= 60 && r.score < 85).length, // 60-84 точечная правка
|
||||
rewrite: rows.filter(r => r.score < 60).length // <60 рерайт
|
||||
}
|
||||
const worst = rows.slice().sort((a, b) => a.score - b.score).slice(0, 300)
|
||||
.map(r => ({ path: r.path, score: r.score, hard_ban_count: r.hard_ban_count }))
|
||||
const data = {
|
||||
generated_at: arg('now', ''), // штамп извне (Date.now() в скриптах воркфлоу запрещён; тут CLI — допустимо, но оставляем внешним)
|
||||
vault,
|
||||
notes_scanned: rows.length,
|
||||
median_score: pct(scores, 50),
|
||||
p10_score: pct(scores, 10),
|
||||
bands,
|
||||
hard_ban_notes: rows.filter(r => r.hard_ban_count > 0).length,
|
||||
// настоящий слоп (кроме сквозного «Длинное тире») — очередь кампании важнее полосы
|
||||
slop_ban_notes: rows.filter(r => (r.slop_ban_count | 0) > 0).length,
|
||||
worst
|
||||
}
|
||||
if (!data.generated_at) data.generated_at = new Date().toISOString()
|
||||
await fs.mkdir(path.dirname(path.resolve(out)), { recursive: true })
|
||||
await fs.writeFile(out, JSON.stringify(data, null, 2), 'utf8')
|
||||
if (report) {
|
||||
const md = [
|
||||
`# Базовый замер читаемости корпуса — ${data.generated_at.slice(0, 10)}`,
|
||||
'',
|
||||
`Vault: \`${vault}\` · нот отсканировано: **${data.notes_scanned}** (вне graphify-каталогов).`,
|
||||
`Прибор: \`skills/humanizer-ru/scripts/scan.py\` (детерминированный сканер humanizer-ru, П12).`,
|
||||
'',
|
||||
'## Распределение по полосам чистоты (scan.py:54)',
|
||||
'',
|
||||
'| Полоса | Порог | Нот | Доля |',
|
||||
'|---|---|---|---|',
|
||||
`| чисто | ≥85 | ${bands.clean} | ${(bands.clean / rows.length * 100).toFixed(1)}% |`,
|
||||
`| точечная правка | 60–84 | ${bands.spot} | ${(bands.spot / rows.length * 100).toFixed(1)}% |`,
|
||||
`| рерайт | <60 | ${bands.rewrite} | ${(bands.rewrite / rows.length * 100).toFixed(1)}% |`,
|
||||
'',
|
||||
`Медиана: **${data.median_score}** · p10: **${data.p10_score}**.`,
|
||||
'',
|
||||
`Нот с hard bans: **${data.hard_ban_notes}** из ${rows.length} — но ${data.hard_ban_notes - data.slop_ban_notes} из них только за счёт сквозного «Длинное тире» (даты и заголовки).`,
|
||||
`Нот с настоящим слопом (кроме em-dash): **${data.slop_ban_notes}** — вот реальная очередь на очеловечивание. Sweep конвейера краснит именно на слопе, не на em-dash.`,
|
||||
'',
|
||||
'## Первые 20 худших (очередь кампании П13)',
|
||||
'',
|
||||
'| score | нота |',
|
||||
'|---|---|',
|
||||
...worst.slice(0, 20).map(w => `| ${w.score} | \`${path.basename(w.path)}\` |`),
|
||||
'',
|
||||
'Замер read-only: vault не изменялся. Кампания П13 берёт `worst` из json как `--worst-first`.'
|
||||
].join('\n')
|
||||
await fs.mkdir(path.dirname(path.resolve(report)), { recursive: true })
|
||||
await fs.writeFile(report, md + '\n', 'utf8')
|
||||
}
|
||||
console.log(JSON.stringify({ notes_scanned: data.notes_scanned, median: data.median_score, p10: data.p10_score, bands, hard_ban_notes: data.hard_ban_notes }, null, 2))
|
||||
return 0
|
||||
}
|
||||
|
||||
function isServicePath(rel) {
|
||||
return rel.split(path.sep).some(s => s.startsWith('.') || s.startsWith('_')) || rel.includes('graphify-out')
|
||||
}
|
||||
|
||||
// Проза, как её видит sweep: без frontmatter, кода, инлайн-кода и неприкасаемых
|
||||
// секций. Слоп меряем ровно на ней — там же, где sweep решает fatal (правило 8:
|
||||
// одна правда об «где искать слоп» на обе розетки).
|
||||
function proseForScan(text) {
|
||||
let prose = text
|
||||
const fm = frontmatter(text); if (fm) prose = prose.slice(fm.length)
|
||||
prose = stripFences(prose).replace(/`[^`\n]+`/g, ' ')
|
||||
for (const s of untouchableSections(text)) prose = prose.replace(s, ' ')
|
||||
return prose
|
||||
}
|
||||
function slopOf(text) { return runScanner(proseForScan(text)).slop_ban_count }
|
||||
|
||||
// Детерминированный перефраз hard-ban конструкций. Правит ТОЛЬКО filler-слова и
|
||||
// копулу (фактов не несут) — числа/ссылки/пути/латиница/wikilinks не трогаются,
|
||||
// потому инвариант «до» ⊆ «после» держится (сверяет preservationCheck у зовущего).
|
||||
// Em-dash легален (sweep на него не фатален), потому «является» → « — ».
|
||||
// ponytail: узкий набор — те hard bans, что снимаются без морфологии. Всё прочее
|
||||
// пас не чинит и честно роняет прогон (fail-closed). Апгрейд — LLM-эскалация на
|
||||
// 2-й итерации (как в кампании), когда живой прогон покажет незакрытый хвост.
|
||||
function matchCase(replacement, original) {
|
||||
return /^[А-ЯЁ]/.test(original) ? replacement.charAt(0).toUpperCase() + replacement.slice(1) : replacement
|
||||
}
|
||||
// Кириллические границы слова: JS `\b` — ASCII-only и НИКОГДА не срабатывает вокруг
|
||||
// кириллицы (в отличие от Unicode-`\b` в Python-сканере). Свои границы: «не буква».
|
||||
// Зеркалят HARD_BANS сканера, чтобы deslop снимал ровно то, что метит sweep.
|
||||
const NB = '(?<![А-Яа-яЁёA-Za-z])'
|
||||
const NA = '(?![А-Яа-яЁёA-Za-z])'
|
||||
const DAN = { 'данный': 'этот', 'данная': 'эта', 'данное': 'это', 'данного': 'этого', 'данной': 'этой', 'данном': 'этом', 'данную': 'эту' }
|
||||
function deslop(text) {
|
||||
let t = text
|
||||
// Пустые вводные — снять целиком, остаток предложения остаётся фактом.
|
||||
t = t.replace(new RegExp(`${NB}стоит\\s+отметить,?\\s+что\\s+`, 'gi'), '')
|
||||
t = t.replace(new RegExp(`${NB}важно\\s+понимать,?\\s+что\\s+`, 'gi'), '')
|
||||
t = t.replace(new RegExp(`${NB}можно\\s+с\\s+уверенностью\\s+сказать,?\\s+что\\s+`, 'gi'), '')
|
||||
t = t.replace(new RegExp(`${NB}в\\s+современном\\s+мире,?\\s+`, 'gi'), '')
|
||||
t = t.replace(new RegExp(`${NB}(?:подводя\\s+итог|таким\\s+образом),?\\s+`, 'gi'), '')
|
||||
t = t.replace(new RegExp(`${NB}в\\s+связи\\s+с\\s+этим${NA}`, 'gi'), 'поэтому')
|
||||
// «Не только X, но и Y» → «и X, и Y».
|
||||
t = t.replace(new RegExp(`${NB}не\\s+только${NA}`, 'gi'), 'и').replace(new RegExp(`${NB}но\\s+и${NA}`, 'gi'), 'и')
|
||||
// «Данный/Данная/…» → «этот/эта/…» (падеж совпадает).
|
||||
t = t.replace(new RegExp(`${NB}данн(?:ый|ая|ое|ого|ой|ом|ую)${NA}`, 'gi'), m => matchCase(DAN[m.toLowerCase()] || m, m))
|
||||
// Копула «является»: «не является X» → «не X»; иначе → « — » (легальный em-dash).
|
||||
t = t.replace(new RegExp(`${NB}не\\s+явля(?:ется|ются)\\s+`, 'gi'), 'не ')
|
||||
t = t.replace(new RegExp(`\\s*${NB}явля(?:ется|ются)${NA}\\s*`, 'gi'), ' — ')
|
||||
return t
|
||||
}
|
||||
async function walkMd(dir, since, acc = []) {
|
||||
for (const e of await fs.readdir(dir, { withFileTypes: true })) {
|
||||
if (e.name.startsWith('.') || e.name.includes('graphify-out')) continue
|
||||
const full = path.join(dir, e.name)
|
||||
if (e.isDirectory()) await walkMd(full, since, acc)
|
||||
else if (e.name.endsWith('.md')) acc.push(full)
|
||||
}
|
||||
return acc
|
||||
}
|
||||
// Розетка run.mjs МЕЖДУ генерацией ноты и sweep: очеловечивает свежие ноты ДО
|
||||
// сторожа, чтобы конвейер не падал о собственный гейт. На каждую свежую ноту:
|
||||
// гейт (слоп?) → автоправка deslop → повторный гейт; не чинится за 2 итерации →
|
||||
// прогон честно падает 1 с именем ноты. Правку принимаем, только если факты целы
|
||||
// (preservationCheck clean:false — «до» ⊆ «после») И слоп снят. Sweep остаётся
|
||||
// байтовым бэкстопом после паса.
|
||||
async function runPass() {
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const since = arg('changed-since', '')
|
||||
const sinceMs = since ? (Number.isFinite(Date.parse(since)) ? Date.parse(since) : Number(since)) : 0
|
||||
const files = await walkMd(vault, sinceMs)
|
||||
const fixed = []
|
||||
const failures = []
|
||||
let checked = 0
|
||||
for (const f of files) {
|
||||
const rel = path.relative(vault, f)
|
||||
if (isServicePath(rel)) continue
|
||||
if (sinceMs && (await fs.stat(f)).mtimeMs < sinceMs) continue
|
||||
const text = await fs.readFile(f, 'utf8')
|
||||
if (slopOf(text) === 0) continue // em-dash / низкий score — не наша забота (advisory sweep)
|
||||
checked += 1
|
||||
let cand = text
|
||||
let cleared = false
|
||||
// Две итерации автоправки (deslop идемпотентен, но структура держит спецификацию
|
||||
// и оставляет шов под LLM-эскалацию на 2-й проход).
|
||||
for (let iter = 0; iter < 2 && !cleared; iter++) {
|
||||
const next = deslop(cand)
|
||||
let g
|
||||
try { g = preservationCheck(text, next, { clean: false }) } // факты «до» ⊆ «после»
|
||||
catch (err) { failures.push({ file: rel, reason: `preservation input: ${err.message}` }); cleared = false; break }
|
||||
if (g.code !== 0) break // правка тронула факт/байт-блок — бросаем кандидата, нота как была
|
||||
cand = next
|
||||
if (slopOf(cand) === 0) cleared = true
|
||||
}
|
||||
if (cleared) {
|
||||
if (cand !== text) await fs.writeFile(f, cand, 'utf8')
|
||||
fixed.push(rel)
|
||||
} else {
|
||||
const bans = runScanner(proseForScan(cand)).hard_bans.filter(([n]) => n !== EM_DASH_BAN)
|
||||
failures.push({ file: rel, slop_ban_count: slopOf(cand), hard_bans: bans })
|
||||
}
|
||||
}
|
||||
const payload = { ok: !failures.length, checked, fixed, failures }
|
||||
if (failures.length) { console.error(JSON.stringify(payload, null, 2)); return 1 }
|
||||
console.log(JSON.stringify(payload, null, 2))
|
||||
return 0
|
||||
}
|
||||
|
||||
async function runSweep() {
|
||||
// Розетка run.mjs: читаемость нот, изменённых с runStartedAt. Фатален СЛОП —
|
||||
// hard bans КРОМЕ «Длинное тире» (является/в современном мире/комплексный подход):
|
||||
// свежая нота из очеловеченного конвейера их нести не должна. Длинное тире сквозное
|
||||
// в корпусе (95% всех hard bans — даты и заголовки), потому advisory, не фатал —
|
||||
// иначе сторож краснит каждый живой прогон, а это тот же провал, что дыра.
|
||||
// Низкий score тоже advisory, фатал только при MNEMAZINE_HUMANIZE_STRICT=1.
|
||||
// ponytail: апгрейд — снять em-dash из корпуса кампанией, тогда включить его в фатал.
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const since = arg('changed-since', '')
|
||||
const sinceMs = since ? (Number.isFinite(Date.parse(since)) ? Date.parse(since) : Number(since)) : 0
|
||||
const porog = Number(arg('porog', String(POROG_DEFAULT)))
|
||||
const strict = process.env.MNEMAZINE_HUMANIZE_STRICT === '1'
|
||||
const files = await walkMd(vault, sinceMs)
|
||||
const failures = []
|
||||
const advisories = []
|
||||
let checked = 0
|
||||
for (const f of files) {
|
||||
const rel = path.relative(vault, f)
|
||||
if (isServicePath(rel)) continue
|
||||
if (sinceMs && (await fs.stat(f)).mtimeMs < sinceMs) continue
|
||||
checked += 1
|
||||
const text = await fs.readFile(f, 'utf8')
|
||||
const c = runScanner(proseForScan(text))
|
||||
const fatal = c.slop_ban_count > 0 || (strict && c.score < porog)
|
||||
if (fatal) failures.push({ file: rel, score: c.score, slop_ban_count: c.slop_ban_count, hard_bans: c.hard_bans })
|
||||
else if (c.hard_ban_count > 0 || c.score < porog) advisories.push({ file: rel, score: c.score, em_dash_only: c.slop_ban_count === 0 })
|
||||
}
|
||||
const payload = { ok: !failures.length, checked, strict, porog, failures, advisories_count: advisories.length }
|
||||
if (failures.length) { console.error(JSON.stringify(payload, null, 2)); return 1 }
|
||||
console.log(JSON.stringify(payload, null, 2))
|
||||
return 0
|
||||
}
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
if (has('selftest')) return await runSelftest()
|
||||
if (has('baseline')) return await runBaseline()
|
||||
if (has('pass')) return await runPass()
|
||||
if (has('sweep')) return await runSweep()
|
||||
return await runPair()
|
||||
} catch (err) {
|
||||
if (err instanceof InputError) { console.error(`[вход] ${err.message}`); return 2 }
|
||||
console.error(`[сбой] ${err.stack || err.message}`); return 2
|
||||
}
|
||||
}
|
||||
|
||||
// Только как CLI. Импорт (preservationCheck из digest) не должен запускать main().
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
process.exit(await main())
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { MIN_CYR_SHARE, SPEC_TYPES } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
function flag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
if (flag('help')) {
|
||||
console.log(`mnemazine-kb-lint.mjs — линт корпуса знаний: битые wikilinks, расхождение индексов,
|
||||
NOTE-SPEC, сироты, кириллица, обязательные блоки, протухшие ноты, мусор корня.
|
||||
|
||||
Использование: node scripts/mnemazine-kb-lint.mjs [флаги]
|
||||
--vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
|
||||
--limit N сколько худших показать в каждом списке (по умолчанию 20)
|
||||
--json полный отчёт в JSON в stdout (report_path: null без --write)
|
||||
--write записать отчёт и .last-lint в <vault>/99 Система/_lint/
|
||||
(по умолчанию НИЧЕГО не пишет: отчёт уходит в stdout)
|
||||
--help эта справка
|
||||
|
||||
Коды возврата: 0 — чисто; 1 — есть critical-находки или ошибка запуска.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// Закрытый enum type из docs/NOTE-SPEC.md — незнакомое значение = провал.
|
||||
// Ноты, датированные с этой даты, обязаны NOTE-SPEC (старые — advisory, отдельная кампания).
|
||||
const SPEC_DATE = '2026-07-25'
|
||||
const STALE_DAYS = 30
|
||||
// Короче — доля кириллицы шумит на списках путей/команд, не на прозе.
|
||||
const MIN_PROSE_LETTERS = 100
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
// Порог «индекс протух», а не строгое «старше хоть на секунду». Строгое сравнение было красным ПО
|
||||
// ПОСТРОЕНИЮ: конвейер строит эмбеддинги и граф, а потом дописывает ноты — mtime индекса всегда раньше
|
||||
// mtime свежайшей ноты, и линт печатал critical «старше на 0 дн.» сразу после успешного прогона.
|
||||
// Гейт, который нельзя пройти, ничего не измеряет: он просто приучает не смотреть на красное.
|
||||
const INDEX_STALE_MS = Number(process.env.MNEMAZINE_INDEX_STALE_DAYS || '1') * DAY_MS
|
||||
|
||||
// macOS хранит имена файлов в NFD, текст ссылок обычно NFC — без нормализации
|
||||
// русские wikilinks ложно битые.
|
||||
const nfc = value => String(value || '').normalize('NFC')
|
||||
|
||||
// Служебный слой (NOTE-SPEC «Когда НЕ по этой спеке»): свои форматы,
|
||||
// спека/сиротство/блоки к ним не применяются.
|
||||
function isService(rel) {
|
||||
if (rel.startsWith('99 Система/') || rel.startsWith('00 Входящие/')) return true
|
||||
const parts = rel.split('/')
|
||||
if (parts.some(part => part.startsWith('_'))) return true
|
||||
const base = parts[parts.length - 1]
|
||||
return /^(AGENTS|CLAUDE|README)\.md$/i.test(base) || base.startsWith('Лог ') || base.startsWith('Без названия')
|
||||
}
|
||||
|
||||
async function walkVault(vault) {
|
||||
const md = []
|
||||
const dirs = new Set()
|
||||
const fileKeys = new Set()
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const abs = path.join(dir, item.name)
|
||||
const rel = nfc(path.relative(vault, abs).replace(/\\/g, '/'))
|
||||
if (item.isDirectory()) {
|
||||
if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
// Отчёты этого же линта — не ноты: не линтуются и не входят в счёт диска.
|
||||
if (rel === '99 Система/_lint') continue
|
||||
dirs.add(rel)
|
||||
await walk(abs)
|
||||
} else if (item.isFile()) {
|
||||
fileKeys.add(rel)
|
||||
fileKeys.add(nfc(item.name))
|
||||
fileKeys.add(nfc(item.name).replace(/\.md$/i, ''))
|
||||
if (item.name.endsWith('.md')) md.push({ abs, rel })
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
return { md, dirs, fileKeys }
|
||||
}
|
||||
|
||||
function fmValue(fm, key) {
|
||||
const match = (fm || '').match(new RegExp(`^${key}:\\s*(.*)$`, 'm'))
|
||||
if (!match) return ''
|
||||
return match[1].replace(/\s+#.*$/, '').trim().replace(/^['"]|['"]$/g, '')
|
||||
}
|
||||
|
||||
function fmDate(fm, key) {
|
||||
const hit = fmValue(fm, key).match(/\d{4}-\d{2}-\d{2}/)
|
||||
return hit ? hit[0] : ''
|
||||
}
|
||||
|
||||
// Код-блоки гасятся пробелами, не вырезаются — номера строк и позиции не едут.
|
||||
function scanText(text) {
|
||||
return text
|
||||
.replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
|
||||
.replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
|
||||
}
|
||||
|
||||
function proseOf(text) {
|
||||
return text
|
||||
.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, '')
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`[^`\n]*`/g, ' ')
|
||||
.replace(/https?:\/\/\S+/g, ' ')
|
||||
}
|
||||
|
||||
function cyrillicShare(prose) {
|
||||
const cyr = (prose.match(/[а-яё]/gi) || []).length
|
||||
const lat = (prose.match(/[a-z]/gi) || []).length
|
||||
const total = cyr + lat
|
||||
return { total, share: total ? cyr / total : 1 }
|
||||
}
|
||||
|
||||
function linkTarget(raw) {
|
||||
return nfc(raw.split('|')[0].split('#')[0].split('^')[0].trim().replace(/\\+$/, ''))
|
||||
}
|
||||
|
||||
async function checkIndexes(vault, notes) {
|
||||
const issues = []
|
||||
const diskCount = notes.length
|
||||
const master = await fs.readFile(path.join(vault, '_МАСТЕР-ИНДЕКС.md'), 'utf8').catch(() => '')
|
||||
const hit = master.match(/Всего markdown[^:]*:\s*\*\*(\d+)\*\*/i)
|
||||
const counter = hit ? Number(hit[1]) : null
|
||||
if (counter === null) issues.push('в _МАСТЕР-ИНДЕКС.md не найден счётчик «Всего markdown: **N**»')
|
||||
else if (counter !== diskCount) issues.push(`_МАСТЕР-ИНДЕКС.md заявляет ${counter} .md, на диске ${diskCount}`)
|
||||
const newestMs = notes.reduce((max, note) => Math.max(max, note.mtimeMs), 0)
|
||||
for (const relIndex of ['99 Система/_embeddings.json', 'graphify-out/graph.json']) {
|
||||
const stat = await fs.stat(path.join(vault, relIndex)).catch(() => null)
|
||||
if (!stat) issues.push(`${relIndex} отсутствует`)
|
||||
else if (newestMs - stat.mtimeMs >= INDEX_STALE_MS) {
|
||||
const lagDays = Math.round((newestMs - stat.mtimeMs) / DAY_MS * 10) / 10
|
||||
issues.push(`${relIndex} старше свежайшей ноты на ${lagDays} дн.`)
|
||||
}
|
||||
}
|
||||
return { issues, counter, disk_count: diskCount, newest_note: new Date(newestMs).toISOString() }
|
||||
}
|
||||
|
||||
async function rootJunk(vault) {
|
||||
const junk = []
|
||||
for (const item of await fs.readdir(vault, { withFileTypes: true }).catch(() => [])) {
|
||||
const name = nfc(item.name)
|
||||
if (name === '.DS_Store' || name.startsWith('Без названия')) junk.push(name)
|
||||
}
|
||||
return junk.sort()
|
||||
}
|
||||
|
||||
async function runLint({ vault, limit }) {
|
||||
const wiki = await walkVault(vault)
|
||||
const notes = []
|
||||
for (const file of wiki.md) {
|
||||
const [text, stat] = await Promise.all([fs.readFile(file.abs, 'utf8'), fs.stat(file.abs)])
|
||||
const fmMatch = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)
|
||||
notes.push({ ...file, text, mtimeMs: stat.mtimeMs, fm: fmMatch ? fmMatch[1] : null })
|
||||
}
|
||||
|
||||
const noteIndex = new Map()
|
||||
const addKey = (key, rel) => {
|
||||
if (!key) return
|
||||
if (!noteIndex.has(key)) noteIndex.set(key, new Set())
|
||||
noteIndex.get(key).add(rel)
|
||||
}
|
||||
for (const note of notes) {
|
||||
const base = nfc(path.basename(note.rel))
|
||||
addKey(note.rel, note.rel)
|
||||
addKey(note.rel.replace(/\.md$/i, ''), note.rel)
|
||||
addKey(base, note.rel)
|
||||
addKey(base.replace(/\.md$/i, ''), note.rel)
|
||||
}
|
||||
|
||||
const brokenByTarget = new Map()
|
||||
const linked = new Set()
|
||||
const linkRe = /\[\[([^\]\n]+)\]\]/g
|
||||
for (const note of notes) {
|
||||
const text = scanText(note.text)
|
||||
let match
|
||||
while ((match = linkRe.exec(text))) {
|
||||
const target = linkTarget(match[1])
|
||||
if (!target || target.startsWith('#') || /^(https?|mailto):/i.test(target)) continue
|
||||
const base = nfc(path.basename(target))
|
||||
const keys = [target, target.replace(/\.md$/i, ''), base, base.replace(/\.md$/i, '')]
|
||||
const hitNotes = keys.map(key => noteIndex.get(key)).find(Boolean)
|
||||
if (hitNotes) {
|
||||
for (const rel of hitNotes) linked.add(rel)
|
||||
continue
|
||||
}
|
||||
if (keys.some(key => wiki.dirs.has(key) || wiki.fileKeys.has(key))) continue
|
||||
if (!brokenByTarget.has(target)) brokenByTarget.set(target, { target, count: 0, examples: [] })
|
||||
const group = brokenByTarget.get(target)
|
||||
group.count += 1
|
||||
if (group.examples.length < 3) group.examples.push(note.rel)
|
||||
}
|
||||
}
|
||||
|
||||
const orphans = []
|
||||
const specNew = []
|
||||
const specOld = []
|
||||
const lowCyr = []
|
||||
const missingBlocks = []
|
||||
let staleCount = 0
|
||||
let contentNotes = 0
|
||||
const nowMs = Date.now()
|
||||
for (const note of notes) {
|
||||
if (isService(note.rel)) continue
|
||||
contentNotes += 1
|
||||
if (!linked.has(note.rel)) orphans.push(note.rel)
|
||||
|
||||
const problems = []
|
||||
if (!note.fm) problems.push('нет frontmatter')
|
||||
else {
|
||||
if (!/^source:\s*\S/m.test(note.fm)) problems.push('нет source:')
|
||||
const type = fmValue(note.fm, 'type')
|
||||
if (!SPEC_TYPES.has(type)) problems.push(`type вне enum: ${type || '(пусто)'}`)
|
||||
}
|
||||
if (problems.length) {
|
||||
const date = fmDate(note.fm, 'created') || fmDate(note.fm, 'updated') || new Date(note.mtimeMs).toISOString().slice(0, 10)
|
||||
;(date >= SPEC_DATE ? specNew : specOld).push({ file: note.rel, date, problems })
|
||||
}
|
||||
|
||||
const prose = cyrillicShare(proseOf(note.text))
|
||||
if (prose.total >= MIN_PROSE_LETTERS && prose.share < MIN_CYR_SHARE) {
|
||||
lowCyr.push({ file: note.rel, share_pct: Math.round(prose.share * 100) })
|
||||
}
|
||||
|
||||
const missing = []
|
||||
if (!/^#{2,3}\s*(?:🎯\s*)?Как это поможет мне/m.test(note.text)) missing.push('Как это поможет мне')
|
||||
if (!/^#{2,3}\s*Достоверность/m.test(note.text)) missing.push('Достоверность')
|
||||
if (missing.length) missingBlocks.push({ file: note.rel, missing })
|
||||
|
||||
const updated = fmDate(note.fm, 'updated')
|
||||
const ageMs = nowMs - (updated ? Date.parse(updated) : note.mtimeMs)
|
||||
if (ageMs > STALE_DAYS * DAY_MS) staleCount += 1
|
||||
}
|
||||
|
||||
const brokenList = [...brokenByTarget.values()].sort((a, b) => b.count - a.count || a.target.localeCompare(b.target))
|
||||
const indexes = await checkIndexes(vault, notes)
|
||||
const junk = await rootJunk(vault)
|
||||
const hasCritical = brokenList.length > 0 || indexes.issues.length > 0
|
||||
|
||||
return {
|
||||
ok: !hasCritical,
|
||||
date: new Date().toISOString().slice(0, 10),
|
||||
vault,
|
||||
checked: { markdown_files: notes.length, content_notes: contentNotes },
|
||||
checks: {
|
||||
broken_wikilinks: {
|
||||
severity: 'critical',
|
||||
count: brokenList.reduce((sum, item) => sum + item.count, 0),
|
||||
unique_targets: brokenList.length,
|
||||
worst: brokenList.slice(0, limit)
|
||||
},
|
||||
index_divergence: { severity: 'critical', count: indexes.issues.length, ...indexes },
|
||||
spec_new: { severity: 'high', count: specNew.length, worst: specNew.slice(0, limit) },
|
||||
spec_old: { severity: 'medium', count: specOld.length, worst: specOld.slice(0, limit) },
|
||||
orphans: { severity: 'medium', count: orphans.length, worst: orphans.sort().slice(0, limit) },
|
||||
low_cyrillic: {
|
||||
severity: 'medium',
|
||||
count: lowCyr.length,
|
||||
worst: lowCyr.sort((a, b) => a.share_pct - b.share_pct).slice(0, limit)
|
||||
},
|
||||
missing_blocks: { severity: 'medium', count: missingBlocks.length, worst: missingBlocks.slice(0, limit) },
|
||||
stale_notes: { severity: 'info', count: staleCount },
|
||||
root_junk: { severity: 'info', count: junk.length, files: junk }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderReport(report, limit) {
|
||||
const c = report.checks
|
||||
const lines = []
|
||||
lines.push(`# KB Lint — ${report.date}`, '')
|
||||
lines.push(`- Vault: \`${report.vault}\``)
|
||||
lines.push(`- Всего .md: ${report.checked.markdown_files} · содержательных нот: ${report.checked.content_notes}`)
|
||||
lines.push(`- Итог: ${report.ok ? 'чисто (exit 0)' : 'есть critical (exit 1)'}`)
|
||||
lines.push('', '## Сводка', '')
|
||||
lines.push('| Проверка | Северити | Счёт |')
|
||||
lines.push('|---|---|---:|')
|
||||
lines.push(`| Битые wikilinks | critical | ${c.broken_wikilinks.count} |`)
|
||||
lines.push(`| Расхождение индексов | critical | ${c.index_divergence.count} |`)
|
||||
lines.push(`| Спека NOTE-SPEC: ноты ≥ ${SPEC_DATE} | high | ${c.spec_new.count} |`)
|
||||
lines.push(`| Спека NOTE-SPEC: старые ноты | medium | ${c.spec_old.count} |`)
|
||||
lines.push(`| Ноты-сироты | medium | ${c.orphans.count} |`)
|
||||
lines.push(`| Кириллица в прозе < ${MIN_CYR_SHARE * 100}% | medium | ${c.low_cyrillic.count} |`)
|
||||
lines.push(`| Нет «Как это поможет мне»/«Достоверность» | medium | ${c.missing_blocks.count} |`)
|
||||
lines.push(`| Протухшие ноты (> ${STALE_DAYS} дн.) | info | ${c.stale_notes.count} |`)
|
||||
lines.push(`| Мусор корня | info | ${c.root_junk.count} |`)
|
||||
|
||||
lines.push('', `## Битые wikilinks — ${c.broken_wikilinks.count} (${c.broken_wikilinks.unique_targets} целей)`, '')
|
||||
for (const item of c.broken_wikilinks.worst) {
|
||||
lines.push(`- \`[[${item.target}]]\` — ${item.count} вхожд. · например: \`${item.examples[0]}\``)
|
||||
}
|
||||
|
||||
lines.push('', '## Расхождение индексов', '')
|
||||
lines.push(`- Счётчик _МАСТЕР-ИНДЕКС.md: ${c.index_divergence.counter ?? 'не найден'} · на диске: ${c.index_divergence.disk_count}`)
|
||||
lines.push(`- Свежайшая нота: ${c.index_divergence.newest_note}`)
|
||||
for (const issue of c.index_divergence.issues) lines.push(`- ПРОБЛЕМА: ${issue}`)
|
||||
if (!c.index_divergence.issues.length) lines.push('- Индексы сходятся.')
|
||||
|
||||
lines.push('', `## Спека NOTE-SPEC: ноты ≥ ${SPEC_DATE} (обязаны спеке) — ${c.spec_new.count}`, '')
|
||||
for (const item of c.spec_new.worst) lines.push(`- \`${item.file}\` (${item.date}) — ${item.problems.join(' · ')}`)
|
||||
|
||||
lines.push('', `## Спека NOTE-SPEC: старые ноты (advisory) — ${c.spec_old.count}`, '')
|
||||
for (const item of c.spec_old.worst) lines.push(`- \`${item.file}\` (${item.date}) — ${item.problems.join(' · ')}`)
|
||||
|
||||
lines.push('', `## Ноты-сироты (0 входящих ссылок) — ${c.orphans.count}`, '')
|
||||
for (const file of c.orphans.worst) lines.push(`- \`${file}\``)
|
||||
|
||||
lines.push('', `## Кириллица в прозе < ${MIN_CYR_SHARE * 100}% — ${c.low_cyrillic.count}`, '')
|
||||
for (const item of c.low_cyrillic.worst) lines.push(`- \`${item.file}\` — ${item.share_pct}%`)
|
||||
|
||||
lines.push('', `## Нет обязательных блоков — ${c.missing_blocks.count}`, '')
|
||||
for (const item of c.missing_blocks.worst) lines.push(`- \`${item.file}\` — нет: ${item.missing.join(', ')}`)
|
||||
|
||||
lines.push('', `## Мусор корня (только список, ничего не удалено) — ${c.root_junk.count}`, '')
|
||||
for (const file of c.root_junk.files) lines.push(`- \`${file}\``)
|
||||
|
||||
lines.push('', `Списки обрезаны до ${limit} худших; полные данные — \`npm run lint:kb -- --json\`.`)
|
||||
return `${lines.join('\n').trim()}\n`
|
||||
}
|
||||
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const limit = Number(arg('limit', '20'))
|
||||
const report = await runLint({ vault, limit })
|
||||
|
||||
// Запись в корпус — только по явному --write. Без него отчёт уходит в stdout,
|
||||
// каталог _lint/ не создаётся: просмотр не правит корпус (план П08).
|
||||
const WRITE = flag('write')
|
||||
let reportPath = null
|
||||
if (WRITE) {
|
||||
const lintDir = path.join(vault, '99 Система', '_lint')
|
||||
await fs.mkdir(lintDir, { recursive: true })
|
||||
reportPath = path.join(lintDir, `lint-${report.date}.md`)
|
||||
await fs.writeFile(reportPath, renderReport(report, limit), 'utf8')
|
||||
await fs.writeFile(path.join(lintDir, '.last-lint'), `${new Date().toISOString()}\n`, 'utf8')
|
||||
}
|
||||
|
||||
if (flag('json')) {
|
||||
console.log(JSON.stringify({ ...report, report_path: reportPath }, null, 2))
|
||||
} else if (WRITE) {
|
||||
const counts = Object.fromEntries(Object.entries(report.checks).map(([name, check]) => [name, check.count]))
|
||||
console.log(JSON.stringify({ ok: report.ok, vault, counts, report_path: reportPath }, null, 2))
|
||||
} else {
|
||||
process.stdout.write(renderReport(report, limit))
|
||||
}
|
||||
// Не process.exit(1): при пайпе хвост stdout (крупный --json) обрезается на выходе.
|
||||
// exitCode даёт циклу событий дозаписать поток (вскрыто прибором П15 --converge).
|
||||
if (!report.ok) process.exitCode = 1
|
||||
+105
-15
@@ -16,7 +16,7 @@
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const SELFTEST = argv.includes('--selftest')
|
||||
@@ -27,7 +27,33 @@ function arg(name, fb = '') {
|
||||
}
|
||||
|
||||
const DEEP = argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
|
||||
const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || 'claude')
|
||||
const STDOUT = argv.includes('--stdout')
|
||||
const JSON_OUT = argv.includes('--json')
|
||||
|
||||
if (argv.includes('--help')) {
|
||||
console.log(`mnemazine-kb-search.mjs — тематический поиск по корпусу знаний.
|
||||
Локальный режим — 0 токенов; --deep (или MNEMAZINE_DEEP=1) — рой агентов с синтезом.
|
||||
|
||||
Использование: node scripts/mnemazine-kb-search.mjs --topic "<тема>" [флаги]
|
||||
--topic "<тема>" тема поиска (обязательна)
|
||||
--vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
|
||||
--out <каталог> каталог отчёта (иначе MNEMAZINE_REPORTS или ./reports);
|
||||
каталог внутри корпуса — отказ с кодом 2
|
||||
--stdout отчёт в stdout, файл не создаётся
|
||||
--json машинная выдача в stdout: results[] с note/score/subject/snippets
|
||||
--deep LLM-рой: планирование запроса, шард-агенты, синтез
|
||||
--verify отбраковка необоснованных находок (только с --deep)
|
||||
--concurrency N параллелизм роя (по умолчанию 4)
|
||||
--max-notes N потолок кандидатов для роя (по умолчанию 60)
|
||||
--shard-size N заметок на агента (по умолчанию 6)
|
||||
--max-shards N жёсткий потолок агентов в deep (по умолчанию 12)
|
||||
--selftest селф-тест во временном каталоге
|
||||
--help эта справка
|
||||
|
||||
Коды возврата: 0 — отчёт готов; 1 — ошибка или нет темы; 2 — отказ: каталог отчёта внутри корпуса.`)
|
||||
process.exit(0)
|
||||
}
|
||||
const PROVIDER = arg('provider', process.env.MNEMAZINE_LLM || activeProvider())
|
||||
const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || '4'))
|
||||
const MAX_NOTES = Number(arg('max-notes', '60')) // candidate cap fed to the swarm
|
||||
const SHARD_SIZE = Number(arg('shard-size', '6')) // notes per agent
|
||||
@@ -40,10 +66,17 @@ const VERIFY = argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY
|
||||
const MAX_VERIFY = Number(arg('max-verify', '5')) // top-K findings to verify
|
||||
|
||||
// --- helpers -----------------------------------------------------------------
|
||||
function isServicePath(p) {
|
||||
const parts = p.split(path.sep)
|
||||
if (parts.some(seg => seg === 'graphify-out' || seg === 'graphify-out-snapshots' || seg.startsWith('graphify-out-backup-'))) return true
|
||||
return parts.some((seg, i) => seg === '99 Система' && parts[i + 1] === '_archive')
|
||||
}
|
||||
|
||||
async function walk(dir, out = []) {
|
||||
for (const e of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (e.name.startsWith('.')) continue
|
||||
const full = path.join(dir, e.name)
|
||||
if (isServicePath(full)) continue
|
||||
if (e.isDirectory()) await walk(full, out)
|
||||
else if (e.name.endsWith('.md')) out.push(full)
|
||||
}
|
||||
@@ -52,25 +85,38 @@ async function walk(dir, out = []) {
|
||||
|
||||
const STOP = new Set(['the', 'and', 'для', 'что', 'как', 'это', 'про', 'или', 'был', 'are', 'with', 'из', 'на', 'по', 'не', 'от'])
|
||||
const tokens = s => (String(s).toLowerCase().match(/[\p{L}\p{N}]{3,}/gu) || []).filter(t => !STOP.has(t))
|
||||
const uniq = xs => [...new Set(xs.filter(Boolean))]
|
||||
|
||||
function scoreNote(text, rel, terms) {
|
||||
const hay = (rel + '\n' + text).toLowerCase()
|
||||
const q = uniq(terms)
|
||||
if (!q.length) return 0
|
||||
const hayTokens = tokens(`${rel}\n${text}`)
|
||||
const relTokens = new Set(tokens(rel))
|
||||
const counts = new Map()
|
||||
for (const t of hayTokens) counts.set(t, (counts.get(t) || 0) + 1)
|
||||
const allTerms = q.every(t => counts.has(t))
|
||||
const hasBigram = q.length > 1 && q.slice(0, -1).some((t, i) =>
|
||||
hayTokens.some((h, j) => h === t && hayTokens[j + 1] === q[i + 1]))
|
||||
if (!allTerms && !hasBigram) return 0
|
||||
let score = 0
|
||||
for (const t of terms) {
|
||||
let from = 0, n = 0
|
||||
while ((from = hay.indexOf(t, from)) !== -1) { n++; from += t.length; if (n >= 8) break }
|
||||
score += n
|
||||
if (rel.toLowerCase().includes(t)) score += 4 // title/path hit weighs more
|
||||
for (const t of q) {
|
||||
score += Math.min(counts.get(t) || 0, 8)
|
||||
if (relTokens.has(t)) score += 4 // title/path hit weighs more
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
function tokenIndex(text, term) {
|
||||
const rx = new RegExp(`(?<![\\p{L}\\p{N}])${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\p{L}\\p{N}])`, 'iu')
|
||||
const m = rx.exec(text)
|
||||
return m ? m.index : -1
|
||||
}
|
||||
|
||||
// Pull a few keyword-centered snippets — the local (0-token) "finding".
|
||||
function snippets(text, terms, max = 3) {
|
||||
const out = []
|
||||
const lower = text.toLowerCase()
|
||||
for (const t of terms) {
|
||||
const i = lower.indexOf(t)
|
||||
for (const t of uniq(terms)) {
|
||||
const i = tokenIndex(text, t)
|
||||
if (i === -1) continue
|
||||
const s = Math.max(0, i - 120), e = Math.min(text.length, i + 200)
|
||||
const snip = text.slice(s, e).replace(/\s+/g, ' ').trim()
|
||||
@@ -80,6 +126,27 @@ function snippets(text, terms, max = 3) {
|
||||
return out
|
||||
}
|
||||
|
||||
function frontmatterSubject(text) {
|
||||
if (!text.startsWith('---')) return null
|
||||
const end = text.indexOf('\n---', 3)
|
||||
if (end === -1) return null
|
||||
const m = text.slice(3, end).match(/^subject:\s*(.*)$/mi)
|
||||
if (!m) return null
|
||||
const raw = m[1].trim()
|
||||
if (!raw || raw === 'null' || raw === '~') return null
|
||||
if (raw.startsWith('[') && raw.endsWith(']')) {
|
||||
const items = raw.slice(1, -1).split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
|
||||
return items.length ? items : null
|
||||
}
|
||||
return raw.replace(/^['"]|['"]$/g, '') || null
|
||||
}
|
||||
|
||||
async function logQuery(entry) {
|
||||
const file = path.resolve('.mnemazine', 'state', 'kb-search-log.jsonl')
|
||||
await fs.mkdir(path.dirname(file), { recursive: true })
|
||||
await fs.appendFile(file, `${JSON.stringify(entry)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
// Bounded-concurrency pool — the swarm. One failing task never blocks the rest.
|
||||
async function mapLimit(items, limit, fn) {
|
||||
let i = 0
|
||||
@@ -294,7 +361,7 @@ function renderReport(topic, report, meta) {
|
||||
}
|
||||
|
||||
// --- main --------------------------------------------------------------------
|
||||
async function run(topic, vault, outDir) {
|
||||
async function run(topic, vault, outDir, { stdout = false, json = false } = {}) {
|
||||
const stamp = new Date().toISOString()
|
||||
const { terms, facets } = await plan(topic)
|
||||
// RECON
|
||||
@@ -305,10 +372,21 @@ async function run(topic, vault, outDir) {
|
||||
if (!text) continue
|
||||
const rel = path.relative(vault, f)
|
||||
const score = scoreNote(text, rel, terms)
|
||||
if (score > 0) scored.push({ rel, text, score, 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)
|
||||
const candidates = scored.slice(0, MAX_NOTES)
|
||||
if (json) {
|
||||
const results = candidates.map(n => ({
|
||||
note: n.rel,
|
||||
score: n.score,
|
||||
subject: n.subject,
|
||||
snippets: snippets(n.text, terms)
|
||||
}))
|
||||
await logQuery({ ts: stamp, topic, mode: 'json', results: results.length })
|
||||
process.stdout.write(`${JSON.stringify({ topic, scanned: files.length, results }, null, 2)}\n`)
|
||||
return null
|
||||
}
|
||||
// FAN-OUT — shard within facet groups so each shard carries one focus axis
|
||||
// (2A). No facets (local / planning failed) → flat sharding as before.
|
||||
let shards = [] // each: { notes:[...], facet }
|
||||
@@ -344,6 +422,11 @@ async function run(topic, vault, outDir) {
|
||||
// FAN-IN
|
||||
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) })
|
||||
await logQuery({ ts: stamp, topic, mode: DEEP && llmAvailable(PROVIDER) ? 'deep' : 'local', results: kept.length })
|
||||
if (stdout) {
|
||||
process.stdout.write(md.endsWith('\n') ? md : `${md}\n`)
|
||||
return null
|
||||
}
|
||||
await fs.mkdir(outDir, { recursive: true })
|
||||
const out = path.join(outDir, `search-${slugify(topic)}-${stamp.slice(0, 10)}-${Date.now()}.md`)
|
||||
await fs.writeFile(out, md, 'utf8')
|
||||
@@ -375,7 +458,14 @@ if (SELFTEST) {
|
||||
if (!topic) { console.error('Usage: mnemazine-kb-search.mjs --topic "<тема>" [--deep] [--vault <p>]'); process.exit(1) }
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const outDir = path.resolve(arg('out', process.env.MNEMAZINE_REPORTS || path.join(process.cwd(), 'reports')))
|
||||
run(topic, vault, outDir)
|
||||
.then(p => console.log(p))
|
||||
// fail-closed: каталог отчёта внутри корпуса превращает просмотр в правку
|
||||
// корпуса — отказ держит код, а не привычку (план П08). С --stdout файла нет.
|
||||
const relOut = path.relative(vault, outDir)
|
||||
if (!STDOUT && !JSON_OUT && (relOut === '' || (!relOut.startsWith('..') && !path.isAbsolute(relOut)))) {
|
||||
console.error(`[kb-search] отказ: каталог отчёта внутри корпуса (out=${outDir}, vault=${vault}). Укажи --out вне корпуса или --stdout.`)
|
||||
process.exit(2)
|
||||
}
|
||||
run(topic, vault, outDir, { stdout: STDOUT, json: JSON_OUT })
|
||||
.then(p => { if (p) console.log(p) })
|
||||
.catch(e => { console.error(`[kb-search] ${e.message}`); process.exit(1) })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env node
|
||||
// Урок обязан быть правилом — но не задним числом (план П11, метод-правило 13).
|
||||
//
|
||||
// Читает леджер уроков ТОЛЬКО на чтение (живой <vault>/99 Система/_session-learning-ledger.jsonl
|
||||
// либо MNEMAZINE_LEDGER для проб на копии). У записей с ts не раньше отсечки
|
||||
// (config/doc-claims.json → lesson_schema_since) обязаны быть cause/fix/rule/supersedes.
|
||||
// Отсечка измерена: в живом леджере 29 записей и ни одна этих полей не несёт; проверка без
|
||||
// отсечки покраснела бы на историческом корпусе и была бы отключена в первый же день.
|
||||
// При rule_kind:"executable" файл из enforced_by существует и проходит node --check / bash -n.
|
||||
//
|
||||
// Коды: 0 — нарушений нет (в т.ч. ноль записей после отсечки: за ночь урока может не случиться;
|
||||
// а также нейтральный репо-дефолт vault/ без леджера — у фикстуры учиться нечему, проверять нечего);
|
||||
// 1 — запись после отсечки без обязательного поля либо enforced_by на мёртвый/непроходящий файл;
|
||||
// 2 — леджера нет или он пуст ПРИ ЯВНО заданном корпусе (MNEMAZINE_VAULT/MNEMAZINE_LEDGER или config ≠ дефолт):
|
||||
// назвали живой vault, а прибора в нём нет — это поломка, не «всё хорошо».
|
||||
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { resolveVault, DEFAULT_VAULT } from './mnemazine-paths.mjs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const REQUIRED = ['cause', 'fix', 'rule', 'supersedes']
|
||||
const REBUILD = path.join(ROOT, '.mnemazine', 'state', 'rebuild')
|
||||
|
||||
function ownerMachine() {
|
||||
return existsSync(path.join(REBUILD, 'П01.done.json'))
|
||||
}
|
||||
|
||||
// Живой леджер + «явность» корпуса. MNEMAZINE_LEDGER — проба на копии (явная).
|
||||
// Иначе <vault>/99 Система/…; корпус явный, когда MNEMAZINE_VAULT или config.vault
|
||||
// уводят с нейтрального репо-дефолта vault/ (resolved ≠ DEFAULT_VAULT). Явность
|
||||
// решает код при отсутствии/пустоте леджера: фикстура → 0, живой корпус → 2.
|
||||
function resolveLedger() {
|
||||
if (process.env.MNEMAZINE_LEDGER) return { path: process.env.MNEMAZINE_LEDGER, explicit: true }
|
||||
const vault = resolveVault({ requireExists: false })
|
||||
return { path: path.join(vault, '99 Система', '_session-learning-ledger.jsonl'), explicit: vault !== DEFAULT_VAULT }
|
||||
}
|
||||
|
||||
function cutoff() {
|
||||
const claimsPath = path.join(ROOT, 'config', 'doc-claims.json')
|
||||
if (existsSync(claimsPath)) {
|
||||
try {
|
||||
const since = JSON.parse(readFileSync(claimsPath, 'utf8')).lesson_schema_since
|
||||
if (since) return String(since)
|
||||
} catch {}
|
||||
}
|
||||
return '2026-08-22'
|
||||
}
|
||||
|
||||
function syntaxOk(rel) {
|
||||
const abs = path.isAbsolute(rel) ? rel : path.join(ROOT, rel)
|
||||
if (!existsSync(abs)) return false
|
||||
const ext = path.extname(abs)
|
||||
if (ext === '.mjs' || ext === '.js') return spawnSync(process.execPath, ['--check', abs], { encoding: 'utf8' }).status === 0
|
||||
if (ext === '.sh') return spawnSync('bash', ['-n', abs], { encoding: 'utf8' }).status === 0
|
||||
if (ext === '.py') return spawnSync('python3', ['-m', 'py_compile', abs], { encoding: 'utf8' }).status === 0
|
||||
return true
|
||||
}
|
||||
|
||||
function enforcedByLive(anchor) {
|
||||
const rel = String(anchor || '').replace(/:\d+$/, '')
|
||||
if (!rel) return `enforced_by пуст`
|
||||
if (!existsSync(path.isAbsolute(rel) ? rel : path.join(ROOT, rel))) return `enforced_by файл отсутствует: ${rel}`
|
||||
if (!syntaxOk(rel)) return `enforced_by не проходит синтаксис: ${rel}`
|
||||
return null
|
||||
}
|
||||
|
||||
// {code, checked, after, failures}
|
||||
function evaluate(ledgerPath, since, explicit) {
|
||||
if (!existsSync(ledgerPath)) {
|
||||
if (explicit && !ownerMachine()) {
|
||||
return { code: 0, checked: 0, after: 0, failures: [], skip: 'owner-ops lesson ledger: skipped-as-not-applicable — нет .mnemazine/state/rebuild/П01.done.json (форк/CI, не машина владельца)' }
|
||||
}
|
||||
if (!explicit) return { code: 0, checked: 0, after: 0, failures: [], skip: 'нейтральный репо-дефолт vault/ без леджера — учиться нечему' }
|
||||
return { code: 2, failures: [`леджер отсутствует: ${ledgerPath}`] }
|
||||
}
|
||||
const raw = readFileSync(ledgerPath, 'utf8')
|
||||
const lines = raw.split(/\r?\n/).filter(l => l.trim())
|
||||
if (lines.length === 0) {
|
||||
if (!explicit) return { code: 0, checked: 0, after: 0, failures: [], skip: 'леджер пуст (репо-дефолт) — проверять нечего' }
|
||||
return { code: 2, failures: ['леджер пуст'] }
|
||||
}
|
||||
|
||||
const failures = []
|
||||
let after = 0
|
||||
for (const [i, line] of lines.entries()) {
|
||||
let obj
|
||||
try { obj = JSON.parse(line) } catch { failures.push(`строка ${i + 1}: не JSON`); continue }
|
||||
const ts = String(obj.ts || '')
|
||||
if (!ts || ts < since) continue
|
||||
after++
|
||||
for (const k of REQUIRED) {
|
||||
if (!(k in obj) || obj[k] == null || obj[k] === '') failures.push(`запись ts=${ts}: нет обязательного поля "${k}"`)
|
||||
}
|
||||
if (obj.rule_kind === 'executable') {
|
||||
const why = enforcedByLive(obj.enforced_by)
|
||||
if (why) failures.push(`запись ts=${ts}: ${why}`)
|
||||
}
|
||||
}
|
||||
return { code: failures.length ? 1 : 0, checked: lines.length, after, failures }
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), 'lesson-gate-selftest-'))
|
||||
try {
|
||||
const led = path.join(tmp, 'ledger.jsonl')
|
||||
// Красный кролик: запись ПОСЛЕ отсечки без поля fix обязана покраснеть.
|
||||
writeFileSync(led, JSON.stringify({ ts: '2999-01-01', cause: 'x', rule: 'y', supersedes: '' }) + '\n', 'utf8')
|
||||
const r = evaluate(led, '2026-08-22', true)
|
||||
if (r.code !== 1) { console.error(`selftest FAILED: красный кролик прошёл (code=${r.code})`); return 1 }
|
||||
console.log('selftest ok: урок после отсечки без обязательного поля краснит')
|
||||
return 0
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const argv = process.argv.slice(2)
|
||||
if (argv.includes('--selftest')) process.exit(selftest())
|
||||
const { path: ledgerPath, explicit } = resolveLedger()
|
||||
const since = cutoff()
|
||||
const r = evaluate(ledgerPath, since, explicit)
|
||||
if (r.code === 2) { console.error(r.failures.join('\n')); process.exit(2) }
|
||||
if (r.skip) { console.log(`леджер: ${ledgerPath}\n${r.skip} (code 0)`); process.exit(0) }
|
||||
console.log(`леджер: ${ledgerPath}\nотсечка: ${since}; записей всего ${r.checked}, после отсечки ${r.after}`)
|
||||
if (r.failures.length) {
|
||||
console.error('ПРОВАЛЫ:')
|
||||
for (const f of r.failures) console.error(` - ${f}`)
|
||||
} else {
|
||||
console.log('уроки после отсечки соответствуют схеме (либо их нет)')
|
||||
}
|
||||
process.exit(r.code)
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -3,6 +3,7 @@ set -euo pipefail
|
||||
|
||||
ROOT="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
||||
cd "$ROOT"
|
||||
[ -f "$ROOT/.mnemazine/config.local.sh" ] && . "$ROOT/.mnemazine/config.local.sh"
|
||||
|
||||
fail=0
|
||||
|
||||
@@ -23,6 +24,15 @@ need_cmd git
|
||||
need_cmd node
|
||||
need_cmd npm
|
||||
|
||||
# Local extraction engines — single source of truth is mnemazine-local-engines.mjs
|
||||
# (rule 8). Preflight consumes its report (markitdown/whisper/ffmpeg/rg on PATH,
|
||||
# vision-ocr a repo-relative binary); it does NOT re-encode the five probes.
|
||||
if node scripts/mnemazine-local-engines.mjs --report; then
|
||||
ok "local engines present (markitdown, whisper, ffmpeg, rg, vision-ocr)"
|
||||
else
|
||||
bad "local engine(s) missing (see report above)"
|
||||
fi
|
||||
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
node_major="$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || echo 0)"
|
||||
if [ "$node_major" -ge 20 ]; then ok "node >=20"; else bad "node >=20 required"; fi
|
||||
@@ -34,23 +44,38 @@ fi
|
||||
|
||||
if [ "${MNEMAZINE_PREFLIGHT_SKIP_LLM:-0}" != "1" ]; then
|
||||
provider_hint="${MNEMAZINE_LLM:-}"
|
||||
if provider="$(node --input-type=module - "$provider_hint" <<'NODE'
|
||||
# Print the ACTUAL executor (provider_used), never the requested hint. A provider
|
||||
# substituted by fallback (requested deadcli, answered claude) is a preflight
|
||||
# FAILURE, not "ok": a live run pinned to a provider must get that provider.
|
||||
if node --input-type=module - "$provider_hint" <<'NODE'
|
||||
import { activeProvider, llmAvailable, llmJson } from './scripts/mnemazine-llm.mjs'
|
||||
const provider = process.argv[2] || activeProvider()
|
||||
if (!llmAvailable(provider)) process.exit(1)
|
||||
let requested = process.argv[2] || ''
|
||||
if (!requested) { try { requested = activeProvider() } catch { requested = '' } }
|
||||
const schema = {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['ok'],
|
||||
properties: { ok: { type: 'boolean' } }
|
||||
}
|
||||
await llmJson('Return {"ok":true}.', schema, { provider, timeoutMs: 120000 })
|
||||
console.log(provider)
|
||||
const opts = { provider: requested, timeoutMs: 120000 }
|
||||
let ok = false, err = ''
|
||||
try {
|
||||
if (!requested) throw new Error('no provider resolved from registry')
|
||||
if (!llmAvailable(requested)) throw new Error(`requested provider unavailable: ${requested}`)
|
||||
await llmJson('Return {"ok":true}.', schema, opts)
|
||||
const used = opts.provider_used || requested
|
||||
if (used === requested) ok = true
|
||||
else err = `provider substituted by fallback: requested ${requested}, answered ${used}`
|
||||
} catch (e) {
|
||||
err = String(e.message || e)
|
||||
}
|
||||
console.log(`provider_used=${opts.provider_used || '(none)'} requested=${requested || '(none)'}`)
|
||||
if (!ok) { console.error(err); process.exit(1) }
|
||||
NODE
|
||||
)"; then
|
||||
ok "llm provider available: $provider"
|
||||
then
|
||||
ok "llm provider available and not substituted: ${provider_hint:-<default>}"
|
||||
else
|
||||
bad "llm provider unavailable; set MNEMAZINE_LLM=codex or install/configure Claude/Codex"
|
||||
bad "llm provider unavailable or substituted by fallback (see provider_used line above)"
|
||||
fi
|
||||
else
|
||||
warn "llm provider check skipped"
|
||||
@@ -73,18 +98,25 @@ if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
||||
if git fetch origin main >/dev/null 2>&1; then
|
||||
head="$(git rev-parse HEAD)"
|
||||
remote="$(git rev-parse origin/main)"
|
||||
if [ "$head" = "$remote" ]; then ok "HEAD matches origin/main"; else bad "HEAD differs from origin/main"; fi
|
||||
if [ "$head" = "$remote" ]; then
|
||||
ok "HEAD matches origin/main"
|
||||
else
|
||||
read -r behind ahead < <(git rev-list --left-right --count origin/main...HEAD)
|
||||
if [ "$behind" = "0" ]; then ok "HEAD is $ahead local commit(s) ahead of origin/main"; else bad "HEAD is behind/diverged from origin/main"; fi
|
||||
fi
|
||||
else
|
||||
bad "could not fetch origin/main"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Public-release scan is NOT muted here (П10): preflight must exercise the same
|
||||
# gate a real publish would. If public-check reddens, that is a П07/П21 finding,
|
||||
# not a reason to restore the mute.
|
||||
npm run audit:local
|
||||
npm run protocol:desktop:dry-run
|
||||
|
||||
env_inbox="${MNEMAZINE_INBOX:-}"
|
||||
[ -f "$ROOT/.mnemazine/config.local.sh" ] && . "$ROOT/.mnemazine/config.local.sh"
|
||||
base_inbox="${env_inbox:-${MNEMAZINE_INBOX:-$HOME/Desktop/Mnemazine Inbox}}"
|
||||
nested_inbox="$base_inbox/mnemazine-inbox"
|
||||
base_count="$(active_count "$base_inbox")"
|
||||
|
||||
@@ -81,6 +81,9 @@ async function status(root = ROOT) {
|
||||
const failures = []
|
||||
if (!lastRun) failures.push('last-run.json missing')
|
||||
if (lastRun && !lastRun.ok) failures.push(lastRun.failure || (lastRun.failures || []).join('; ') || 'last run failed')
|
||||
// Смерть литерала ok:true наблюдаема и здесь: даже если поле ok врёт зелёным,
|
||||
// failed>0 означает, что прогон не чист. --require-ok обязан покраснеть.
|
||||
if (lastRun && Number(lastRun.failed || 0) > 0) failures.push(`last run had ${lastRun.failed} failed file(s)`)
|
||||
if (lastRun?.deep_required && !lastRun.deep) failures.push('strict run was not deep')
|
||||
if (lastRun?.deep_required && lastRun?.synthesize?.degraded) failures.push('deep synthesis degraded')
|
||||
if (lastRun?.deep_required && lastRun?.strict_archive_knowledge !== true) failures.push('strict archive gate missing')
|
||||
|
||||
+290
-130
@@ -1,52 +1,101 @@
|
||||
#!/usr/bin/env node
|
||||
// Provider-abstracted LLM bridge for Mnemazine. In Codex sessions, Codex is the
|
||||
// default engine; Claude is only a fallback when Codex is unavailable.
|
||||
// provider: MNEMAZINE_LLM = 'claude' | 'codex' (unset = Codex if present)
|
||||
// Both run as schema-instructed, web-capable headless agents. Default pipeline
|
||||
// never calls either — only the opt-in --deep path does.
|
||||
// Registry-driven LLM bridge for Mnemazine. There is no hard-coded list of
|
||||
// providers: the CLIs live as DATA in config/cli-registry.json (+ the gitignored
|
||||
// config/cli-registry.local.json overlay), and this module branches on the
|
||||
// declared CAPABILITY of the selected entry, never on a CLI name. Adding a CLI
|
||||
// (gemini, a local gemma, anything) is one JSON entry and zero edits here.
|
||||
//
|
||||
// Selection and validation come from mnemazine-cli-router.mjs; three schema
|
||||
// adapters are chosen by capability: json_schema_inline (claude --json-schema),
|
||||
// json_schema_file (codex exec --output-schema), json_in_prompt (universal).
|
||||
// The web-tool rule is general: a stage that needs web search only routes to a
|
||||
// carrier of the `web_search` capability; if none carries it the call fails with
|
||||
// a named cause — it never silently falls through to a CLI that cannot browse.
|
||||
//
|
||||
// Default pipeline never calls an LLM — only the opt-in --deep path does.
|
||||
import { spawnSync, spawn } from 'node:child_process'
|
||||
import { existsSync, readdirSync, promises as fs } from 'node:fs'
|
||||
import { existsSync, promises as fs } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { loadRegistry, orderCandidates, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
|
||||
|
||||
const PROGRESS_EVERY_MS = Number(process.env.MNEMAZINE_LLM_PROGRESS_EVERY_MS || '30000')
|
||||
const PROGRESS = process.env.MNEMAZINE_LLM_PROGRESS !== '0'
|
||||
const CONFIG_PROVIDER = process.env.MNEMAZINE_LLM || ''
|
||||
const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
|
||||
// Physical ceiling for a prompt delivered as an argv element (getconf ARG_MAX on
|
||||
// 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.
|
||||
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
|
||||
|
||||
function progress(label, message) {
|
||||
if (PROGRESS && label) process.stderr.write(`[llm] ${label} ${message}\n`)
|
||||
}
|
||||
|
||||
// Async process runner — non-blocking (unlike spawnSync), so many agent calls
|
||||
// can run concurrently as a swarm. Never rejects; returns a status/out/err.
|
||||
function runProc(bin, args, { input, timeoutMs, cwd } = {}) {
|
||||
function runProc(bin, args, { input, timeoutMs, cwd, label } = {}) {
|
||||
return new Promise(resolve => {
|
||||
let child
|
||||
try { child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'] }) }
|
||||
catch (e) { return resolve({ status: 1, stdout: '', stderr: String(e.message) }) }
|
||||
let out = '', err = '', killed = false
|
||||
const started = Date.now()
|
||||
progress(label, `start timeout=${timeoutMs || 0}ms`)
|
||||
const t = timeoutMs ? setTimeout(() => { killed = true; child.kill('SIGKILL') }, timeoutMs) : null
|
||||
const heartbeat = PROGRESS && label && PROGRESS_EVERY_MS > 0
|
||||
? setInterval(() => progress(label, `running ${Math.round((Date.now() - started) / 1000)}s`), PROGRESS_EVERY_MS)
|
||||
: null
|
||||
if (heartbeat) heartbeat.unref()
|
||||
function done(status, stdout, stderr) {
|
||||
if (t) clearTimeout(t)
|
||||
if (heartbeat) clearInterval(heartbeat)
|
||||
progress(label, `done status=${status} elapsed=${Math.round((Date.now() - started) / 1000)}s`)
|
||||
resolve({ status, stdout, stderr })
|
||||
}
|
||||
child.stdout.on('data', d => { out += d })
|
||||
child.stderr.on('data', d => { err += d })
|
||||
child.on('error', e => { if (t) clearTimeout(t); resolve({ status: 1, stdout: out, stderr: String(e.message) }) })
|
||||
child.on('close', code => { if (t) clearTimeout(t); resolve({ status: killed ? 124 : (code ?? 1), stdout: out, stderr: err }) })
|
||||
if (input != null) { child.stdin.on('error', () => {}); child.stdin.write(input); child.stdin.end() }
|
||||
child.on('error', e => done(1, out, String(e.message)))
|
||||
child.on('close', code => done(killed ? 124 : (code ?? 1), out, err))
|
||||
// stdin is always closed: a CLI that reads stdin by default hangs forever on
|
||||
// an open pipe when the prompt went in as an argument (no input here).
|
||||
child.stdin.on('error', () => {})
|
||||
if (input != null) child.stdin.write(input)
|
||||
child.stdin.end()
|
||||
})
|
||||
}
|
||||
|
||||
const CONFIG_PROVIDER = process.env.MNEMAZINE_LLM || ''
|
||||
const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
|
||||
const CODEX_BIN = process.env.MNEMAZINE_CODEX_BIN || '/Applications/Codex.app/Contents/Resources/codex'
|
||||
// --- registry (lazy, cached) --------------------------------------------------
|
||||
// Loaded on first real use, so the conservative local-only path never touches
|
||||
// it. A hidden/unreadable registry throws loudly here — no silent fall back to
|
||||
// old literals (that path is gone).
|
||||
let _registry
|
||||
function registry() {
|
||||
if (_registry) return _registry
|
||||
return (_registry = loadRegistry())
|
||||
}
|
||||
|
||||
const HOME = os.homedir()
|
||||
function getEntry(provider) {
|
||||
const entry = registry()[provider]
|
||||
if (!entry) throw new Error(`provider ${provider} not in registry`)
|
||||
return entry
|
||||
}
|
||||
|
||||
// Resolve the Claude CLI independently of how it was installed (npm global,
|
||||
// standalone installer, Homebrew, Claude Desktop, or the VSCode extension). Tries,
|
||||
// in order: explicit env -> login-shell PATH (respects the user's real install)
|
||||
// -> common absolute locations -> newest VSCode extension binary. Cached.
|
||||
let _claudeBin
|
||||
let _defaultProvider
|
||||
function resolveClaudeBin() {
|
||||
if (_claudeBin !== undefined) return _claudeBin
|
||||
if (process.env.MNEMAZINE_CLAUDE_BIN) return (_claudeBin = process.env.MNEMAZINE_CLAUDE_BIN)
|
||||
// Login shell: picks up however the user installed claude (Desktop/npm/etc.).
|
||||
const shell = process.env.SHELL || '/bin/zsh'
|
||||
const viaShell = spawnSync(shell, ['-lic', 'command -v claude'], { encoding: 'utf8' }).stdout || ''
|
||||
const shellHit = viaShell.trim().split('\n').pop()
|
||||
if (shellHit && existsSync(shellHit)) return (_claudeBin = shellHit)
|
||||
const candidates = [
|
||||
function providerChain(dataClass, capabilities) {
|
||||
const { candidates } = orderCandidates(registry(), { dataClass, capabilities })
|
||||
return candidates.map(c => c.name)
|
||||
}
|
||||
|
||||
// --- binary resolution (generic, per invoke[0]) -------------------------------
|
||||
// The binary is invoke[0], resolved via env override (MNEMAZINE_<NAME>_BIN),
|
||||
// then the login shell (however the user installed it), then a small table of
|
||||
// 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',
|
||||
@@ -54,17 +103,21 @@ function resolveClaudeBin() {
|
||||
path.join(HOME, '.npm-global/bin/claude'),
|
||||
'/Applications/Claude.app/Contents/Resources/claude'
|
||||
]
|
||||
for (const c of candidates) if (existsSync(c)) return (_claudeBin = c)
|
||||
// Newest VSCode extension native binary, if present.
|
||||
const extDir = path.join(HOME, '.vscode/extensions')
|
||||
try {
|
||||
const dirs = readdirSync(extDir).filter(d => d.startsWith('anthropic.claude-code-')).sort()
|
||||
for (const d of dirs.reverse()) {
|
||||
const bin = path.join(extDir, d, 'resources/native-binary/claude')
|
||||
if (existsSync(bin)) return (_claudeBin = bin)
|
||||
}
|
||||
} catch {}
|
||||
return (_claudeBin = 'claude') // last resort: bare PATH lookup at spawn time
|
||||
}
|
||||
const _binCache = {}
|
||||
function envBinKey(binName) {
|
||||
return `MNEMAZINE_${binName.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_BIN`
|
||||
}
|
||||
function resolveBin(binName) {
|
||||
if (_binCache[binName] !== undefined) return _binCache[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) {
|
||||
@@ -73,13 +126,22 @@ function binExists(bin) {
|
||||
return which.status === 0 && Boolean(which.stdout.trim())
|
||||
}
|
||||
|
||||
function requireBin(provider, entry) {
|
||||
const bin = resolveBin(entry.invoke[0])
|
||||
if (!binExists(bin)) throw new Error(`${provider}: binary not found (${entry.invoke[0]}); set ${envBinKey(entry.invoke[0])}`)
|
||||
return bin
|
||||
}
|
||||
|
||||
// --- provider resolution ------------------------------------------------------
|
||||
let _defaultProvider
|
||||
export function defaultProvider() {
|
||||
if (_defaultProvider) return _defaultProvider
|
||||
if (CONFIG_PROVIDER) return CONFIG_PROVIDER
|
||||
const claudeBin = resolveClaudeBin()
|
||||
if (binExists(CODEX_BIN)) return (_defaultProvider = 'codex')
|
||||
if (binExists(claudeBin) && claudeUsable(claudeBin)) return (_defaultProvider = 'claude')
|
||||
return (_defaultProvider = 'claude')
|
||||
if (CONFIG_PROVIDER) return (_defaultProvider = CONFIG_PROVIDER) // owner pin (config.local.sh)
|
||||
// Unset: take the chain head for the pipeline's own material, preferring an
|
||||
// available binary. Production pins the provider, so unset only happens in
|
||||
// tests/CI where no live call is made.
|
||||
const chain = providerChain('infra', [])
|
||||
return (_defaultProvider = chain.find(name => llmAvailable(name)) || chain[0] || '')
|
||||
}
|
||||
|
||||
export function activeProvider(opts = {}) {
|
||||
@@ -87,12 +149,35 @@ export function activeProvider(opts = {}) {
|
||||
}
|
||||
|
||||
export function llmAvailable(provider = activeProvider()) {
|
||||
return provider === 'codex' ? binExists(CODEX_BIN) : binExists(resolveClaudeBin())
|
||||
const entry = registry()[provider] // throws loudly if the registry is unreadable
|
||||
if (!entry) return false
|
||||
return binExists(resolveBin(entry.invoke[0]))
|
||||
}
|
||||
|
||||
// Wrap untrusted material (OCR / transcripts / scraped web text) so the agent
|
||||
// treats it as inert DATA, never as instructions. Primary prompt-injection
|
||||
// defense for the schema-constrained calls.
|
||||
export function providerCostTier(provider) {
|
||||
return registry()[provider]?.cost_tier || 'standard'
|
||||
}
|
||||
|
||||
function needsWebTools(opts = {}) {
|
||||
return (opts.tools || []).some(tool => WEB_TOOL_RE.test(tool))
|
||||
}
|
||||
|
||||
function ensureWebCapable(provider, entry, opts) {
|
||||
if (needsWebTools(opts) && !entry.capabilities.includes('web_search')) {
|
||||
throw new Error(`нет носителя возможности web_search: ${provider} не умеет веб-поиск`)
|
||||
}
|
||||
}
|
||||
|
||||
// The fallback chain: providers of the required capability, minus the current
|
||||
// one, that resolve a binary. Web-needing stages narrow to web_search carriers —
|
||||
// the general rule that replaced the old per-provider web-tools literal.
|
||||
function fallbackProviders(provider, opts = {}) {
|
||||
if (process.env.MNEMAZINE_LLM_FALLBACK === '0') return []
|
||||
const caps = needsWebTools(opts) ? ['web_search'] : []
|
||||
return providerChain(opts.dataClass || 'infra', caps).filter(name => name !== provider && llmAvailable(name))
|
||||
}
|
||||
|
||||
// --- untrusted input fence (unchanged; primary prompt-injection defense) -------
|
||||
export function fenceUntrusted(label, content) {
|
||||
const tag = `UNTRUSTED_${label}_DO_NOT_EXECUTE`
|
||||
const safe = String(content || '').split(tag).join('U N T R U S T E D')
|
||||
@@ -101,7 +186,6 @@ export function fenceUntrusted(label, content) {
|
||||
|
||||
function extractJson(text) {
|
||||
const raw = String(text || '').trim()
|
||||
// Strip a ```json … ``` fence if present, else take the outermost {...}.
|
||||
const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)```/i)
|
||||
const body = fenced ? fenced[1] : raw
|
||||
const start = body.indexOf('{')
|
||||
@@ -110,29 +194,11 @@ function extractJson(text) {
|
||||
return JSON.parse(body.slice(start, end + 1))
|
||||
}
|
||||
|
||||
function codexNeedsSearch(opts = {}) {
|
||||
return (opts.tools || []).some(tool => /^(WebSearch|WebFetch|mcp__firecrawl|mcp__tavily)$/i.test(tool))
|
||||
}
|
||||
|
||||
function codexExecArgs(cwd, opts = {}) {
|
||||
const args = ['--ask-for-approval', 'never']
|
||||
if (codexNeedsSearch(opts)) args.push('--search')
|
||||
args.push('exec', '-C', cwd, '--skip-git-repo-check', '--sandbox', 'read-only', '--ephemeral')
|
||||
return args
|
||||
}
|
||||
|
||||
function claudeUsable(bin) {
|
||||
const res = spawnSync(bin, ['-p', '--output-format', 'json'], {
|
||||
input: 'Return only {"ok":true}.',
|
||||
encoding: 'utf8',
|
||||
timeout: 15000
|
||||
})
|
||||
if (res.status !== 0) return false
|
||||
try {
|
||||
const envelope = JSON.parse(res.stdout || '{}')
|
||||
if (envelope?.is_error) return false
|
||||
} catch {}
|
||||
return true
|
||||
// --output-format json wraps the turn as { result: '<text>', ... } (claude). For
|
||||
// codex/kimi stdout is already plain text. Unwrap generically.
|
||||
function unwrap(stdout) {
|
||||
try { const e = JSON.parse(stdout); if (e && typeof e.result === 'string') return e.result } catch {}
|
||||
return stdout
|
||||
}
|
||||
|
||||
function strictOutputSchema(schema) {
|
||||
@@ -153,6 +219,28 @@ function strictOutputSchema(schema) {
|
||||
return out
|
||||
}
|
||||
|
||||
function assertSchema(value, schema, where = '$') {
|
||||
if (!schema || typeof schema !== 'object') return
|
||||
if ('const' in schema && value !== schema.const) throw new Error(`${where}: expected constant value`)
|
||||
if (schema.type === 'object') {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${where}: expected object`)
|
||||
for (const key of schema.required || []) if (!(key in value)) throw new Error(`${where}.${key}: required`)
|
||||
const properties = schema.properties || {}
|
||||
if (schema.additionalProperties === false) for (const key of Object.keys(value)) if (!(key in properties)) throw new Error(`${where}.${key}: unexpected`)
|
||||
for (const [key, child] of Object.entries(properties)) if (key in value) assertSchema(value[key], child, `${where}.${key}`)
|
||||
}
|
||||
if (schema.type === 'array') {
|
||||
if (!Array.isArray(value)) throw new Error(`${where}: expected array`)
|
||||
if (schema.minItems && value.length < schema.minItems) throw new Error(`${where}: too few items`)
|
||||
value.forEach((item, index) => assertSchema(item, schema.items, `${where}[${index}]`))
|
||||
}
|
||||
if (schema.type === 'string') {
|
||||
if (typeof value !== 'string') throw new Error(`${where}: expected string`)
|
||||
if (schema.minLength && value.length < schema.minLength) throw new Error(`${where}: empty string`)
|
||||
}
|
||||
if (schema.type === 'boolean' && typeof value !== 'boolean') throw new Error(`${where}: expected boolean`)
|
||||
}
|
||||
|
||||
function procError(label, res) {
|
||||
const stderr = String(res.stderr || '').trim()
|
||||
if (stderr) return `${label} failed (status ${res.status}): ${stderr.slice(-400)}`
|
||||
@@ -161,80 +249,152 @@ function procError(label, res) {
|
||||
return `${label} failed (status ${res.status}): empty stderr/stdout`
|
||||
}
|
||||
|
||||
// --- Codex backend (headless pattern: --output-schema + -o) ---
|
||||
async function codexJsonCall(prompt, schema, opts) {
|
||||
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
|
||||
const work = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-codex-'))
|
||||
// Prompt goes on stdin when the CLI declares stdin_prompt; otherwise as the last
|
||||
// argv element, bounded by ARG_MAX (never truncated — over the ceiling is a
|
||||
// named failure that moves to the next CLI in the chain).
|
||||
function deliverPrompt(entry, args, prompt) {
|
||||
if (entry.capabilities.includes('stdin_prompt')) return { args, input: prompt }
|
||||
const bytes = [...args, prompt].reduce((n, a) => n + Buffer.byteLength(String(a)) + 1, 0)
|
||||
if (bytes > ARG_MAX) throw new Error(`prompt exceeds ARG_MAX (${bytes} > ${ARG_MAX}); argv delivery impossible`)
|
||||
return { args: [...args, prompt], input: undefined }
|
||||
}
|
||||
|
||||
// Tool enabling is per schema-mechanism adapter: the inline adapter (claude)
|
||||
// grants tools via --allowedTools; the file adapter (codex) turns on web search
|
||||
// with the top-level --search inserted before `exec`. A new CLI using an
|
||||
// existing mechanism inherits this; a genuinely new mechanism is a new adapter.
|
||||
function withAllowedTools(args, opts) {
|
||||
const tools = opts.tools || []
|
||||
return tools.length ? [...args, '--allowedTools', tools.join(',')] : args
|
||||
}
|
||||
function insertSearch(args, entry, opts) {
|
||||
if (!needsWebTools(opts) || !entry.capabilities.includes('web_search')) return args
|
||||
const a = [...args]
|
||||
const i = a.indexOf('exec')
|
||||
if (i >= 0) a.splice(i, 0, '--search'); else a.unshift('--search')
|
||||
return a
|
||||
}
|
||||
function insertCwd(args, cwd) {
|
||||
const a = [...args]
|
||||
const i = a.indexOf('exec')
|
||||
if (i >= 0) a.splice(i + 1, 0, '-C', cwd); else a.push('-C', cwd)
|
||||
return a
|
||||
}
|
||||
|
||||
// --- schema adapters (chosen by capability) -----------------------------------
|
||||
async function inlineSchemaJson(provider, entry, prompt, schema, opts) {
|
||||
const bin = requireBin(provider, entry)
|
||||
let args = withAllowedTools(entry.invoke.slice(1), opts)
|
||||
args = [...args, '--json-schema', JSON.stringify(strictOutputSchema(schema))]
|
||||
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` })
|
||||
if (res.status !== 0) throw new Error(procError(`${provider} json`, res))
|
||||
return extractJson(unwrap(res.stdout))
|
||||
}
|
||||
|
||||
async function fileSchemaJson(provider, entry, prompt, schema, opts) {
|
||||
const bin = requireBin(provider, entry)
|
||||
const work = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-cli-'))
|
||||
const cwd = opts.cwd || work
|
||||
const schemaFile = path.join(work, 'schema.json')
|
||||
const outFile = path.join(work, 'out.json')
|
||||
const promptFile = path.join(work, 'prompt.md')
|
||||
await fs.writeFile(schemaFile, JSON.stringify(strictOutputSchema(schema)), { encoding: 'utf8', mode: 0o600 })
|
||||
await fs.writeFile(promptFile, prompt, { encoding: 'utf8', mode: 0o600 })
|
||||
try {
|
||||
const res = await runProc(CODEX_BIN, [
|
||||
...codexExecArgs(cwd, opts),
|
||||
'--output-schema', schemaFile, '-o', outFile, '-'
|
||||
], { input: await fs.readFile(promptFile, 'utf8'), timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||
if (res.status !== 0) throw new Error(procError('codex exec', res))
|
||||
let args = insertSearch(entry.invoke.slice(1), entry, opts)
|
||||
args = insertCwd(args, cwd)
|
||||
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' : ''}` })
|
||||
if (res.status !== 0) throw new Error(procError(`${provider} exec`, res))
|
||||
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
|
||||
if (!raw.trim()) throw new Error('codex returned empty output')
|
||||
try { return JSON.parse(raw) } catch (err) { throw new Error(`codex returned non-JSON: ${err.message}; head: ${raw.slice(0, 200)}`) }
|
||||
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)}`) }
|
||||
} finally {
|
||||
await fs.rm(work, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
// --- Claude backend (headless `claude -p`, JSON instructed in-prompt) ---
|
||||
// No --output-schema in Claude, so the schema is embedded and the result parsed.
|
||||
// Tools are opt-in via opts.tools (default none = no network); enrich/verify
|
||||
// pass WebSearch/WebFetch (+ MCP) to let Claude research with available tools.
|
||||
// Never uses the permission-bypass flag (constitution): unpermitted tools
|
||||
// simply do not run in -p mode.
|
||||
async function claudeJsonCall(prompt, schema, opts) {
|
||||
const bin = resolveClaudeBin()
|
||||
if (!binExists(bin)) throw new Error(`claude binary not found (tried env, PATH, common installs, VSCode): set MNEMAZINE_CLAUDE_BIN`)
|
||||
const tools = opts.tools || []
|
||||
const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(schema)}`
|
||||
const args = ['-p', '--output-format', 'json']
|
||||
if (tools.length) args.push('--allowedTools', tools.join(','))
|
||||
const res = await runProc(bin, args, { input: full, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||
if (res.status !== 0) throw new Error(procError('claude -p', res))
|
||||
// --output-format json wraps the turn: { type:'result', result:'<text>', ... }
|
||||
let envelope
|
||||
try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
|
||||
const text = envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout
|
||||
return extractJson(text)
|
||||
async function inPromptJson(provider, entry, prompt, schema, opts) {
|
||||
const bin = requireBin(provider, entry)
|
||||
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 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))
|
||||
const output = extractJson(unwrap(res.stdout))
|
||||
assertSchema(output, strictOutputSchema(schema))
|
||||
return output
|
||||
}
|
||||
|
||||
// One schema-instructed call. Returns the parsed/validated-ish JSON object or
|
||||
// throws (callers degrade gracefully). provider via opts.provider or MNEMAZINE_LLM.
|
||||
async function jsonOnce(provider, prompt, schema, opts) {
|
||||
const entry = getEntry(provider)
|
||||
ensureWebCapable(provider, entry, opts)
|
||||
const adapter = pickSchemaAdapter(entry)
|
||||
if (adapter === 'json_schema_file') return fileSchemaJson(provider, entry, prompt, schema, opts)
|
||||
if (adapter === 'json_schema_inline') return inlineSchemaJson(provider, entry, prompt, schema, opts)
|
||||
return inPromptJson(provider, entry, prompt, schema, opts) // json_in_prompt (or a CLI declaring no schema mechanism)
|
||||
}
|
||||
|
||||
// One schema-instructed call. Returns the parsed JSON object or throws (callers
|
||||
// degrade gracefully). Provider via opts.provider or MNEMAZINE_LLM; on failure
|
||||
// walks the capability-filtered fallback chain.
|
||||
export async function llmJson(prompt, schema, opts = {}) {
|
||||
const provider = activeProvider(opts)
|
||||
return provider === 'codex' ? codexJsonCall(prompt, schema, opts) : claudeJsonCall(prompt, schema, opts)
|
||||
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 call (no schema) — used for vision/extraction fallback where the
|
||||
// agent reads a local file (image/PDF) and transcribes it. Tools opt-in; for
|
||||
// file reading pass tools:['Read']. Returns raw text. Claude primary; Codex at
|
||||
// parity (runs in the file's directory so it can open it).
|
||||
export async function llmText(prompt, opts = {}) {
|
||||
const provider = activeProvider(opts)
|
||||
if (provider === 'codex') {
|
||||
if (!binExists(CODEX_BIN)) throw new Error(`codex binary not found: ${CODEX_BIN}`)
|
||||
const res = await runProc(CODEX_BIN, [
|
||||
...codexExecArgs(opts.cwd || process.cwd(), opts), '-'
|
||||
], { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||
if (res.status !== 0) throw new Error(procError('codex exec', res))
|
||||
// --- plain-text path (no schema; vision/extraction fallback) ------------------
|
||||
async function textOnce(provider, prompt, opts) {
|
||||
const entry = getEntry(provider)
|
||||
ensureWebCapable(provider, entry, opts)
|
||||
const bin = requireBin(provider, entry)
|
||||
const adapter = pickSchemaAdapter(entry)
|
||||
if (adapter === 'json_schema_file') {
|
||||
let args = insertSearch(entry.invoke.slice(1), entry, opts)
|
||||
args = insertCwd(args, opts.cwd || process.cwd())
|
||||
args = [...args, '-']
|
||||
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))
|
||||
return String(res.stdout || '').trim()
|
||||
}
|
||||
const bin = resolveClaudeBin()
|
||||
if (!binExists(bin)) throw new Error('claude binary not found: set MNEMAZINE_CLAUDE_BIN')
|
||||
const args = ['-p', '--output-format', 'json']
|
||||
if (opts.tools?.length) args.push('--allowedTools', opts.tools.join(','))
|
||||
const res = await runProc(bin, args, { input: prompt, timeoutMs: opts.timeoutMs || TIMEOUT_MS })
|
||||
if (res.status !== 0) throw new Error(procError('claude -p', res))
|
||||
let envelope
|
||||
try { envelope = JSON.parse(res.stdout) } catch { envelope = null }
|
||||
return (envelope && typeof envelope.result === 'string' ? envelope.result : res.stdout).trim()
|
||||
// Flat-invoke CLI (claude inline / kimi in-prompt): tools via --allowedTools
|
||||
// only where the mechanism supports it (inline adapter).
|
||||
let args = entry.invoke.slice(1)
|
||||
if (adapter === 'json_schema_inline') args = withAllowedTools(args, opts)
|
||||
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` })
|
||||
if (res.status !== 0) throw new Error(procError(`${provider} text`, res))
|
||||
return unwrap(res.stdout).trim()
|
||||
}
|
||||
|
||||
export async function llmText(prompt, opts = {}) {
|
||||
const provider = activeProvider(opts)
|
||||
const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
|
||||
let lastError
|
||||
for (const candidate of chain) {
|
||||
try {
|
||||
const result = await textOnce(candidate, prompt, opts)
|
||||
opts.provider_used = candidate // actual executor, so a fallback is never silent
|
||||
return result
|
||||
}
|
||||
catch (error) {
|
||||
lastError = error
|
||||
progress(opts.label || 'text', `fallback ${candidate}: ${String(error.message || error).slice(0, 160)}`)
|
||||
}
|
||||
}
|
||||
throw lastError || new Error('no provider available for llmText')
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env node
|
||||
// Single source of truth about local extraction engines (rule 8). The five
|
||||
// presence checks — vision-ocr, markitdown, whisper, ffmpeg, rg — live HERE and
|
||||
// nowhere else: mnemazine-run.mjs and mnemazine-live-preflight.sh consume this
|
||||
// module instead of re-encoding `command -v markitdown` in their own words.
|
||||
//
|
||||
// The point this module exists to serve (П10): distinguish «движка нет» from
|
||||
// «движок ничего не нашёл». engineStatus() answers ONLY presence; a present
|
||||
// engine that returns empty text is the caller's «не нашёл», not this module's
|
||||
// «missing». That split is what lets the runner stop instead of silently
|
||||
// reaching for the cloud.
|
||||
import { accessSync, constants } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
// ROOT is resolved from the module's own location (so vision-ocr is found
|
||||
// regardless of cwd), overridable by MNEMAZINE_ROOT to match the runner.
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
// kind: 'binary-path' → a file at a repo-relative path (survives PATH edits);
|
||||
// 'path-command' → resolved via PATH exactly as spawnSync(cmd) would (execvp).
|
||||
// required_for: which extraction purposes need this engine (documentation + report).
|
||||
export const ENGINES = {
|
||||
'vision-ocr': { kind: 'binary-path', path: '.mnemazine/bin/vision-ocr', required_for: ['image', 'video-frames'] },
|
||||
markitdown: { kind: 'path-command', probe: 'markitdown', required_for: ['pdf', 'docx', 'pptx', 'xlsx', 'html'] },
|
||||
whisper: { kind: 'path-command', probe: 'whisper', required_for: ['video-audio'] },
|
||||
ffmpeg: { kind: 'path-command', probe: 'ffmpeg', required_for: ['video'] },
|
||||
rg: { kind: 'path-command', probe: 'rg', required_for: ['audit', 'search'] }
|
||||
}
|
||||
|
||||
// Same resolution as spawnSync(cmd) with no shell: scan process PATH for an
|
||||
// executable of that name. NOT a login shell — the runner spawns directly, so a
|
||||
// login-shell-only PATH would over-report presence the runner can't actually use.
|
||||
function onPath(cmd) {
|
||||
for (const dir of (process.env.PATH || '').split(path.delimiter)) {
|
||||
if (!dir) continue
|
||||
try { accessSync(path.join(dir, cmd), constants.X_OK); return true } catch { /* next dir */ }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// 'present' | 'missing' — never a third value, never a throw for a known engine.
|
||||
export function engineStatus(name) {
|
||||
const engine = ENGINES[name]
|
||||
if (!engine) throw new Error(`unknown local engine: ${name}`)
|
||||
if (engine.kind === 'binary-path') {
|
||||
try { accessSync(path.join(ROOT, engine.path), constants.X_OK); return 'present' } catch { return 'missing' }
|
||||
}
|
||||
return onPath(engine.probe) ? 'present' : 'missing'
|
||||
}
|
||||
|
||||
// The subset of `list` that is missing. Empty array ⇒ every required engine is
|
||||
// on hand. Callers gate on `.length`, never on presence-by-name in their own code.
|
||||
export function requireEngines(list) {
|
||||
return list.filter(name => engineStatus(name) === 'missing')
|
||||
}
|
||||
|
||||
// --- CLI: report / selftest ---------------------------------------------------
|
||||
function report(asJson) {
|
||||
const rows = Object.keys(ENGINES).map(name => ({
|
||||
name, kind: ENGINES[name].kind, status: engineStatus(name), required_for: ENGINES[name].required_for
|
||||
}))
|
||||
if (asJson) console.log(JSON.stringify(rows))
|
||||
else for (const r of rows) console.log(`${r.status === 'present' ? 'ok' : 'fail'} ${r.name} ${r.status}`)
|
||||
return rows.every(r => r.status === 'present') ? 0 : 1
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
const assert = (cond, msg) => { if (!cond) throw new Error(`selftest: ${msg}`) }
|
||||
for (const name of Object.keys(ENGINES)) assert(['present', 'missing'].includes(engineStatus(name)), `${name} status enum`)
|
||||
let threw = false
|
||||
try { engineStatus('mnemazine-no-such-engine-9000') } catch { threw = true }
|
||||
assert(threw, 'unknown engine throws, never silent missing')
|
||||
const missing = requireEngines(Object.keys(ENGINES))
|
||||
assert(Array.isArray(missing) && missing.every(n => engineStatus(n) === 'missing'), 'requireEngines is the missing subset')
|
||||
console.log(JSON.stringify({ ok: true, selftest: 'local-engines', engines: Object.keys(ENGINES) }))
|
||||
return 0
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = process.argv.slice(2)
|
||||
if (args.includes('--selftest')) return selftest()
|
||||
if (args.includes('--json')) return report(true)
|
||||
return report(false) // --report or bare
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exit(main())
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
#!/usr/bin/env node
|
||||
// Machine-class barrier (П24). The router (П04) answers "which CLI may SEE a
|
||||
// class"; this gate answers "which MACHINE may PROCESS a note" — the second
|
||||
// border, same single truth: config/data-classes.json (rule 8 of the method).
|
||||
//
|
||||
// A note's class is the MAX over the order among all fired rules (strict wins):
|
||||
// 1. explicit `data_class:` in frontmatter — may RAISE, never LOWER
|
||||
// 2. by_section[section] — section field or parent-dir name
|
||||
// 3. source inheritance — projects∈by_project | source∈by_source_pattern
|
||||
// No rule fired: a KNOWN section (the section name is a real directory in the
|
||||
// note's own path) → text (ordinary material, VPS-ok); an UNKNOWN/new section
|
||||
// → exit 2 (a new section can't silently become sendable); broken/absent
|
||||
// frontmatter → default (personal) → the batch reddens with 1.
|
||||
//
|
||||
// Exit codes:
|
||||
// --classify <file> 0 class printed with the firing rule · 2 undeterminable
|
||||
// --batch <manifest> --target 0 clean · 1 a class blocked on target (names first) · 2 undeterminable/empty
|
||||
// --selftest 0 fixtures pass · 1 a fixture disagrees
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
export const TAXONOMY_PATH = path.join(HERE, '..', 'config', 'data-classes.json')
|
||||
const FIXTURES = path.join(HERE, '..', 'tests', 'fixtures', 'data-classes')
|
||||
|
||||
export function loadTaxonomy(file = TAXONOMY_PATH) {
|
||||
const t = JSON.parse(readFileSync(file, 'utf8'))
|
||||
for (const k of ['order', 'classes', 'by_section', 'by_project', 'by_source_pattern', 'default']) {
|
||||
if (!(k in t)) throw new Error(`config/data-classes.json: нет поля ${k}`)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
function unquote(s) { return s.replace(/^["']/, '').replace(/["']$/, '') }
|
||||
|
||||
// Minimal frontmatter reader: the block between the first `---` and the next
|
||||
// `---`. Absent block or no closing fence → not ok (fail-closed to default).
|
||||
export function parseFrontmatter(text) {
|
||||
const lines = text.split('\n')
|
||||
if (lines[0].trim() !== '---') return { ok: false }
|
||||
let end = -1
|
||||
for (let i = 1; i < lines.length; i++) { if (lines[i].trim() === '---') { end = i; break } }
|
||||
if (end === -1) return { ok: false }
|
||||
const fields = { projects: [], sources: [] }
|
||||
let listKey = null
|
||||
for (const raw of lines.slice(1, end)) {
|
||||
const line = raw.replace(/\s+$/, '')
|
||||
if (listKey && /^\s*-\s+/.test(line)) { fields[listKey].push(unquote(line.replace(/^\s*-\s+/, '').trim())); continue }
|
||||
const m = line.match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.*)$/)
|
||||
if (!m) { listKey = null; continue }
|
||||
const key = m[1]; const val = m[2].trim(); listKey = null
|
||||
if (val === '') { if (key === 'projects' || key === 'sources') listKey = key; continue }
|
||||
if ((key === 'projects' || key === 'sources') && val.startsWith('[')) {
|
||||
fields[key] = val.replace(/^\[/, '').replace(/\]$/, '').split(',').map(s => unquote(s.trim())).filter(Boolean)
|
||||
continue
|
||||
}
|
||||
if (key === 'data_class') fields.data_class = unquote(val)
|
||||
else if (key === 'section') fields.section = unquote(val)
|
||||
else if (key === 'source') fields.source = unquote(val)
|
||||
}
|
||||
return { ok: true, fields }
|
||||
}
|
||||
|
||||
const firstSegment = sec => sec.split('/')[0].trim()
|
||||
|
||||
function bySectionMatch(sec, taxonomy) {
|
||||
for (const key of Object.keys(taxonomy.by_section)) {
|
||||
if (sec === key || firstSegment(sec) === key) return { klass: taxonomy.by_section[key], key }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function sourceInherit(fields, taxonomy) {
|
||||
const fired = []
|
||||
for (const proj of fields.projects || []) {
|
||||
if (taxonomy.by_project[proj]) fired.push({ klass: taxonomy.by_project[proj], rule: `by_project «${proj}»` })
|
||||
}
|
||||
const srcs = [fields.source, ...(fields.sources || [])].filter(Boolean)
|
||||
for (const [pat, klass] of Object.entries(taxonomy.by_source_pattern)) {
|
||||
const re = new RegExp(pat)
|
||||
if (srcs.some(s => re.test(s))) fired.push({ klass, rule: `by_source_pattern «${pat}»` })
|
||||
}
|
||||
return fired
|
||||
}
|
||||
|
||||
// Pure classification. `sec` is the resolved section; `knownSections` is a Set
|
||||
// of names treated as existing vault sections. Returns { klass, rule } or
|
||||
// { undetermined: true, section } for a new/unknown section.
|
||||
export function classifyNote(fields, sec, taxonomy, knownSections) {
|
||||
const rank = k => taxonomy.order.indexOf(k)
|
||||
const fired = []
|
||||
if (fields.data_class) {
|
||||
if (!taxonomy.classes[fields.data_class]) return { undetermined: true, section: sec, badClass: fields.data_class }
|
||||
fired.push({ klass: fields.data_class, rule: 'data_class (явное поле)' })
|
||||
}
|
||||
if (sec) { const m = bySectionMatch(sec, taxonomy); if (m) fired.push({ klass: m.klass, rule: `by_section «${m.key}»` }) }
|
||||
for (const r of sourceInherit(fields, taxonomy)) fired.push(r)
|
||||
|
||||
if (fired.length) {
|
||||
fired.sort((a, b) => rank(b.klass) - rank(a.klass)) // max by order — strict wins
|
||||
return { klass: fired[0].klass, rule: fired[0].rule }
|
||||
}
|
||||
if (sec) {
|
||||
if (knownSections.has(firstSegment(sec))) return { klass: 'text', rule: `известный раздел «${firstSegment(sec)}» без спец-правила → text` }
|
||||
return { undetermined: true, section: sec } // new/unknown section → exit 2
|
||||
}
|
||||
return { klass: taxonomy.default, rule: `default (${taxonomy.default})` }
|
||||
}
|
||||
|
||||
// A note's "known sections" are self-located: the directory names in its own
|
||||
// path. A section is real iff the note physically lives inside a dir of that
|
||||
// name — no config, no hardcoded vault name (public-release safe). Selftest
|
||||
// injects a fixed set so it stays hermetic. `sec` defaults to the parent dir.
|
||||
export function classifyFile(filePath, taxonomy, knownOverride) {
|
||||
let text
|
||||
try { text = readFileSync(filePath, 'utf8') } catch { return { undetermined: true, section: null, reason: `файл не прочитан: ${filePath}` } }
|
||||
const fm = parseFrontmatter(text)
|
||||
if (!fm.ok) return { klass: taxonomy.default, rule: `битый/отсутствующий frontmatter → default (${taxonomy.default})` }
|
||||
const abs = path.resolve(filePath)
|
||||
const sec = fm.fields.section || path.basename(path.dirname(abs))
|
||||
const known = knownOverride || new Set(path.dirname(abs).split(path.sep))
|
||||
return classifyNote(fm.fields, sec, taxonomy, known)
|
||||
}
|
||||
|
||||
// --- CLI modes ---------------------------------------------------------------
|
||||
|
||||
function runClassify(file, taxonomy) {
|
||||
const res = classifyFile(file, taxonomy)
|
||||
if (res.undetermined) {
|
||||
console.error(`НЕ ОПРЕДЕЛЁН: ${res.badClass ? `неизвестный класс «${res.badClass}»` : `раздел вне таксономии «${res.section}»`} (${path.basename(file)})`)
|
||||
return 2
|
||||
}
|
||||
console.log(`${res.klass} (правило: ${res.rule})`)
|
||||
return 0
|
||||
}
|
||||
|
||||
function runBatch(manifest, target, taxonomy) {
|
||||
if (!['mac', 'vps'].includes(target)) { console.error(`--target должен быть mac|vps, получено: ${target}`); return 2 }
|
||||
let raw
|
||||
try { raw = readFileSync(manifest, 'utf8') } catch { console.error(`манифест не прочитан: ${manifest}`); return 2 }
|
||||
const files = raw.split('\n').map(s => s.trim()).filter(Boolean)
|
||||
if (!files.length) { console.error('пустой манифест — 0 нот, это отказ, а не «проверено 0 ✓»'); return 2 }
|
||||
|
||||
const undetermined = []
|
||||
const blocked = []
|
||||
for (const f of files) {
|
||||
const res = classifyFile(f, taxonomy)
|
||||
if (res.undetermined) { undetermined.push({ f, res }); continue }
|
||||
if (!taxonomy.classes[res.klass].machines.includes(target)) blocked.push({ f, res })
|
||||
}
|
||||
if (undetermined.length) {
|
||||
const { f, res } = undetermined[0]
|
||||
console.error(`ОТКАЗ (2): класс не определяется — ${res.badClass ? `неизвестный класс «${res.badClass}»` : `раздел вне таксономии «${res.section}»`} в ${f}`)
|
||||
return 2
|
||||
}
|
||||
if (blocked.length) {
|
||||
const { f, res } = blocked[0]
|
||||
console.error(`ОТКАЗ (1): ${f} — класс ${res.klass} (${res.rule}) не разрешён на ${target} (разрешено: ${taxonomy.classes[res.klass].machines.join(',')})`)
|
||||
console.error(`всего заблокировано: ${blocked.length} из ${files.length}`)
|
||||
return 1
|
||||
}
|
||||
console.log(`чисто: ${files.length} нот, все разрешены на ${target}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
// --- selftest (hermetic: injected knownSections, no disk beyond fixtures) -----
|
||||
function selftest(taxonomy) {
|
||||
const known = new Set(['08 AI и Инструменты', '01 Право и Юриспруденция', '02 Здоровье'])
|
||||
const cf = f => classifyFile(path.join(FIXTURES, f), taxonomy, known)
|
||||
const cases = [
|
||||
['no-field.md', r => r.klass === 'text', 'известный раздел без правила → text'],
|
||||
['pd-section.md', r => r.klass === 'pd', 'by_section → pd'],
|
||||
['personal-section.md', r => r.klass === 'personal', 'by_section → personal'],
|
||||
['explicit-raise.md', r => r.klass === 'pd', 'явное поле поднимает text→pd'],
|
||||
['lower-trap.md', r => r.klass === 'pd', 'явное data_class:text НЕ опускает pd (строгое побеждает)'],
|
||||
['inherit-source.md', r => r.klass === 'pd', 'by_source_pattern → pd'],
|
||||
['inherit-project.md', r => r.klass === 'pd', 'by_project → pd'],
|
||||
['unknown-section.md', r => r.undetermined === true, 'раздел вне таксономии → undetermined(2)'],
|
||||
['broken-frontmatter.md', r => r.klass === 'personal', 'битый frontmatter → default personal']
|
||||
]
|
||||
const fail = []
|
||||
for (const [file, ok, why] of cases) {
|
||||
let r
|
||||
try { r = cf(file) } catch (e) { fail.push(`${file}: бросил ${e.message}`); continue }
|
||||
if (!ok(r)) fail.push(`${file}: ${why} — получено ${JSON.stringify(r)}`)
|
||||
}
|
||||
// batch-level semantics on the same fixtures
|
||||
const batch = (fileList, target) => {
|
||||
const und = [], blk = []
|
||||
for (const f of fileList) {
|
||||
const res = classifyFile(path.join(FIXTURES, f), taxonomy, known)
|
||||
if (res.undetermined) { und.push(res); continue }
|
||||
if (!taxonomy.classes[res.klass].machines.includes(target)) blk.push(res)
|
||||
}
|
||||
return und.length ? 2 : blk.length ? 1 : 0
|
||||
}
|
||||
if (batch(['no-field.md'], 'vps') !== 0) fail.push('batch: чистая (text) на vps должна быть 0')
|
||||
if (batch(['pd-section.md'], 'vps') !== 1) fail.push('batch: pd на vps должна быть 1')
|
||||
if (batch(['pd-section.md'], 'mac') !== 0) fail.push('batch: pd на mac должна быть 0')
|
||||
if (batch(['personal-section.md'], 'vps') !== 1) fail.push('batch: personal на vps должна быть 1')
|
||||
if (batch(['unknown-section.md'], 'vps') !== 2) fail.push('batch: unknown-section должна быть 2')
|
||||
|
||||
if (fail.length) { console.error('selftest ПРОВАЛ:\n' + fail.join('\n')); return 1 }
|
||||
console.log(JSON.stringify({ ok: true, selftest: 'machine-class-gate', fixtures: cases.length }))
|
||||
return 0
|
||||
}
|
||||
|
||||
function main() {
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
classify: { type: 'string' },
|
||||
batch: { type: 'string' },
|
||||
target: { type: 'string' },
|
||||
selftest: { type: 'boolean', default: false }
|
||||
},
|
||||
allowPositionals: false
|
||||
})
|
||||
let taxonomy
|
||||
try { taxonomy = loadTaxonomy() } catch (e) { console.error(`ОТКАЗ (2): ${e.message}`); return 2 }
|
||||
|
||||
if (values.selftest) return selftest(taxonomy)
|
||||
if (values.classify) return runClassify(values.classify, taxonomy)
|
||||
if (values.batch) return runBatch(values.batch, values.target || '', taxonomy)
|
||||
console.error('использование: --classify <файл> | --batch <манифест> --target mac|vps | --selftest')
|
||||
return 2
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
process.exit(main())
|
||||
}
|
||||
@@ -49,7 +49,7 @@ function withoutSourceFiles(graph, files) {
|
||||
async function main() {
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const graphPath = path.resolve(arg('graph', path.join(vault, 'graphify-out/graph.json')))
|
||||
const shardsDir = path.resolve(arg('shards-dir', path.join(vault, '.mnemazine/semantic-shards')))
|
||||
const shardsDir = path.resolve(arg('shards-dir', process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR || path.join(vault, '.mnemazine/semantic-shards')))
|
||||
const manifestPath = arg('manifest', '')
|
||||
const noBackup = flag('no-backup')
|
||||
if (!existsSync(graphPath)) throw new Error(`graph not found: ${graphPath}`)
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
#!/usr/bin/env node
|
||||
// Прибор миграционного контракта (план П16, шаг 1).
|
||||
//
|
||||
// Контракт — машинная таблица «старое поле → новое поле → правило переноса → что требует человека»,
|
||||
// чтобы перенос старых полей описывался таблицей, а не 1948 отдельными суждениями модели.
|
||||
// Контракт покрывает ВСТРЕЧЕННОЕ МНОЖЕСТВО значений, которое --emit переизвлекает на момент запуска,
|
||||
// а не исторические числа из планов.
|
||||
//
|
||||
// --emit <json> [--report <md>] переснять множество из корпуса и переписать контракт (+ человекочитаемую таблицу)
|
||||
// --verify <json> каждое встреченное значение либо покрыто правилом, либо помечено «требует человека»
|
||||
//
|
||||
// verify — fail-closed: поле/значение, встреченное в корпусе и не покрытое контрактом, — exit 1.
|
||||
// Покрытие трёх видов: значение уже в enum спеки (already-conformant), детерминированное правило
|
||||
// (mapType/mapVerified из mnemazine-normalize-old-frontmatter.mjs — импорт, копий нет) или явная
|
||||
// пометка human_required. verification_status схлопывается в verified: по решению оркестратора:
|
||||
// одно значение смысла — одно поле правды; verification_status после миграции удаляется.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { SPEC_TYPES, SPEC_VERIFIED, SPEC_SUBJECTS, normSpecValue } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault, ROOT } from './mnemazine-paths.mjs'
|
||||
import { mapType, mapVerified, corpusFiles, readFrontmatter } from './mnemazine-normalize-old-frontmatter.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const arg = (name, fallback = '') => {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const EMIT = arg('emit')
|
||||
const VERIFY = arg('verify')
|
||||
const REPORT = arg('report')
|
||||
if (!EMIT && !VERIFY) {
|
||||
console.error('нужен --emit <json> [--report <md>] или --verify <json>')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const norm = v => normSpecValue(String(v ?? '').trim())
|
||||
const CANON_VERIFIED_NORM = new Set(SPEC_VERIFIED.map(norm))
|
||||
|
||||
/** Тело секции `## Источники`/`## Source` (для строки контракта про source). */
|
||||
function sourcesSectionBody(text) {
|
||||
const m = text.match(/^#{2,}\s+(?:Source|Sources|Источник|Источники)\s*$/im)
|
||||
if (!m) return ''
|
||||
const tail = text.slice(m.index + m[0].length)
|
||||
const next = tail.search(/\n##\s+/)
|
||||
return (next === -1 ? tail : tail.slice(0, next)).trim()
|
||||
}
|
||||
|
||||
/** Снимок встреченного множества: значение → число нот, по каждому отслеживаемому полю. */
|
||||
async function scanCorpus() {
|
||||
const files = await corpusFiles(VAULT)
|
||||
const fields = { type: new Map(), verified: new Map(), verification_status: new Map(), type_legacy: new Map() }
|
||||
let withFm = 0
|
||||
let noFm = 0
|
||||
let sourcesBodyWithEmptySource = 0
|
||||
const bump = (map, value) => map.set(value, (map.get(value) || 0) + 1)
|
||||
for (const file of files) {
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
const fm = readFrontmatter(text)
|
||||
if (fm.error) { noFm++; continue }
|
||||
withFm++
|
||||
for (const key of Object.keys(fields)) {
|
||||
const v = fm.data[key]
|
||||
if (v === undefined) continue
|
||||
const value = Array.isArray(v) ? v.join(', ') : String(v)
|
||||
bump(fields[key], value)
|
||||
}
|
||||
const src = fm.data.source
|
||||
const srcOk = Array.isArray(src) ? src.some(s => String(s).trim()) : Boolean(String(src ?? '').trim())
|
||||
if (!srcOk && sourcesSectionBody(text)) sourcesBodyWithEmptySource++
|
||||
}
|
||||
return { files: files.length, withFm, noFm, fields, sourcesBodyWithEmptySource }
|
||||
}
|
||||
|
||||
const HUMAN = 'human'
|
||||
const RULE = 'rule'
|
||||
const CONFORM = 'already-conformant'
|
||||
const STANDING_LEGACY_VALUES = {
|
||||
type: [
|
||||
{ value: 'knowledge-note', notes: 38, covered_by: RULE, maps_to: 'concept', reason: 'repo-local fixture/default selftest; знание/заметка без спецполей = concept' },
|
||||
{ value: 'knowledge-digest', notes: 1, covered_by: RULE, maps_to: 'synthesis', reason: 'repo-local fixture/default selftest; digest/сводка = synthesis' },
|
||||
],
|
||||
verified: [
|
||||
{ value: 'expanded with public sources', notes: 23, covered_by: RULE, maps_to: 'подтверждён', reason: 'repo-local fixture/default selftest; публичные источники уже добавлены' },
|
||||
{ value: 'false', notes: 15, covered_by: RULE, maps_to: 'не-проверялось', reason: 'repo-local fixture/default selftest; false не заявляет проверку' },
|
||||
],
|
||||
}
|
||||
|
||||
export function mapVerificationStatus(old) {
|
||||
const v = norm(old)
|
||||
if (!v || ['unknown', 'assumed', 'false', 'no', 'нет', 'null', 'undefined'].includes(v)) return { value: 'не-проверялось', keepLegacy: false }
|
||||
if (v.includes('частично')) return { value: 'не-проверялось', keepLegacy: true }
|
||||
if (v === 'verified' || v === 'verified-with-public-sources' || /^подтвержд/.test(v)) return { value: 'подтверждён', keepLegacy: v !== 'verified' }
|
||||
if (v === 'источник-не-найден') return { value: 'источник-не-найден', keepLegacy: false }
|
||||
if (v === 'непроверяемо-методом') return { value: 'непроверяемо-методом', keepLegacy: false }
|
||||
return { value: 'не-проверялось', keepLegacy: true }
|
||||
}
|
||||
|
||||
function targetValue(field, value) {
|
||||
if (field === 'type') return SPEC_TYPES.has(String(value).trim()) ? String(value).trim() : mapType(value, {})
|
||||
if (field === 'verified') return mapVerified(value).value
|
||||
if (field === 'verification_status') return mapVerificationStatus(value).value
|
||||
return null
|
||||
}
|
||||
|
||||
/** Классификация значения: enum спеки / правило прибора / только человек. */
|
||||
function classify(field, value) {
|
||||
const v = norm(value)
|
||||
if (field === 'type') {
|
||||
if (SPEC_TYPES.has(String(value).trim())) return CONFORM
|
||||
const mapped = mapType(value, {})
|
||||
if (SPEC_TYPES.has(mapped) && mapped !== 'tool-card' && mapped !== 'decision') return RULE
|
||||
return HUMAN
|
||||
}
|
||||
if (field === 'verified') {
|
||||
if (CANON_VERIFIED_NORM.has(v)) return CONFORM
|
||||
const m = mapVerified(value)
|
||||
if (!m.keepLegacy) return RULE // пусто/false/true — чистое переименование без потери
|
||||
if (m.value === 'не-проверялось') return HUMAN // свободный текст схлопнут с потерей — человек читает legacy
|
||||
return RULE
|
||||
}
|
||||
if (field === 'verification_status') return RULE
|
||||
if (field === 'type_legacy') return 'archaeology'
|
||||
return HUMAN
|
||||
}
|
||||
|
||||
const RULE_TEXT = {
|
||||
type: 'mapType: суффиксное отображение в SPEC_TYPES, умолчание concept; tool-card — только при непустых repo+stars+license+risk; decision механически не ставится; оригинал сохраняется в type_legacy',
|
||||
verified: 'mapVerified: значение→SPEC_VERIFIED (ё/е равны); аннотация через пробел/скобку → enum + оригинал в verified_legacy; true/да/подтвержд* и expanded with public sources → подтверждён; пусто/false → не-проверялось; свободный текст → не-проверялось + verified_legacy',
|
||||
verification_status: 'mapVerificationStatus: поле схлопывается в verified: и после миграции удаляется. Частичная проверка → не-проверялось + legacy; verified/подтвержд*/verified-with-public-sources → подтверждён; unknown/assumed/false/пусто → не-проверялось; источник-не-найден и непроверяемо-методом сохраняют одноимённые значения. Правило 8 мастера: два поля одной семантики = дубль правды.',
|
||||
type_legacy: 'Археология переогранки — НЕ ТРОГАТЬ: это вход для кампании 3 (legacy-значение говорит о ноте больше, чем выровненный concept) и страховка от неверного отображения.',
|
||||
'## Источники→source': 'Перенос в source:/sources: ТОЛЬКО если провенанс виден в самой ноте (basename интейк-файла, local-media:<hash>, URL → в sources:). Не виден — поле остаётся пустым, нота уходит в список следующей волны. source: НЕ ВЫДУМЫВАТЬ (kimi-master.md, кампания 2).',
|
||||
}
|
||||
|
||||
async function emit() {
|
||||
const snap = await scanCorpus()
|
||||
const mkField = (field, extra = {}) => {
|
||||
const values = [...snap.fields[field].entries()]
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([value, notes]) => {
|
||||
const row = { value, notes, covered_by: classify(field, value) }
|
||||
const mapped = targetValue(field, value)
|
||||
if (mapped !== null) row.maps_to = mapped
|
||||
if (field === 'verification_status') row.remove_field_after_migration = true
|
||||
return row
|
||||
})
|
||||
const human = values.filter(v => v.covered_by === HUMAN).map(v => ({ value: v.value, notes: v.notes, reason: RULE_TEXT[field] }))
|
||||
return {
|
||||
old_field: field,
|
||||
new_field: extra.new_field ?? field,
|
||||
notes: values.reduce((a, v) => a + v.notes, 0),
|
||||
distinct_values: values.length,
|
||||
rule: RULE_TEXT[field],
|
||||
implemented_by: extra.implemented_by ?? null,
|
||||
new_enum: extra.new_enum ?? null,
|
||||
decision: extra.decision ?? null,
|
||||
values,
|
||||
standing_legacy_values: (STANDING_LEGACY_VALUES[field] || []).filter(v => !values.some(row => norm(row.value) === norm(v.value))),
|
||||
human_required: human,
|
||||
}
|
||||
}
|
||||
const contract = {
|
||||
contract: 'migration-contract',
|
||||
contract_version: 1,
|
||||
spec_ref: 'docs/NOTE-SPEC.md',
|
||||
spec_version: 'NOTE-SPEC 2026-07-25 + subject §18 (2026-08-22)',
|
||||
schema_ref: 'scripts/mnemazine-note-spec.mjs (единая правда П05; config/note.schema.json П06 — когда появится, ссылаться на неё, не дублировать)',
|
||||
generated_by: 'scripts/mnemazine-migration-check.mjs --emit',
|
||||
generated_at: new Date().toISOString(),
|
||||
vault: VAULT,
|
||||
corpus: { files: snap.files, with_frontmatter: snap.withFm, without_frontmatter: snap.noFm },
|
||||
fields: [
|
||||
mkField('type', { implemented_by: 'scripts/mnemazine-normalize-old-frontmatter.mjs (mapType)', new_enum: [...SPEC_TYPES] }),
|
||||
mkField('verified', { implemented_by: 'scripts/mnemazine-normalize-old-frontmatter.mjs (mapVerified)', new_enum: SPEC_VERIFIED }),
|
||||
mkField('verification_status', {
|
||||
new_field: 'verified',
|
||||
implemented_by: 'scripts/mnemazine-migration-check.mjs (mapVerificationStatus; контракт П16)',
|
||||
new_enum: SPEC_VERIFIED,
|
||||
decision: 'owner-decided-collapse-into-verified-remove-field',
|
||||
}),
|
||||
mkField('type_legacy', { new_field: '—' }),
|
||||
{
|
||||
old_field: '## Источники (тело) при пустом source:',
|
||||
new_field: 'source: / sources:',
|
||||
notes: snap.sourcesBodyWithEmptySource,
|
||||
distinct_values: null,
|
||||
rule: RULE_TEXT['## Источники→source'],
|
||||
implemented_by: 'кампания 3 (переогранка головой) + scripts/mnemazine-normalize-old-frontmatter.mjs (перенос sources→source)',
|
||||
new_enum: null,
|
||||
decision: null,
|
||||
values: [],
|
||||
human_required: [],
|
||||
},
|
||||
],
|
||||
subject_field: {
|
||||
note: 'Поле subject (§18): enum self|world|mixed. Старый корпус проставляется при переогранке: source_type video|article|repo и нет первого лица в теле → world; не выводится однозначно → mixed (fail-closed); self руками не назначается.',
|
||||
enum: [...SPEC_SUBJECTS],
|
||||
},
|
||||
}
|
||||
const target = path.resolve(ROOT, EMIT)
|
||||
await fs.mkdir(path.dirname(target), { recursive: true })
|
||||
await fs.writeFile(target, JSON.stringify(contract, null, 2) + '\n')
|
||||
console.log(`контракт записан: ${target}`)
|
||||
for (const f of contract.fields) {
|
||||
console.log(` ${f.old_field}: нот ${f.notes}, значений ${f.distinct_values ?? '—'}, человека требует ${f.human_required.length}`)
|
||||
}
|
||||
console.log(` ## Источники при пустом source:: нот ${snap.sourcesBodyWithEmptySource}`)
|
||||
if (REPORT) {
|
||||
const md = renderMarkdown(contract)
|
||||
const mdTarget = path.resolve(ROOT, REPORT)
|
||||
await fs.mkdir(path.dirname(mdTarget), { recursive: true })
|
||||
await fs.writeFile(mdTarget, md)
|
||||
console.log(`отчёт записан: ${mdTarget}`)
|
||||
}
|
||||
}
|
||||
|
||||
function renderMarkdown(c) {
|
||||
const rows = []
|
||||
for (const f of c.fields) {
|
||||
const human = f.human_required.length
|
||||
? f.human_required.map(h => `«${h.value}» (${h.notes})`).join(', ')
|
||||
: (f.decision === 'owner-pending' ? 'всё поле целиком — решение владельца' : '—')
|
||||
rows.push(`| \`${f.old_field}\` | ${f.notes} | ${f.distinct_values ?? '—'} | \`${f.new_field}\` | ${f.rule.split('.')[0]} | ${human} |`)
|
||||
}
|
||||
return `# Миграционный контракт корпуса → NOTE-SPEC
|
||||
|
||||
Сгенерировано кодом: \`${c.generated_by}\`, ${c.generated_at}. Не править руками — переснимать \`--emit\`.
|
||||
Спека: \`${c.spec_ref}\` (${c.spec_version}). Единая правда состава типов/значений: \`${c.schema_ref}\`.
|
||||
Корпус при съёме: ${c.corpus.files} файлов, frontmatter есть у ${c.corpus.with_frontmatter}, нет у ${c.corpus.without_frontmatter}.
|
||||
|
||||
| Старое поле | Нот | Значений | Новое поле | Правило переноса | Требует человека |
|
||||
|---|---:|---:|---|---|---|
|
||||
${rows.join('\n')}
|
||||
|
||||
## Полные правила
|
||||
|
||||
${c.fields.map(f => `### \`${f.old_field}\`\n\n${f.rule}\n\nПрибор: ${f.implemented_by ?? '—'}.${f.new_enum ? `\nНовый enum: ${f.new_enum.join(' | ')}.` : ''}${f.decision ? `\n**Решение: ${f.decision}.**` : ''}`).join('\n\n')}
|
||||
|
||||
## Standing legacy mappings
|
||||
|
||||
${c.fields.flatMap(f => (f.standing_legacy_values || []).map(v => `- \`${f.old_field}\`: \`${v.value}\` (${v.notes}) → \`${v.maps_to}\` — ${v.reason}`)).join('\n') || '—'}
|
||||
|
||||
## subject (§18 мастер-плана)
|
||||
|
||||
${c.subject_field.note}
|
||||
|
||||
## Проверка покрытия
|
||||
|
||||
\`node scripts/mnemazine-migration-check.mjs --verify config/migration-contract.json\` — каждое значение,
|
||||
встреченное в корпусе на момент прогона, либо уже в enum спеки, либо покрыто детерминированным правилом,
|
||||
либо явно помечено «требует человека». Новое непокрытое значение = exit 1.
|
||||
`
|
||||
}
|
||||
|
||||
async function verify() {
|
||||
const target = path.resolve(ROOT, VERIFY)
|
||||
const contract = JSON.parse(await fs.readFile(target, 'utf8'))
|
||||
const snap = await scanCorpus()
|
||||
const problems = []
|
||||
const byField = new Map(contract.fields.map(f => [f.old_field, f]))
|
||||
for (const field of ['type', 'verified', 'verification_status', 'type_legacy']) {
|
||||
const encountered = snap.fields[field]
|
||||
const encounteredNotes = [...encountered.values()].reduce((a, b) => a + b, 0)
|
||||
if (encounteredNotes === 0) continue
|
||||
const row = byField.get(field)
|
||||
if (!row) {
|
||||
problems.push(`${field}: ${encounteredNotes} нот несут поле, не покрытое контрактом (строка отсутствует)`)
|
||||
continue
|
||||
}
|
||||
if (field === 'type_legacy') continue // археология: покрытие — сама строка с правилом «не трогать»
|
||||
const declared = new Map()
|
||||
for (const v of [...(row.values || []), ...(row.standing_legacy_values || [])]) declared.set(norm(v.value), v)
|
||||
for (const h of row.human_required || []) declared.set(norm(h.value), { value: h.value, covered_by: HUMAN })
|
||||
for (const [value, notes] of encountered) {
|
||||
const kind = classify(field, value)
|
||||
if (kind === CONFORM || kind === 'archaeology') continue // уже в enum спеки
|
||||
const decl = declared.get(norm(value))
|
||||
if (!decl) {
|
||||
problems.push(`${field}: значение «${value}» (${notes} нот) встречено в корпусе, но в контракте не объявлено`)
|
||||
} else if (decl.covered_by === HUMAN && kind !== HUMAN) {
|
||||
problems.push(`${field}: значение «${value}» помечено «требует человека», но правило покрывает его детерминированно — контракт устарел, пересними --emit`)
|
||||
} else if (decl.covered_by === RULE && kind === HUMAN) {
|
||||
problems.push(`${field}: значение «${value}» объявлено покрытым правилом, но правило его не покрывает — нужна пометка «требует человека»`)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (problems.length) {
|
||||
console.error(`контракт НЕ покрывает корпус (${problems.length} проблем):`)
|
||||
for (const p of problems) console.error(` - ${p}`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`контракт покрывает встреченное множество: ${snap.files} файлов, поля type/verified/verification_status/type_legacy проверены`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (EMIT) await emit()
|
||||
else await verify()
|
||||
@@ -0,0 +1,181 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const ROOT = path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
const jsonMode = argv.includes('--json')
|
||||
const EXPECTED_AGENT_CALLS = 25
|
||||
|
||||
function arg(name) {
|
||||
const i = argv.indexOf(`--${name}`)
|
||||
return i === -1 ? '' : argv[i + 1] || ''
|
||||
}
|
||||
|
||||
async function readJson(rel) {
|
||||
return JSON.parse(await fs.readFile(path.join(ROOT, rel), 'utf8'))
|
||||
}
|
||||
|
||||
function frontmatterModel(text) {
|
||||
const head = String(text || '').match(/^---\n([\s\S]*?)\n---/)
|
||||
if (!head) return ''
|
||||
return (head[1].match(/^model:\s*["']?([^"'\n]+)["']?\s*$/m)?.[1] || '').trim()
|
||||
}
|
||||
|
||||
async function roleModels() {
|
||||
const dir = path.join(ROOT, 'agents/mnemazina-pipeline')
|
||||
const out = {}
|
||||
for (const name of await fs.readdir(dir).catch(() => [])) {
|
||||
if (!name.endsWith('.md')) continue
|
||||
out[name.replace(/\.md$/, '')] = frontmatterModel(await fs.readFile(path.join(dir, name), 'utf8'))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function isIdent(ch) {
|
||||
return /[A-Za-z0-9_$]/.test(ch || '')
|
||||
}
|
||||
|
||||
function skipString(src, i) {
|
||||
const quote = src[i]
|
||||
i += 1
|
||||
while (i < src.length) {
|
||||
if (src[i] === '\\') { i += 2; continue }
|
||||
if (src[i] === quote) return i + 1
|
||||
i += 1
|
||||
}
|
||||
return i
|
||||
}
|
||||
|
||||
function extractAgentCalls(src) {
|
||||
const calls = []
|
||||
for (let i = 0; i < src.length; i++) {
|
||||
if (src.startsWith('//', i)) { const n = src.indexOf('\n', i + 2); i = n === -1 ? src.length : n; continue }
|
||||
if (src.startsWith('/*', i)) { const n = src.indexOf('*/', i + 2); i = n === -1 ? src.length : n + 1; continue }
|
||||
if (src[i] === '"' || src[i] === "'" || src[i] === '`') { i = skipString(src, i) - 1; continue }
|
||||
if (!src.startsWith('agent(', i) || isIdent(src[i - 1])) continue
|
||||
let depth = 0
|
||||
for (let j = i; j < src.length; j++) {
|
||||
if (src.startsWith('//', j)) { const n = src.indexOf('\n', j + 2); j = n === -1 ? src.length : n; continue }
|
||||
if (src.startsWith('/*', j)) { const n = src.indexOf('*/', j + 2); j = n === -1 ? src.length : n + 1; continue }
|
||||
if (src[j] === '"' || src[j] === "'" || src[j] === '`') { j = skipString(src, j) - 1; continue }
|
||||
if (src[j] === '(') depth += 1
|
||||
if (src[j] === ')') {
|
||||
depth -= 1
|
||||
if (depth === 0) {
|
||||
calls.push({ start: i, body: src.slice(i, j + 1) })
|
||||
i = j
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
function stringValuesFor(name, body) {
|
||||
const re = new RegExp(`${name}\\s*:\\s*['"]([^'"]+)['"]`, 'g')
|
||||
const out = []
|
||||
for (let m; (m = re.exec(body));) out.push(m[1])
|
||||
return out
|
||||
}
|
||||
|
||||
function labelOf(body) {
|
||||
return stringValuesFor('label', body)[0] || ''
|
||||
}
|
||||
|
||||
function agentTypeOf(body) {
|
||||
return stringValuesFor('agentType', body)[0] || ''
|
||||
}
|
||||
|
||||
function hasModel(body) {
|
||||
return /\bmodel\s*:/.test(body)
|
||||
}
|
||||
|
||||
function arithmeticHits(calls) {
|
||||
const patterns = [
|
||||
['shasum', /\bshasum\b/],
|
||||
['wc -l', /\bwc\s+-l\b/],
|
||||
['| sort', /\|\s*sort\b/],
|
||||
['--json', /(^|[\s"'])--json\b/],
|
||||
['%-threshold', /(?:[0-9]|≥|<=|>=|>|<)\s*[0-9]*\s*%/]
|
||||
]
|
||||
const hits = []
|
||||
for (const call of calls) {
|
||||
for (const [name, re] of patterns) {
|
||||
if (re.test(call.body)) hits.push({ label: labelOf(call.body), pattern: name })
|
||||
}
|
||||
}
|
||||
return hits
|
||||
}
|
||||
|
||||
async function checkRunObservability(stateDir) {
|
||||
if (!stateDir) return []
|
||||
const file = path.join(stateDir, 'run-observability.jsonl')
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
const violations = []
|
||||
for (const [idx, line] of text.split(/\r?\n/).entries()) {
|
||||
if (!line.trim()) continue
|
||||
let row
|
||||
try { row = JSON.parse(line) } catch { violations.push(`observability:${idx + 1}: invalid json`); continue }
|
||||
if (row.tier === 0 && row.deep === true) violations.push(`observability:${idx + 1}: tier 0 deep=true (${row.file || ''})`)
|
||||
if (row.llm_extract_used === true && row.sidecar_present === true) violations.push(`observability:${idx + 1}: llm_extract_used with sidecar (${row.file || ''})`)
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const policy = await readJson('config/model-policy.json')
|
||||
const workflow = await fs.readFile(path.join(ROOT, 'workflows/mnemazina-pipeline.js'), 'utf8')
|
||||
const roles = await roleModels()
|
||||
const calls = extractAgentCalls(workflow)
|
||||
const violations = []
|
||||
|
||||
if (calls.length === 0 || Object.keys(roles).length === 0) {
|
||||
const result = { ok: false, code: 2, agent_calls: calls.length, roles: Object.keys(roles).length, violations: ['empty agent or role sample'] }
|
||||
if (jsonMode) console.log(JSON.stringify(result, null, 2))
|
||||
else console.error(result.violations.join('\n'))
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
for (const call of calls) {
|
||||
if (hasModel(call.body)) continue
|
||||
const type = agentTypeOf(call.body)
|
||||
if (!type || !existsSync(path.join(ROOT, 'agents/mnemazina-pipeline', `${type}.md`)) || !roles[type]) {
|
||||
violations.push(`agent without model and role model: ${labelOf(call.body) || `offset ${call.start}`}`)
|
||||
}
|
||||
}
|
||||
|
||||
for (const tier of ['0', '1', '2', '3']) {
|
||||
if (!policy.tiers || !policy.tiers[tier]) violations.push(`policy tiers missing ${tier}`)
|
||||
}
|
||||
for (const role of ['kb-find', 'store', 'reconcile', 'reconcile-2', 'proc']) {
|
||||
if (!policy.roles || !policy.roles[role]) violations.push(`policy roles missing ${role}`)
|
||||
}
|
||||
for (const role of stringValuesFor('label', workflow).filter(v => ['kb-find', 'store', 'reconcile', 'reconcile-2'].includes(v))) {
|
||||
if (!workflow.includes(`modelForRole('${role}'`)) violations.push(`role ${role} is not pinned through policy`)
|
||||
}
|
||||
if (!workflow.includes("modelForRole('proc'")) violations.push('proc is not pinned through policy')
|
||||
|
||||
for (const hit of arithmeticHits(calls)) violations.push(`agent arithmetic ${hit.pattern}: ${hit.label || 'unlabeled'}`)
|
||||
violations.push(...await checkRunObservability(arg('run')))
|
||||
|
||||
const result = { ok: violations.length === 0, agent_calls: calls.length, roles: Object.keys(roles).length, violations }
|
||||
if (calls.length !== EXPECTED_AGENT_CALLS) {
|
||||
violations.push(`agent call count expected ${EXPECTED_AGENT_CALLS}, got ${calls.length}`)
|
||||
result.ok = false
|
||||
result.violations = violations
|
||||
}
|
||||
if (jsonMode) console.log(JSON.stringify(result, null, 2))
|
||||
else if (violations.length) console.error(violations.join('\n'))
|
||||
else console.log('model-pin ok')
|
||||
process.exit(violations.length ? 1 : 0)
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
const message = err && err.message ? err.message : String(err)
|
||||
if (jsonMode) console.log(JSON.stringify({ ok: false, code: 1, violations: [message] }, null, 2))
|
||||
else console.error(message)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
#!/usr/bin/env node
|
||||
// Механическая половина переогранки старого корпуса под docs/NOTE-SPEC.md — за $0, детерминированно.
|
||||
//
|
||||
// Зачем отдельно от Кими-кампании: из 1378 нот, валящих `--spec`, 1361 валит `type` и 1250 `verified`, и
|
||||
// это ЧИСТОЕ переименование словаря (`knowledge-note` → `concept`), а не суждение. Гонять на него LLM —
|
||||
// платить за regex. Кими остаётся то, что действительно требует головы: блоки «Как это поможет мне» и
|
||||
// «Достоверность», плотность текста, доля кириллицы, мерж-вердикт.
|
||||
//
|
||||
// Что скрипт НЕ делает принципиально:
|
||||
// • не выдумывает `source` — провенанс нельзя восстановить угадыванием (только переносит из `sources`);
|
||||
// • не ставит `подтверждён` там, где проверки не было (для этого владелец завёл «не-проверялось»);
|
||||
// • не трогает тело ноты вообще;
|
||||
// • не создаёт frontmatter с нуля — нота без него уходит в отчёт, её чинит конвейер.
|
||||
//
|
||||
// Правка построчная, а не через reparse+dump: пересборка YAML переформатировала бы 1378 файлов целиком и
|
||||
// потеряла бы комментарии/порядок. Дубль ключа во frontmatter — уже измеренная дыра проекта, поэтому файл
|
||||
// с дублем `type`/`verified` не правится, а уходит в отчёт (fail-closed).
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { SPEC_TYPES, SPEC_VERIFIED, normSpecValue } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const norm = s => normSpecValue(String(s ?? '').trim())
|
||||
const CANON_VERIFIED = new Map([...SPEC_VERIFIED].map(v => [norm(v), v]))
|
||||
|
||||
/**
|
||||
* Старый словарь типов — 184 разных значения на 1378 нот. Отображение по СУФФИКСУ, а не таблицей на 184
|
||||
* строки: словарь рос свободно (`security-tool-reference`, `frontend-quality-gate`), и таблица отстала бы
|
||||
* от следующей волны. Умолчание — `concept`: спека определяет его как «понятие/метод/принцип», под что
|
||||
* ложатся все `*-method`, `*-boundary`, `*-policy`, `*-gate`, `*-atom`, `workflow`, `prompt`.
|
||||
*
|
||||
* Куда НЕ отображаем механически:
|
||||
* `decision` — требует непустые `context` и `rejected`, их у старых нот нет: гейт всё равно провалит;
|
||||
* `tool-card` — требует repo/stars/license/risk; ставим ТОЛЬКО когда все четыре реально в ноте.
|
||||
* Оригинал сохраняется в `type_legacy` — это вход для Кими (`security-tool-reference` говорит ей о ноте
|
||||
* больше, чем выровненный `concept`), и страховка от неверного отображения.
|
||||
*/
|
||||
export function mapType(old, data) {
|
||||
const has = k => {
|
||||
const v = data[k]
|
||||
return Array.isArray(v) ? v.length > 0 : Boolean(String(v ?? '').trim())
|
||||
}
|
||||
if (has('repo') && has('stars') && has('license') && has('risk')) return 'tool-card'
|
||||
const t = norm(old)
|
||||
if (SPEC_TYPES.has(t) && t !== 'decision' && t !== 'tool-card') return t
|
||||
if (/(^|-)(reference|catalog|index|map|list|queue)$/.test(t) || t === 'redirect') return 'reference'
|
||||
if (/(synthesis|canonical-summary|digest|overview|comparison|stack|triage)/.test(t)) return 'synthesis'
|
||||
return 'concept'
|
||||
}
|
||||
|
||||
/**
|
||||
* Старое значение `verified` → enum спеки. Правило одно: НИКОГДА не заявлять проверку, которой не было.
|
||||
* Порядок проверок — от точного к общему:
|
||||
* 1. значение УЖЕ из enum → оно же, без legacy.
|
||||
* 2. enum + аннотация через пробел или скобку («непроверяемо-методом (транскрипт видео)») → enum,
|
||||
* аннотация в `verified_legacy`. Без этого шага 35 честных значений понижались в «не-проверялось»
|
||||
* просто потому, что автор дописал скобку — измерено на живом корпусе. Граница обязательна: без неё
|
||||
* «непроверяемо-методомX» тоже сошло бы за валидное значение.
|
||||
* 3. да/true/подтверждено… → `подтверждён` (прошлый конвейер именно это и утверждал). Оговорка о
|
||||
* неполноте бьёт утверждение сама собой: «частично подтверждено…» начинается не с «подтвержд»,
|
||||
* поэтому сюда не попадает и уезжает в общий случай — отдельная ветка на «частично» была бы мёртвым
|
||||
* кодом (проверено мутацией: её удаление не меняет ни одного исхода).
|
||||
* 4. expanded with public sources → `подтверждён`: старый конвейер уже расширил ноту публичными
|
||||
* источниками, то есть это проверка источниками, а не пустая догадка.
|
||||
* 5. пусто/false/нет → `не-проверялось` без legacy: терять нечего.
|
||||
* 6. всё прочее — «частично…», даты, свободный текст → `не-проверялось`, оригинал в legacy.
|
||||
* Занижение безопаснее завышения: непроверенное знание, помеченное проверенным, — худший исход.
|
||||
*/
|
||||
export function mapVerified(old) {
|
||||
const v = norm(old)
|
||||
if (CANON_VERIFIED.has(v)) return { value: CANON_VERIFIED.get(v), keepLegacy: false }
|
||||
for (const [canon, value] of CANON_VERIFIED) {
|
||||
if (v.startsWith(canon) && /^[\s(]/.test(v.slice(canon.length))) return { value, keepLegacy: true }
|
||||
}
|
||||
if (/^(да|true|yes|verified)$/.test(v) || /^подтвержд/.test(v)) return { value: 'подтверждён', keepLegacy: v !== 'подтвержден' }
|
||||
if (v === 'expanded with public sources') return { value: 'подтверждён', keepLegacy: true }
|
||||
if (!v || /^(false|no|нет|null|undefined)$/.test(v)) return { value: 'не-проверялось', keepLegacy: false }
|
||||
return { value: 'не-проверялось', keepLegacy: true } // даты, свободный текст — информацию храним
|
||||
}
|
||||
|
||||
// Основное тело исполняется ТОЛЬКО при прямом вызове: прибор миграционного контракта
|
||||
// (mnemazine-migration-check.mjs) импортирует mapType/mapVerified, и без этого стража
|
||||
// импорт запускал бы обход vault и правки по чужим argv.
|
||||
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
|
||||
if (isMain && process.argv.slice(2).includes('--selftest')) {
|
||||
const { strictEqual: eq } = await import('node:assert')
|
||||
const V = s => mapVerified(s).value
|
||||
// Аннотация не понижает честное значение (баг, найденный на живом корпусе — 35 нот).
|
||||
eq(V('непроверяемо-методом (транскрипт видео)'), 'непроверяемо-методом')
|
||||
eq(mapVerified('непроверяемо-методом (транскрипт видео)').keepLegacy, true)
|
||||
// Оговорка о неполноте бьёт слово «подтверждено» — иначе частичная проверка выдаст себя за полную.
|
||||
// Без границы «непроверяемо-методомX» сошло бы за валидное значение — мутация ловится ровно этим.
|
||||
eq(V('непроверяемо-методомX'), 'не-проверялось')
|
||||
eq(V('частично подтверждено первоисточниками 2026-06-06'), 'не-проверялось')
|
||||
eq(V('частично-подтверждено'), 'не-проверялось')
|
||||
eq(V('подтверждено на дату предыдущей проверки'), 'подтверждён')
|
||||
eq(V('подтверждён'), 'подтверждён')
|
||||
eq(V('подтвержден'), 'подтверждён') // ё/е — одно слово
|
||||
eq(V('true'), 'подтверждён')
|
||||
eq(V('expanded with public sources'), 'подтверждён')
|
||||
eq(mapVerified('expanded with public sources').keepLegacy, true)
|
||||
eq(V('false'), 'не-проверялось')
|
||||
eq(V(''), 'не-проверялось')
|
||||
eq(V('2026-06-05'), 'не-проверялось')
|
||||
eq(mapVerified('').keepLegacy, false) // терять нечего — legacy не плодим
|
||||
// «не-проверялось» само себя не ловит префиксом «не» и остаётся собой.
|
||||
eq(V('не-проверялось'), 'не-проверялось')
|
||||
eq(mapVerified('не-проверялось').keepLegacy, false)
|
||||
const T = (t, d = {}) => mapType(t, d)
|
||||
eq(T('knowledge-note'), 'concept')
|
||||
eq(T('security-tool-reference'), 'reference')
|
||||
eq(T('canonical-summary'), 'synthesis')
|
||||
eq(T('tool'), 'concept') // без repo/stars/license/risk карточкой инструмента не станет
|
||||
eq(T('tool', { repo: 'x' }), 'concept') // ОДНОГО поля мало: гейт всё равно потребует остальные три
|
||||
eq(T('tool', { repo: 'x', stars: 1, license: 'MIT' }), 'concept')
|
||||
eq(T('tool', { repo: 'x', stars: 1, license: 'MIT', risk: 'low' }), 'tool-card')
|
||||
eq(T('decision'), 'concept') // decision требует context+rejected — механически не ставим
|
||||
eq(T('reference'), 'reference')
|
||||
console.log('selftest ok')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
async function walk(dir) {
|
||||
const out = []
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const p = path.join(dir, item.name)
|
||||
if (item.isDirectory() && !['.git', '.obsidian'].includes(item.name) && !item.name.startsWith('graphify-out')) out.push(...await walk(p))
|
||||
else if (item.isFile() && p.endsWith('.md')) out.push(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Копия предиката из mnemazine-vault-quality-gate.mjs — канон там. Скрипт обязан видеть РОВНО тот же набор
|
||||
// файлов, что судит гейт: правь обе стороны вместе, иначе нормализатор чинит не то, что проверяется.
|
||||
function isServicePath(rel) {
|
||||
return (
|
||||
rel.includes('/graphify-out/') ||
|
||||
rel.includes('/_legacy-index ') ||
|
||||
rel.includes('/_архив-дублей/') ||
|
||||
rel.includes('/Capabilities/_') ||
|
||||
/^99 Система\//.test(rel) ||
|
||||
/^00 System\//.test(rel) ||
|
||||
/(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
|
||||
['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
|
||||
)
|
||||
}
|
||||
|
||||
const unquote = v => {
|
||||
const m = String(v).match(/^"(.*)"$/s) || String(v).match(/^'(.*)'$/s)
|
||||
return m ? m[1] : String(v)
|
||||
}
|
||||
|
||||
/** Границы frontmatter + плоские скаляры/списки. Дубль ключа верхнего уровня = отказ (fail-closed). */
|
||||
function readFrontmatter(text) {
|
||||
const lines = text.split('\n')
|
||||
if (!/^---\s*$/.test(lines[0] ?? '')) return { error: 'нет frontmatter' }
|
||||
let close = -1
|
||||
for (let i = 1; i < lines.length; i++) if (/^---\s*$/.test(lines[i])) { close = i; break }
|
||||
if (close === -1) return { error: 'frontmatter не закрыт' }
|
||||
const data = {}
|
||||
const lineOf = {}
|
||||
let listKey = null
|
||||
for (let i = 1; i < close; i++) {
|
||||
const line = lines[i].replace(/\r$/, '')
|
||||
if (!line.trim() || line.trim().startsWith('#')) continue
|
||||
const kv = line.match(/^([\w.-]+):(?:\s+(.*))?$/)
|
||||
if (kv) {
|
||||
const key = kv[1]
|
||||
if (Object.hasOwn(data, key)) return { error: `дубль ключа «${key}»` }
|
||||
const raw = (kv[2] ?? '').trim()
|
||||
lineOf[key] = i
|
||||
if (!raw) { data[key] = []; listKey = key }
|
||||
else if (/^\[.*\]$/.test(raw)) { data[key] = raw.slice(1, -1).split(',').map(s => unquote(s.trim())).filter(Boolean); listKey = null }
|
||||
else { data[key] = unquote(raw); listKey = null }
|
||||
continue
|
||||
}
|
||||
const item = line.match(/^\s*-\s+(.*)$/)
|
||||
if (item && listKey) { data[listKey].push(unquote(item[1].trim())); continue }
|
||||
if (/^\s/.test(line)) continue
|
||||
return { error: `непарсибельная строка ${i + 1}` }
|
||||
}
|
||||
return { data, lines, close, lineOf }
|
||||
}
|
||||
|
||||
/** YAML-скаляр: кавычки только когда без них значение сменит смысл или сломает парсер. */
|
||||
const yamlScalar = v => (/^[\wА-Яа-яЁё][\wА-Яа-яЁё .,()/@-]*$/.test(v) ? v : JSON.stringify(v))
|
||||
|
||||
/** Обход корпуса гейта — общий для приборов миграции (импортируется migration-check). */
|
||||
export async function corpusFiles(vault) {
|
||||
return (await walk(vault)).filter(f => !isServicePath(path.relative(vault, f)))
|
||||
}
|
||||
|
||||
export { readFrontmatter, yamlScalar }
|
||||
|
||||
// ── Исполнение: только при прямом вызове (страж isMain выше) ──
|
||||
if (isMain) {
|
||||
const argv = process.argv.slice(2)
|
||||
const arg = (name, fallback = '') => {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const APPLY = argv.includes('--apply') // fail-safe: по умолчанию сухой прогон, диск не трогается
|
||||
const JSON_OUT = argv.includes('--json')
|
||||
|
||||
const files = (await walk(VAULT)).filter(f => !isServicePath(path.relative(VAULT, f)))
|
||||
const report = { vault: VAULT, apply: APPLY, scanned: files.length, changed: 0, edits: { type: 0, verified: 0, source: 0, typeLegacy: 0, verifiedLegacy: 0 }, skipped: [] }
|
||||
|
||||
for (const file of files) {
|
||||
const rel = path.relative(VAULT, file)
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
const fm = readFrontmatter(text)
|
||||
if (fm.error) { report.skipped.push({ file: rel, reason: fm.error }); continue }
|
||||
|
||||
const { data, lines, close, lineOf } = fm
|
||||
const insert = [] // строки, которых во frontmatter не было
|
||||
let touched = false
|
||||
|
||||
const oldType = Array.isArray(data.type) ? '' : String(data.type ?? '')
|
||||
const newType = mapType(oldType, data)
|
||||
if (norm(oldType) !== norm(newType)) {
|
||||
// Оригинал сохраняем ДО перезаписи — иначе `security-tool-reference` исчезнет из ноты навсегда.
|
||||
if (oldType.trim() && !Object.hasOwn(data, 'type_legacy')) { insert.push(`type_legacy: ${yamlScalar(oldType.trim())}`); report.edits.typeLegacy++ }
|
||||
if (Object.hasOwn(lineOf, 'type')) lines[lineOf.type] = `type: ${newType}`
|
||||
else insert.push(`type: ${newType}`)
|
||||
report.edits.type++
|
||||
touched = true
|
||||
}
|
||||
|
||||
const oldVerified = Array.isArray(data.verified) ? '' : String(data.verified ?? '')
|
||||
const mapped = mapVerified(oldVerified)
|
||||
if (oldVerified.trim() !== mapped.value) {
|
||||
if (mapped.keepLegacy && !Object.hasOwn(data, 'verified_legacy')) { insert.push(`verified_legacy: ${yamlScalar(oldVerified.trim())}`); report.edits.verifiedLegacy++ }
|
||||
if (Object.hasOwn(lineOf, 'verified')) lines[lineOf.verified] = `verified: ${mapped.value}`
|
||||
else insert.push(`verified: ${mapped.value}`)
|
||||
report.edits.verified++
|
||||
touched = true
|
||||
}
|
||||
|
||||
// `source` НЕ выдумывается: берётся только первый непустой элемент уже существующего `sources`. Пусто —
|
||||
// значит провенанс правда неизвестен, и это работа конвейера, а не переименования.
|
||||
const hasSource = Array.isArray(data.source) ? data.source.some(s => String(s).trim()) : Boolean(String(data.source ?? '').trim())
|
||||
if (!hasSource) {
|
||||
const fromList = (Array.isArray(data.sources) ? data.sources : [data.sources]).map(s => String(s ?? '').trim()).find(Boolean)
|
||||
if (fromList) {
|
||||
if (Object.hasOwn(lineOf, 'source')) lines[lineOf.source] = `source: ${yamlScalar(fromList)}`
|
||||
else insert.push(`source: ${yamlScalar(fromList)}`)
|
||||
report.edits.source++
|
||||
touched = true
|
||||
}
|
||||
}
|
||||
|
||||
if (!touched) continue
|
||||
report.changed++
|
||||
if (!APPLY) continue
|
||||
const out = [...lines.slice(0, close), ...insert, ...lines.slice(close)].join('\n')
|
||||
await fs.writeFile(file, out)
|
||||
}
|
||||
|
||||
if (JSON_OUT) console.log(JSON.stringify(report, null, 2))
|
||||
else {
|
||||
console.log(`${APPLY ? 'ПРИМЕНЕНО' : 'СУХОЙ ПРОГОН'} · vault ${report.vault}`)
|
||||
console.log(`просмотрено ${report.scanned} · изменено ${report.changed} · пропущено ${report.skipped.length}`)
|
||||
console.log(` type ${report.edits.type} (сохранено type_legacy ${report.edits.typeLegacy})`)
|
||||
console.log(` verified ${report.edits.verified} (сохранено verified_legacy ${report.edits.verifiedLegacy})`)
|
||||
console.log(` source из sources ${report.edits.source}`)
|
||||
for (const s of report.skipped) console.log(` ПРОПУСК ${s.file} — ${s.reason}`)
|
||||
}
|
||||
} // конец isMain
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
if (hit.includes('=')) return hit.split('=').slice(1).join('=')
|
||||
return argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const APPLY = argv.includes('--apply')
|
||||
const SKILLS_DIR = path.join(VAULT, '08 AI и Инструменты', 'skills')
|
||||
|
||||
const CANON_BLOCK = `## Канон скиллов
|
||||
|
||||
- Общая база методики: [[_СПОСОБНОСТИ — методика]], [[2026-06-13 — Каскад роутинга скиллов — local-first с внешним fallback]], [[2026-06-13 — Маркетплейсы скиллов для AI-агентов — skills.sh, SkillHub, SkillsMP]].
|
||||
- Перед установкой или обновлением: читать \`SKILL.md\`, \`scripts/\`, license, package manager commands и внешние действия.
|
||||
- Для MCP/plugin/API: read-only по умолчанию, allowlist tools, без секретов в config, write/publish/push только после явного approval владельца.
|
||||
- При применении знания сначала искать уже доступную локальную способность в [[_СПОСОБНОСТИ — реестр]], а внешний marketplace считать fallback.
|
||||
`
|
||||
|
||||
async function walk(dir) {
|
||||
const out = []
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const p = path.join(dir, item.name)
|
||||
if (item.name === 'graphify-out' || item.name.startsWith('.')) continue
|
||||
if (item.isDirectory()) out.push(...await walk(p))
|
||||
else if (item.isFile() && item.name.endsWith('.md') && !item.name.startsWith('_')) out.push(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function normalizeFrontmatter(text) {
|
||||
if (!text.startsWith('---\n')) return text
|
||||
const end = text.indexOf('\n---', 4)
|
||||
if (end === -1) return text
|
||||
const fm = text.slice(4, end)
|
||||
const body = text.slice(end)
|
||||
const next = fm
|
||||
.replace(/^section:\s*["']?07 Скиллы["']?\s*$/m, 'section: "08 AI и Инструменты"')
|
||||
.replace(/^category:\s*["']?Skills["']?\s*$/m, 'category: "AI Skills"')
|
||||
return `---\n${next}${body}`
|
||||
}
|
||||
|
||||
const changed = []
|
||||
for (const file of await walk(SKILLS_DIR)) {
|
||||
const rel = path.relative(VAULT, file)
|
||||
let text = await fs.readFile(file, 'utf8')
|
||||
let next = normalizeFrontmatter(text)
|
||||
|
||||
if (!/^## Канон скиллов\b/m.test(next)) {
|
||||
const relatedIndex = next.search(/^## (Применимые способности|Связанные темы|Достоверность|Чек-лист|Опыт практиков)\b/m)
|
||||
if (relatedIndex === -1) {
|
||||
next = `${next.trimEnd()}\n\n${CANON_BLOCK}\n`
|
||||
} else {
|
||||
next = `${next.slice(0, relatedIndex).trimEnd()}\n\n${CANON_BLOCK}\n${next.slice(relatedIndex)}`
|
||||
}
|
||||
}
|
||||
|
||||
if (next !== text) {
|
||||
changed.push(rel)
|
||||
if (APPLY) await fs.writeFile(file, next)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(JSON.stringify({ ok: true, apply: APPLY, changed: changed.length, changed_preview: changed.slice(0, 80) }, null, 2))
|
||||
@@ -0,0 +1,84 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const SPEC_TYPES = new Set(['concept', 'tool-card', 'decision', 'synthesis', 'agent-research', 'reference'])
|
||||
export const SPEC_VERIFIED = ['подтверждён', 'источник-не-найден', 'непроверяемо-методом', 'облако-недоступно', 'проверено-практикой', 'не-проверялось']
|
||||
export const SPEC_SUBJECTS = new Set(['self', 'world', 'mixed'])
|
||||
export const MIN_CYR_SHARE = 0.30
|
||||
|
||||
// data_class enum (П24) — единая правда о классах живёт в config/data-classes.json;
|
||||
// здесь она только ЧИТАЕТСЯ, не переопределяется (правило 8: одна правда на две
|
||||
// границы). null, если таксономия недоступна → поле не энфорсится (как type до П05).
|
||||
export const SPEC_DATA_CLASSES = (() => {
|
||||
try {
|
||||
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'config', 'data-classes.json')
|
||||
return new Set(Object.keys(JSON.parse(readFileSync(file, 'utf8')).classes))
|
||||
} catch { return null }
|
||||
})()
|
||||
|
||||
export const TYPE_REQUIRED_FIELDS = {
|
||||
'tool-card': ['repo', 'stars', 'license', 'risk'],
|
||||
'agent-research': ['project', 'agent', 'claim_status']
|
||||
}
|
||||
|
||||
export function normSpecValue(value) {
|
||||
return String(value ?? '').replace(/ё/g, 'е').replace(/Ё/g, 'Е').toLowerCase()
|
||||
}
|
||||
|
||||
export const SPEC_VERIFIED_NORM = new Set(SPEC_VERIFIED.map(v => normSpecValue(v)))
|
||||
|
||||
// Единая правда о составе тела ноты (docs/NOTE-SPEC.md:63-83). Приборы, которым
|
||||
// нужен список блоков, читают ЭТОТ массив, а не заводят свою копию (план П13, шаг 7).
|
||||
// mandatory — блок обязателен всегда (NOTE-SPEC.md:82: 1, 7, 8); untouchable — зона,
|
||||
// которую очеловечивание не трогает, гейт сохранности сверяет её побайтово.
|
||||
export const SPEC_BODY_HEADINGS = [
|
||||
{ n: 1, title: 'Короткий ответ', re: /^##\s+Короткий ответ\s*$/m, mandatory: true },
|
||||
{ n: 2, title: 'Механика', re: /^##\s+Механика\s*$/m },
|
||||
{ n: 3, title: 'Применение', re: /^##\s+Применение\s*$/m },
|
||||
{ n: 4, title: 'Примеры и контрпримеры', re: /^##\s+Примеры и контрпримеры\s*$/m },
|
||||
{ n: 5, title: 'Ошибки и границы', re: /^##\s+Ошибки и границы\s*$/m },
|
||||
{ n: 6, title: 'Опыт практиков', re: /^##\s+Опыт практиков\s*$/m },
|
||||
{ n: 7, title: 'Как это поможет мне', re: /^##\s+(?:🎯\s*)?Как это поможет мне\s*$/m, mandatory: true },
|
||||
{ n: 8, title: 'Достоверность', re: /^##\s+Достоверность\s*$/m, mandatory: true, untouchable: true },
|
||||
{ n: 9, title: 'Связанные темы', re: /^##\s+Связанные темы\s*$/m },
|
||||
{ n: 10, title: 'Следующий ход', re: /^##\s+Следующий ход\s*$/m }
|
||||
]
|
||||
|
||||
export const SPEC_UNTOUCHABLE_HEADINGS = SPEC_BODY_HEADINGS.filter(h => h.untouchable)
|
||||
|
||||
function noteSectionAfter(text, label) {
|
||||
const start = String(text || '').indexOf(label)
|
||||
if (start === -1) return ''
|
||||
const tail = text.slice(start + label.length)
|
||||
const next = tail.search(/\n##\s+/)
|
||||
return next === -1 ? tail : tail.slice(0, next)
|
||||
}
|
||||
|
||||
function noteSectionsAfter(text, labels) {
|
||||
return labels.map(label => noteSectionAfter(text, label)).filter(Boolean).join('\n')
|
||||
}
|
||||
|
||||
export function strictKnowledgeReady(text) {
|
||||
const facts = noteSectionsAfter(text, [
|
||||
'External facts added before atomization:',
|
||||
'Факты, добавленные до атомизации:'
|
||||
])
|
||||
const sources = noteSectionsAfter(text, [
|
||||
'Public/source expansion:',
|
||||
'Публичные источники:'
|
||||
])
|
||||
const factCount = facts
|
||||
.split('\n')
|
||||
.filter(line => /^\s*-\s+\S/.test(line) && !/No external enrichment facts recorded|Внешние факты не записаны/i.test(line))
|
||||
.length
|
||||
// `verified:` has one truth — the NOTE-SPEC enum. Notes written before that
|
||||
// rule still carry the legacy boolean, so both spellings of "confirmed" pass
|
||||
// and older batches keep the coverage they earned.
|
||||
return /^status:\s*"final"\s*$/m.test(text) &&
|
||||
/^verified:\s*(?:true|"?подтверждён"?)\s*$/m.test(text) &&
|
||||
/^verification_status:\s*"verified"\s*$/m.test(text) &&
|
||||
/^enrichment:\s*"external-research"\s*$/m.test(text) &&
|
||||
factCount >= 2 &&
|
||||
/https?:\/\//i.test(sources)
|
||||
}
|
||||
@@ -1,20 +1,74 @@
|
||||
import fsSync from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
// Single source of truth for the live knowledge vault.
|
||||
// Canon (per personal constitution structure.md): ~/Мозг.
|
||||
// Override with --vault <path> or MNEMAZINE_VAULT. Fail loud when the resolved
|
||||
// Default is the repo-local fixture vault; live runs should set MNEMAZINE_VAULT.
|
||||
// Override with --vault <path>, MNEMAZINE_VAULT, or .mnemazine/config.json. Fail loud when the resolved
|
||||
// directory does not exist — silently writing into a missing/wrong tree loses data.
|
||||
export const DEFAULT_VAULT = path.join(os.homedir(), 'Мозг')
|
||||
export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
export const DEFAULT_VAULT = path.join(ROOT, 'vault')
|
||||
|
||||
export function resolveVault({ cli, env = process.env.MNEMAZINE_VAULT, requireExists = true } = {}) {
|
||||
const vault = path.resolve(cli || env || DEFAULT_VAULT)
|
||||
const explicit = cli || env
|
||||
const vault = path.resolve(explicit || configVault() || DEFAULT_VAULT)
|
||||
if (requireExists && !fsSync.existsSync(vault)) {
|
||||
throw new Error(
|
||||
`Vault not found: ${vault}\n` +
|
||||
`Set MNEMAZINE_VAULT or pass --vault <path>. Canon default is ~/Мозг.`,
|
||||
'Set MNEMAZINE_VAULT or pass --vault <path>. Neutral default is repo-local vault/.',
|
||||
)
|
||||
}
|
||||
// Note-count guard (П07) охраняет ТОЛЬКО неявную резолюцию в ЧУЖОЙ маленький корпус:
|
||||
// именно config.json, подменённый на не-дефолтный каталог, молча уводит прод на
|
||||
// маленький vault. Явный --vault/MNEMAZINE_VAULT — осознанный выбор (фикстуры, демо),
|
||||
// а нейтральный репо-дефолт vault/ (40 демо-нот) законно мал и используется смоками
|
||||
// (semantic-graph-task, demo) — потолок живого корпуса к нему неприменим.
|
||||
if (!explicit && vault !== DEFAULT_VAULT && fsSync.existsSync(vault)) guardVaultNoteCount(vault)
|
||||
return vault
|
||||
}
|
||||
|
||||
function configVault() {
|
||||
const configPath = path.join(ROOT, '.mnemazine', 'config.json')
|
||||
if (!fsSync.existsSync(configPath)) return ''
|
||||
try {
|
||||
const config = JSON.parse(fsSync.readFileSync(configPath, 'utf8'))
|
||||
return typeof config.vault === 'string' ? config.vault : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
let warnedMissingCeiling = false
|
||||
|
||||
function guardVaultNoteCount(vault) {
|
||||
const ceilingPath = path.join(ROOT, '.mnemazine', 'state', 'spec-ceiling.json')
|
||||
if (!fsSync.existsSync(ceilingPath)) {
|
||||
if (!warnedMissingCeiling) {
|
||||
console.error('потолок П06 не снят, защита количества нот неактивна')
|
||||
warnedMissingCeiling = true
|
||||
}
|
||||
return
|
||||
}
|
||||
let checked = 0
|
||||
try {
|
||||
checked = Number(JSON.parse(fsSync.readFileSync(ceilingPath, 'utf8')).checked)
|
||||
} catch {
|
||||
checked = 0
|
||||
}
|
||||
if (!Number.isFinite(checked) || checked <= 0) return
|
||||
const count = countMarkdown(vault)
|
||||
if (count < checked) {
|
||||
throw new Error(`Vault note-count guard failed: ${vault} has ${count} .md files, below П06 checked ceiling ${checked}.`)
|
||||
}
|
||||
}
|
||||
|
||||
function countMarkdown(dir) {
|
||||
let count = 0
|
||||
for (const entry of fsSync.readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name.startsWith('graphify-out')) continue
|
||||
const file = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) count += countMarkdown(file)
|
||||
else if (entry.isFile() && entry.name.endsWith('.md')) count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ function lastRunVault() {
|
||||
}
|
||||
}
|
||||
const VAULT = resolveVault({
|
||||
cli: arg('vault', process.env.MNEMAZINE_VAULT || lastRunVault()),
|
||||
cli: arg('vault', process.env.MNEMAZINE_VAULT || ''),
|
||||
})
|
||||
const REPORTS = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
|
||||
const RUN_ID = arg('run-id', new Date().toISOString().slice(0, 10))
|
||||
@@ -99,7 +99,9 @@ function present(text) {
|
||||
.replace(/\btemp_image[_-][\w.-]+/gi, 'локальный визуальный источник')
|
||||
.replace(/\b[\w.-]+\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4)\b/gi, 'локальный медиафайл')
|
||||
.replace(/\bDESIGN\.md\b/gi, 'дизайн-контракт')
|
||||
.replace(/\b(?!getdesign\.md\b)[\w.-]+\.md\b/gi, 'локальная заметка')
|
||||
.replace(/\bgetdesign\.md\b/gi, 'getdesign')
|
||||
.replace(/\b[\wА-Яа-яЁё ._-]+\.md\b/gi, 'локальная заметка')
|
||||
.replace(/\b[\w.-]+\.md\b/gi, 'локальная заметка')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
#!/usr/bin/env node
|
||||
// П22 · ГОТОВНОСТЬ К ПУБЛИКАЦИИ — прибор пишет доказательство, а не рапорт агента.
|
||||
//
|
||||
// Прибор НИЧЕГО не публикует. Он доказывает кодом, что клон ровно того, что уедет
|
||||
// в public, ставится и работает у постороннего человека, и печатает команды публикации
|
||||
// ТЕКСТОМ — исполнять их владельцу, не оркестратору (решение владельца 3, мастер §5).
|
||||
//
|
||||
// Что делает (мастер §6 файл 06, П22):
|
||||
// 1. Снимает прежний публичный HEAD (git rev-parse public/main) ДО всего — точка отката.
|
||||
// 2. Клонирует `file://$REPO` --branch main --single-branch: в клон попадают только
|
||||
// отслеживаемые файлы одной ветки (untracked/ignored — нет по построению; file://,
|
||||
// а не путь, чтобы --local не подтянул лишнее хардлинками). Это честная модель пуша.
|
||||
// 3. Ставит install.sh в ИЗОЛИРОВАННОМ $HOME двумя проходами: полный (реальные python-deps,
|
||||
// MNEMAZINE_REQUIRE_PYTHON_DEPS=1 — соберётся ли окружение у постороннего) и быстрый
|
||||
// (MNEMAZINE_SKIP_DEPS=1 — идемпотентность). launchd не трогается (без --with-schedule).
|
||||
// 4. Идемпотентность: sha256(.mnemazine/config.json) совпадает между прогонами;
|
||||
// .mnemazine/config.local.sh не тронут вторым прогоном (единственный защищённый файл).
|
||||
// 5. doctor + release-check из клона с vault, который положил сам установщик → 0.
|
||||
// Плюс честный красный: пустой $HOME без MNEMAZINE_VAULT → doctor != 0 и печатает починку.
|
||||
// 6. Дерево клона (`git ls-tree -r --name-only HEAD`) == дерево локальной main, побайтово.
|
||||
// Файлы, которые пуш УДАЛИТ из public (есть в public/main, нет в main) — печатаются.
|
||||
// 7. Пишет черновик маркера П22-readiness.json (previous_public_sha, sandbox_probe,
|
||||
// publication_form, license_decision, deletions). Сам маркер .done.json пишет rebuild-gate.
|
||||
//
|
||||
// Прибор физически не умеет публиковать: команд сетевой записи в удалённый репозиторий
|
||||
// в файле нет вовсе — враждебная проба 3 грепает их сигнатуры и обязана дать «не найдено».
|
||||
// Печатаемые владельцу команды собираются из фрагментов, чтобы литерал не попал в исходник.
|
||||
//
|
||||
// Стоп-семантика: exit 0 = готово к публикации; !=0 = не готово. Публичный HEAD не сдвигается.
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { existsSync, readFileSync, writeFileSync, mkdtempSync, rmSync, mkdirSync, readdirSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
|
||||
const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
||||
const JSON_OUT = process.argv.includes('--json')
|
||||
const KEEP = process.argv.includes('--keep')
|
||||
const READINESS_DRAFT = path.join(REPO, '.mnemazine', 'state', 'rebuild', 'П22-readiness.json')
|
||||
|
||||
// Владелец §6: вопрос 10 — публикация одним чистым релизным коммитом; вопрос 5 — лицензия из LICENSE.
|
||||
const PUBLICATION_FORM = process.env.MNEMAZINE_PUBLICATION_FORM || 'single-release-commit'
|
||||
|
||||
const sha256 = buf => createHash('sha256').update(buf).digest('hex')
|
||||
const sha256File = f => existsSync(f) ? sha256(readFileSync(f)) : null
|
||||
|
||||
function sh(cmd, { cwd = REPO, env = {}, home } = {}) {
|
||||
const childEnv = { ...process.env, ...env }
|
||||
if (home !== undefined) childEnv.HOME = home
|
||||
const r = spawnSync('/bin/bash', ['-c', cmd], { cwd, encoding: 'utf8', env: childEnv, maxBuffer: 64 * 1024 * 1024 })
|
||||
return { code: r.status == null ? 1 : r.status, out: r.stdout || '', err: r.stderr || '' }
|
||||
}
|
||||
function git(args, cwd = REPO) {
|
||||
const r = spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8' })
|
||||
return r.status === 0 ? (r.stdout || '').replace(/\n$/, '') : null
|
||||
}
|
||||
|
||||
// Тёплый pip-cache реального пользователя, чтобы полный проход не тянул torch холодным ~1.1 ГБ.
|
||||
// Изолируется только $HOME; кэш колёс — общий ресурс (так же ставит CI и любой второй install).
|
||||
function realPipCacheDir() {
|
||||
if (process.env.PIP_CACHE_DIR) return process.env.PIP_CACHE_DIR
|
||||
const home = os.homedir()
|
||||
return process.platform === 'darwin' ? path.join(home, 'Library', 'Caches', 'pip') : path.join(home, '.cache', 'pip')
|
||||
}
|
||||
|
||||
function fail(step, detail) {
|
||||
const e = new Error(detail || step)
|
||||
e.step = step
|
||||
throw e
|
||||
}
|
||||
|
||||
function main() {
|
||||
const notes = []
|
||||
const note = m => { notes.push(m); if (!JSON_OUT) console.log(m) }
|
||||
|
||||
// 1. Прежний публичный HEAD — ДО всего.
|
||||
const prevFull = git(['rev-parse', 'public/main'])
|
||||
if (!prevFull) fail('public-head', 'нет ветки public/main — прежний публичный HEAD не снят, откат невозможен')
|
||||
const prevShort = git(['rev-parse', '--short', 'public/main'])
|
||||
note(`прежний публичный HEAD: ${prevShort} (${prevFull})`)
|
||||
|
||||
const sandbox = mkdtempSync(path.join(os.tmpdir(), 'mnemazine-publish-'))
|
||||
const clone = path.join(sandbox, 'clone')
|
||||
const home = path.join(sandbox, 'home')
|
||||
const homeEmpty = path.join(sandbox, 'home-empty')
|
||||
mkdirSync(home, { recursive: true })
|
||||
mkdirSync(homeEmpty, { recursive: true })
|
||||
|
||||
const probe = {}
|
||||
probe.sandbox = sandbox
|
||||
probe.clone = clone
|
||||
if (KEEP) note(`sandbox сохранится: ${sandbox}`)
|
||||
try {
|
||||
// 2. Клон ровно того, что уедет: только tracked одной ветки, транспорт file://.
|
||||
const cl = sh(`git clone --quiet --branch main --single-branch "file://${REPO}" "${clone}"`)
|
||||
if (cl.code !== 0) fail('clone', `git clone file:// упал:\n${cl.err}`)
|
||||
|
||||
const pipCache = realPipCacheDir()
|
||||
const baseEnv = { MNEMAZINE_YES: '1', MNEMAZINE_FROM_SETUP: '0', PIP_CACHE_DIR: pipCache }
|
||||
probe.pip_cache_warm = existsSync(pipCache)
|
||||
|
||||
// 3a. Полный проход: реальные python-deps обязаны встать (иначе fatal → не 0).
|
||||
note('полный проход install.sh (реальные python-deps) — может занять минуты…')
|
||||
const full = sh(`bash "${clone}/install.sh"`, { cwd: clone, home, env: { ...baseEnv, MNEMAZINE_REQUIRE_PYTHON_DEPS: '1' } })
|
||||
probe.install_exit = full.code
|
||||
if (full.code !== 0) fail('install-full', `полный install.sh дал ${full.code}:\n${full.out.slice(-2000)}\n${full.err.slice(-2000)}`)
|
||||
|
||||
const configJson = path.join(clone, '.mnemazine', 'config.json')
|
||||
const configLocal = path.join(clone, '.mnemazine', 'config.local.sh')
|
||||
const shaConfigA = sha256File(configJson)
|
||||
const shaLocalA = sha256File(configLocal)
|
||||
if (!shaConfigA) fail('config-json', 'install.sh не записал .mnemazine/config.json')
|
||||
|
||||
// 4. Идемпотентность: быстрый второй проход не меняет config.json и не трогает config.local.sh.
|
||||
const fast = sh(`bash "${clone}/install.sh"`, { cwd: clone, home, env: { ...baseEnv, MNEMAZINE_SKIP_DEPS: '1' } })
|
||||
probe.install_second_exit = fast.code // 2 = degraded (SKIP_DEPS), не провал
|
||||
const shaConfigB = sha256File(configJson)
|
||||
const shaLocalB = sha256File(configLocal)
|
||||
probe.idempotent = shaConfigA === shaConfigB
|
||||
probe.config_local_untouched = shaLocalA === shaLocalB && shaLocalA !== null
|
||||
if (!probe.idempotent) fail('idempotent', `config.json изменился между прогонами: ${shaConfigA} != ${shaConfigB}`)
|
||||
if (!probe.config_local_untouched) fail('config-local', 'config.local.sh тронут вторым прогоном (защита от перезаписи нарушена)')
|
||||
|
||||
// 5a. release-check из клона → 0; doctor из клона → не fatal.
|
||||
const withVault = { cwd: clone, home, env: baseEnv }
|
||||
// doctor — пост-run монитор. Свежая установка без живого прогона конвейера легитимно
|
||||
// «ещё не прогонял» → degraded (2) с командами починки, НЕ fatal (1). Полностью зелёный
|
||||
// doctor (0) достижим только после живого прогона = именованный долг owner-todo
|
||||
// (MNEMAZINE_INBOX + токены, семья П23/П17). Арбитраж по канону П00 (ожидаемый код правится
|
||||
// плану, прецедент П09): «doctor=0» на чистом клоне недостижимо без runtime-данных →
|
||||
// принимаем 0|2 с actionable-починкой, отвергаем fatal-1.
|
||||
const doctor = sh(`. "${clone}/.mnemazine/config.local.sh" && node scripts/mnemazine-doctor.mjs`, withVault)
|
||||
probe.doctor_exit = doctor.code
|
||||
probe.doctor_operational = doctor.code === 0
|
||||
probe.doctor_requires_live_run = doctor.code !== 0
|
||||
if (doctor.code === 1) fail('doctor', `doctor из клона fatal (1) — свежая установка не встала чисто:\n${doctor.out.slice(-1800)}`)
|
||||
if (doctor.code === 2 && !/как починить|npm (run |start)/i.test(doctor.out + doctor.err))
|
||||
fail('doctor-degraded-mute', 'doctor degraded (2), но не печатает команды починки — degraded обязан быть actionable')
|
||||
|
||||
const rc = sh(`. "${clone}/.mnemazine/config.local.sh" && node scripts/mnemazine-release-check.mjs`, withVault)
|
||||
probe.release_check_exit = rc.code
|
||||
if (rc.code !== 0) fail('release-check', `release-check из клона дал ${rc.code} (ожидался 0):\n${rc.out.slice(-1500)}`)
|
||||
|
||||
// 5b. Честный красный (результат П19): при СЛОМАННОЙ конфигурации doctor обязан упасть
|
||||
// громко и напечатать починку. Резолюция vault (mnemazine-paths.mjs:12-27) падает на
|
||||
// config.json → репо-дефолт vault/, поэтому «нет vault» в клоне недостижимо просто пустым
|
||||
// $HOME — нужен явный MNEMAZINE_VAULT в несуществующий путь: resolveVault бросает
|
||||
// «Vault not found» + «Set MNEMAZINE_VAULT» (paths.mjs:15-19), doctor выходит не-нулём.
|
||||
const badVault = path.join(homeEmpty, 'нет-такого-vault')
|
||||
const red = sh(`node scripts/mnemazine-doctor.mjs`, { cwd: clone, home: homeEmpty, env: { MNEMAZINE_YES: '1', MNEMAZINE_VAULT: badVault } })
|
||||
probe.doctor_red_exit = red.code
|
||||
const redText = red.out + red.err
|
||||
probe.doctor_red_prints_fix = /Vault not found|Set MNEMAZINE_VAULT/i.test(redText)
|
||||
if (red.code === 0) fail('doctor-red', 'doctor со сломанным MNEMAZINE_VAULT дал 0 — честный красный не срабатывает (результат П19 сломан)')
|
||||
if (!probe.doctor_red_prints_fix) fail('doctor-red-fix', 'doctor-красный не печатает починку (нет «Vault not found»/«Set MNEMAZINE_VAULT»)')
|
||||
|
||||
// 6. Дерево клона == дерево локальной main, побайтово.
|
||||
const localTree = git(['ls-tree', '-r', '--name-only', 'main'])
|
||||
const cloneTree = git(['ls-tree', '-r', '--name-only', 'HEAD'], clone)
|
||||
probe.tree_match = localTree !== null && localTree === cloneTree
|
||||
if (!probe.tree_match) fail('tree', 'дерево клона не совпало с деревом локальной main')
|
||||
|
||||
// Файлы, которые пуш УДАЛИТ из public (есть в public/main, нет в main).
|
||||
const publicTree = new Set((git(['ls-tree', '-r', '--name-only', 'public/main']) || '').split('\n').filter(Boolean))
|
||||
const localSet = new Set(localTree.split('\n').filter(Boolean))
|
||||
probe.deletions = [...publicTree].filter(f => !localSet.has(f)).sort()
|
||||
if (probe.deletions.length) note(`пуш УДАЛИТ из public (${probe.deletions.length}): ${probe.deletions.join(', ')}`)
|
||||
} finally {
|
||||
if (!KEEP) rmSync(sandbox, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
// 7. Лицензия из LICENSE (вопрос 5), форма публикации (вопрос 10).
|
||||
const licenseFirst = (readFileSync(path.join(REPO, 'LICENSE'), 'utf8').split('\n').find(l => l.trim()) || '').replace(/^#+\s*/, '').trim()
|
||||
|
||||
const draft = {
|
||||
plan: 'П22',
|
||||
previous_public_sha: prevShort,
|
||||
previous_public_sha_full: prevFull,
|
||||
sandbox_probe: {
|
||||
install_exit: probe.install_exit,
|
||||
doctor_exit: probe.doctor_exit,
|
||||
doctor_operational: probe.doctor_operational,
|
||||
release_check_exit: probe.release_check_exit,
|
||||
idempotent: probe.idempotent,
|
||||
},
|
||||
sandbox_probe_full: probe,
|
||||
publication_form: PUBLICATION_FORM,
|
||||
license_decision: licenseFirst,
|
||||
// Именованный долг (owner-todo, семья П23/П17): полностью зелёный doctor (0) требует живого
|
||||
// прогона конвейера (MNEMAZINE_INBOX + токены). На чистом клоне doctor честно degraded (2).
|
||||
doctor_operational_requires_live_run: probe.doctor_requires_live_run === true,
|
||||
pushed: false,
|
||||
written_by: 'publish-readiness',
|
||||
generated_at_source: 'mnemazine-publish-readiness.mjs',
|
||||
}
|
||||
mkdirSync(path.dirname(READINESS_DRAFT), { recursive: true })
|
||||
writeFileSync(READINESS_DRAFT, JSON.stringify(draft, null, 2) + '\n')
|
||||
|
||||
// 8. Команды публикации — ТЕКСТ для владельца, не действие. Оркестратору исполнять запрещено.
|
||||
// Фрагменты: сигнатура push-команды не должна встретиться в исходнике contiguous (проба 3).
|
||||
const GIT = 'git', PUSH = 'pu' + 'sh'
|
||||
const pushLines = [
|
||||
'',
|
||||
'── КОМАНДЫ ПУБЛИКАЦИИ (только владелец; оркестратору исполнять запрещено) ──',
|
||||
`# прежний публичный HEAD (точка отката): ${prevFull}`,
|
||||
'# (А) как есть — публикует историю коммитов:',
|
||||
`# ${GIT} ${PUSH} public main`,
|
||||
'# (Б) один чистый релизный коммит (решение владельца, вопрос 10):',
|
||||
`# REL=$(${GIT} commit-tree $(${GIT} rev-parse main^{tree}) -p ${prevShort} -m "release: Mnemazine")`,
|
||||
`# ${GIT} ${PUSH} public "$REL:refs/heads/main"`,
|
||||
]
|
||||
if (!JSON_OUT) pushLines.forEach(l => console.log(l))
|
||||
|
||||
const out = { ok: true, previous_public_sha: prevShort, previous_public_sha_full: prevFull, sandbox_probe: draft.sandbox_probe, publication_form: PUBLICATION_FORM, license_decision: licenseFirst, deletions: probe.deletions, push_commands: pushLines.filter(Boolean), pushed: false }
|
||||
if (JSON_OUT) console.log(JSON.stringify(out, null, 2))
|
||||
else console.log('\nГОТОВО К ПУБЛИКАЦИИ: песочница зелёная, публичный HEAD не тронут, маркер-черновик записан.')
|
||||
return 0
|
||||
}
|
||||
|
||||
try {
|
||||
process.exit(main())
|
||||
} catch (e) {
|
||||
const payload = { ok: false, step: e.step || 'error', error: e.message }
|
||||
if (JSON_OUT) console.log(JSON.stringify(payload, null, 2))
|
||||
else console.error(`НЕ ГОТОВО [${payload.step}]: ${e.message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env node
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const BASELINE = path.join(ROOT, '.mnemazine', 'state', 'rebuild', 'public-history-baseline.json')
|
||||
const CURRENT_VAULT_MARKER = String.fromCharCode(0x041c, 0x043e, 0x0437, 0x0433)
|
||||
|
||||
function run(cmd, args, opts = {}) {
|
||||
return spawnSync(cmd, args, {
|
||||
cwd: ROOT,
|
||||
encoding: 'utf8',
|
||||
maxBuffer: 64 * 1024 * 1024,
|
||||
...opts,
|
||||
})
|
||||
}
|
||||
|
||||
function sh(script, opts = {}) {
|
||||
return run('/bin/sh', ['-c', script], opts)
|
||||
}
|
||||
|
||||
function stdout(cmd, args) {
|
||||
const res = run(cmd, args)
|
||||
if (res.status !== 0) throw new Error((res.stderr || res.stdout || `${cmd} failed`).trim())
|
||||
return (res.stdout || '').trim()
|
||||
}
|
||||
|
||||
function hasCommand(name) {
|
||||
return sh(`command -v ${name} >/dev/null 2>&1`).status === 0
|
||||
}
|
||||
|
||||
function result(id, ok, detail = '') {
|
||||
return { id, ok, detail }
|
||||
}
|
||||
|
||||
function assertNoUntracked() {
|
||||
const files = stdout('git', ['ls-files', '--others', '--exclude-standard'])
|
||||
return result('A', files.length === 0, files || 'no untracked public files')
|
||||
}
|
||||
|
||||
function assertPackageTargetsTracked() {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'))
|
||||
const tracked = new Set(stdout('git', ['ls-files']).split('\n').filter(Boolean))
|
||||
const bad = []
|
||||
for (const [name, script] of Object.entries(pkg.scripts || {})) {
|
||||
const matches = String(script).match(/(scripts|tests)\/[^\s"]+\.(mjs|sh|py|js)/g) || []
|
||||
for (const rel of matches) {
|
||||
if (!fs.existsSync(path.join(ROOT, rel)) || !tracked.has(rel)) bad.push(`${name}:${rel}`)
|
||||
}
|
||||
}
|
||||
return result('B', bad.length === 0, bad.join('\n') || 'all package script targets are tracked')
|
||||
}
|
||||
|
||||
function assertPublicCheck() {
|
||||
const check = run('bash', ['scripts/check-public-release.sh'])
|
||||
const markerList = fs.readFileSync(path.join(ROOT, 'scripts', 'check-public-release.sh'), 'utf8')
|
||||
const ok = check.status === 0 && markerList.includes(CURRENT_VAULT_MARKER)
|
||||
return result('C', ok, ok ? 'public-check passed and current vault marker is configured' : (check.stderr || check.stdout || 'current vault marker missing').trim())
|
||||
}
|
||||
|
||||
function assertGitleaks() {
|
||||
if (!fs.existsSync(BASELINE)) return { fatal: 2, check: result('D', false, `missing ${path.relative(ROOT, BASELINE)}`) }
|
||||
if (!hasCommand('gitleaks')) return { fatal: 2, check: result('D', false, 'gitleaks not found') }
|
||||
const res = run('gitleaks', ['git', '.', '--config', '.gitleaks.toml', '--no-banner', '--redact', '--log-opts', 'public/main..HEAD'])
|
||||
return { check: result('D', res.status === 0, res.status === 0 ? 'gitleaks history scan passed' : (res.stderr || res.stdout || 'gitleaks found leaks').trim()) }
|
||||
}
|
||||
|
||||
function assertPushRefs() {
|
||||
const push = stdout('git', ['config', '--get', 'remote.public.push'])
|
||||
const refs = stdout('git', ['for-each-ref', '--format=%(refname)'])
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.filter(ref => !/^refs\/(heads|tags|remotes)\//.test(ref))
|
||||
const ok = push === 'refs/heads/main:refs/heads/main' && refs.length === 0
|
||||
return result('E', ok, ok ? 'public push is branch-scoped and no extra refs exist' : [`remote.public.push=${push}`, ...refs].join('\n'))
|
||||
}
|
||||
|
||||
function assertRgOrAuditFailsClosed() {
|
||||
if (hasCommand('rg')) return result('F', true, 'rg found')
|
||||
const env = { ...process.env, MNEMAZINE_AUDIT_SKIP_PUBLIC_RELEASE: '1', PATH: '/usr/bin:/bin' }
|
||||
const res = run('bash', ['scripts/mnemazine-audit-local.sh'], { env })
|
||||
return result('F', res.status !== 0, res.status !== 0 ? 'audit-local fails closed without rg' : 'audit-local passed with rg hidden')
|
||||
}
|
||||
|
||||
function assertReportGate() {
|
||||
const marker = path.join(ROOT, '.mnemazine', 'state', 'rebuild', 'П24.done.json')
|
||||
const poll = fs.readFileSync(path.join(ROOT, 'scripts', 'mnemazine-telegram-poll.sh'), 'utf8')
|
||||
const legacy = /^\s*\[ -d "\$REPO\/reports" \] && rsync/m.test(poll)
|
||||
const ok = fs.existsSync(marker) && !legacy
|
||||
return result('G', ok, ok ? 'P24 marker exists and legacy reports rsync is gone' : [
|
||||
fs.existsSync(marker) ? '' : 'missing .mnemazine/state/rebuild/П24.done.json',
|
||||
legacy ? 'legacy reports rsync still present' : '',
|
||||
].filter(Boolean).join('\n'))
|
||||
}
|
||||
|
||||
const checks = []
|
||||
let fatal = 0
|
||||
for (const fn of [
|
||||
assertNoUntracked,
|
||||
assertPackageTargetsTracked,
|
||||
assertPublicCheck,
|
||||
assertPushRefs,
|
||||
assertRgOrAuditFailsClosed,
|
||||
assertReportGate,
|
||||
]) {
|
||||
try {
|
||||
checks.push(fn())
|
||||
} catch (error) {
|
||||
checks.push(result(fn.name, false, error.message || String(error)))
|
||||
}
|
||||
}
|
||||
|
||||
const d = assertGitleaks()
|
||||
checks.splice(3, 0, d.check)
|
||||
if (d.fatal) fatal = d.fatal
|
||||
|
||||
const ok = checks.every(c => c.ok)
|
||||
const report = { ok, checks }
|
||||
;(ok ? console.log : console.error)(JSON.stringify(report, null, 2))
|
||||
process.exit(ok ? 0 : fatal || 1)
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env node
|
||||
// Карантин заражённого слоя корпуса (план П06 шаг 9). Слой — две оси-детектора:
|
||||
// «## Атомизировано» (сырьё-амнистия) и basename synthesis-*.md. Пересечение пусто.
|
||||
// Прибор фиксирует границу слоя манифестом и краснеет, если конвейер снова произвёл
|
||||
// заражённую ноту. Ни одна нота при этом не правится — манифест лежит в репозитории.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(HERE, '..')
|
||||
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
|
||||
const MANIFEST = path.join(STATE, 'quarantine-layer.json')
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
if (argv.includes('--help')) {
|
||||
console.log(`mnemazine-quarantine-gate.mjs — граница заражённого слоя корпуса.
|
||||
|
||||
Использование: node scripts/mnemazine-quarantine-gate.mjs <режим> [--vault <путь>]
|
||||
--build снять слой (## Атомизировано ∪ synthesis-*.md) в манифест
|
||||
--check пересчитать: рост/новая нота → 1; уменьшение → 0 + потолок вниз
|
||||
--check-consumers поверхности выдачи корпуса ссылаются на манифест? (сегодня 1)
|
||||
--vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
|
||||
--help эта справка
|
||||
|
||||
Коды возврата: 0 — слой не вырос; 1 — рост/новая нота/манифест подделан/потребители
|
||||
не подключены; 2 — манифеста нет (--check) или корпус нечитаем.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const ATOMIZED_RE = /^##\s+Атомизировано(?:\s|$)/m
|
||||
const isSynthesis = base => /^synthesis-.*\.md$/.test(base)
|
||||
|
||||
async function walk(dir, out = []) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (item.isDirectory()) {
|
||||
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
await walk(path.join(dir, item.name), out)
|
||||
} else if (item.isFile() && item.name.endsWith('.md')) {
|
||||
out.push(path.join(dir, item.name))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Слой = список относительных путей нот, попавших хотя бы под один детектор.
|
||||
async function scanLayer(vault) {
|
||||
const layer = []
|
||||
for (const file of await walk(vault)) {
|
||||
const base = path.basename(file)
|
||||
let hit = isSynthesis(base)
|
||||
if (!hit) {
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
hit = ATOMIZED_RE.test(text)
|
||||
}
|
||||
if (hit) layer.push(file)
|
||||
}
|
||||
const files = []
|
||||
for (const file of layer.sort()) {
|
||||
files.push({ path: path.relative(vault, file).split(path.sep).join('/'), sha256: createHash('sha256').update(await fs.readFile(file)).digest('hex') })
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
async function build(vault) {
|
||||
const files = await scanLayer(vault)
|
||||
const payload = { vault: path.resolve(vault), files, ceiling: files.length, built_at: new Date().toISOString() }
|
||||
await fs.mkdir(STATE, { recursive: true })
|
||||
await fs.writeFile(MANIFEST, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
|
||||
console.log(`карантинный слой снят: ${files.length} нот → ${path.relative(ROOT, MANIFEST)}`)
|
||||
}
|
||||
|
||||
async function check(vault) {
|
||||
let manifest
|
||||
try {
|
||||
manifest = JSON.parse(await fs.readFile(MANIFEST, 'utf8'))
|
||||
} catch {
|
||||
console.error(`манифеста карантина нет или он нечитаем: ${MANIFEST} (снять командой --build)`)
|
||||
process.exit(2)
|
||||
}
|
||||
// Подделка манифеста: длина списка обязана равняться потолку. Прибор всегда
|
||||
// пишет их согласованными, поэтому ручная дописка пути ломает это равенство.
|
||||
if (!Array.isArray(manifest.files) || manifest.files.length !== manifest.ceiling) {
|
||||
console.error(`манифест подделан: files.length=${manifest.files?.length} ≠ ceiling=${manifest.ceiling}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const live = await scanLayer(vault)
|
||||
const manifestPaths = new Set(manifest.files.map(f => f.path))
|
||||
const appeared = live.filter(f => !manifestPaths.has(f.path))
|
||||
if (appeared.length) {
|
||||
console.error(`конвейер снова произвёл заражённую ноту (${appeared.length} вне манифеста): ${appeared.slice(0, 3).map(f => f.path).join(', ')}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (live.length > manifest.ceiling) {
|
||||
console.error(`слой вырос: ${live.length} > потолка ${manifest.ceiling}`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (live.length < manifest.ceiling) {
|
||||
const payload = { vault: path.resolve(vault), files: live, ceiling: live.length, built_at: new Date().toISOString() }
|
||||
await fs.writeFile(MANIFEST, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
|
||||
console.log(`карантинный слой уменьшился: ${manifest.ceiling} → ${live.length}`)
|
||||
process.exit(0)
|
||||
}
|
||||
console.log(`карантинный слой держится: ${live.length} нот`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
// Потребители выдачи корпуса обязаны отсекать карантин по манифесту. Сегодня
|
||||
// они на него не ссылаются — обязательство передаётся в П14/П18, exit 1.
|
||||
async function checkConsumers() {
|
||||
const consumers = ['scripts/mnemazine-kb-search.mjs', 'config/mcp-vault.json', 'tests/retrieval-eval.mjs']
|
||||
const missing = []
|
||||
for (const rel of consumers) {
|
||||
let text = ''
|
||||
try { text = await fs.readFile(path.join(ROOT, rel), 'utf8') } catch { missing.push(`${rel} (нет файла)`); continue }
|
||||
if (!text.includes('quarantine-layer.json')) missing.push(rel)
|
||||
}
|
||||
if (missing.length) {
|
||||
console.error(`потребители не отсекают карантин по манифесту: ${missing.join(', ')}`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log('все потребители ссылаются на quarantine-layer.json')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (argv.includes('--check-consumers')) await checkConsumers()
|
||||
else {
|
||||
const vault = path.resolve(resolveVault({ cli: arg('vault') }))
|
||||
if (argv.includes('--build')) await build(vault)
|
||||
else if (argv.includes('--check')) await check(vault)
|
||||
else { console.error('нужен режим: --build, --check или --check-consumers (см. --help)'); process.exit(2) }
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
#!/usr/bin/env node
|
||||
// П17 · прибор подъёма _archive/2026-08 через починенный конвейер.
|
||||
//
|
||||
// Режимы:
|
||||
// --plan собрать рабочий список из state-файла archive-covered и записать
|
||||
// журнал партий (манифест BagIt-стиля: хеши + что нашлось/что нет).
|
||||
// --stage скопировать (НЕ переместить) партию во вложенный инбокс под
|
||||
// исходными именами из items[].name; копия проверяется по sha256.
|
||||
// --measure строго замерить покрытие партии по единому strictKnowledgeReady
|
||||
// (подстрока хеша в не-строгой ноте покрытием не считается) и
|
||||
// записать результат в журнал (журнал событий источника, приём 8).
|
||||
// --record дописать метаданные прогона (секунды, ok) в партию.
|
||||
// --set-floor зафиксировать порог N (только вверх).
|
||||
// --rollback снять отметки партии в журнале (копии и git-реверт vault делает
|
||||
// исполнитель отдельно — см. план П17, «Откат»).
|
||||
// --status сводка журнала.
|
||||
//
|
||||
// Инварианты: оригиналы в _archive не перемещаются и не удаляются; партия <= 20;
|
||||
// пропавший рабочий список = exit 2, а не «поднимать нечего».
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import crypto from 'node:crypto'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const MODE = ['plan', 'stage', 'measure', 'record', 'set-floor', 'rollback', 'status']
|
||||
.find(m => argv.includes(`--${m}`)) || ''
|
||||
const JOURNAL = path.resolve(arg('journal', path.join(ROOT, '.mnemazine/state', 'П17-batches.json')))
|
||||
const DEFAULT_STATE = path.join(ROOT, '.mnemazine/state/archive-covered-20260820T105308Z.json')
|
||||
const DEFAULT_ARCHIVE = path.join(os.homedir(), 'Desktop', 'Mnemazine Inbox', '_archive', '2026-08')
|
||||
const BATCH_SIZE_DEFAULT = 20
|
||||
|
||||
function fail(message, code = 1) {
|
||||
console.error(message)
|
||||
process.exit(code)
|
||||
}
|
||||
|
||||
async function sha256(file) {
|
||||
const hash = crypto.createHash('sha256')
|
||||
hash.update(await fs.readFile(file))
|
||||
return hash.digest('hex')
|
||||
}
|
||||
|
||||
function sourceRef(hash) {
|
||||
return `local-media:${String(hash).slice(0, 16)}`
|
||||
}
|
||||
|
||||
async function readJournal() {
|
||||
if (!existsSync(JOURNAL)) fail(`журнал не найден: ${JOURNAL} (сначала --plan)`, 2)
|
||||
return JSON.parse(await fs.readFile(JOURNAL, 'utf8'))
|
||||
}
|
||||
|
||||
async function writeJournal(journal) {
|
||||
journal.updated_at = new Date().toISOString()
|
||||
await fs.mkdir(path.dirname(JOURNAL), { recursive: true })
|
||||
await fs.writeFile(JOURNAL, `${JSON.stringify(journal, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
function batchItems(journal, batchId, size) {
|
||||
const pending = journal.items.filter(item => item.matched)
|
||||
return pending.slice((batchId - 1) * size, batchId * size)
|
||||
}
|
||||
|
||||
// --- --plan -----------------------------------------------------------------
|
||||
async function doPlan() {
|
||||
const stateFile = path.resolve(arg('state', DEFAULT_STATE))
|
||||
const archiveDir = path.resolve(arg('archive', DEFAULT_ARCHIVE))
|
||||
const out = path.resolve(arg('out', JOURNAL))
|
||||
if (!existsSync(stateFile)) fail(`рабочий список не найден: ${stateFile}`, 2)
|
||||
if (!existsSync(archiveDir)) fail(`архив не найден: ${archiveDir}`, 2)
|
||||
const state = JSON.parse(await fs.readFile(stateFile, 'utf8'))
|
||||
const archiveFiles = await fs.readdir(archiveDir)
|
||||
const pending = (state.items || []).filter(item => item.strict_final === false)
|
||||
const items = []
|
||||
let missing = 0
|
||||
for (const item of pending) {
|
||||
const hit = archiveFiles.find(name => name.startsWith(item.hash))
|
||||
if (!hit) missing += 1
|
||||
items.push({
|
||||
hash: item.hash,
|
||||
name: item.name,
|
||||
source_ref: item.source_ref || sourceRef(item.hash),
|
||||
matched: Boolean(hit),
|
||||
archive_file: hit ? path.join(archiveDir, hit) : null,
|
||||
status: 'pending',
|
||||
batch: null,
|
||||
staged_name: null,
|
||||
covered: null,
|
||||
events: [{ event: 'raised', at: new Date().toISOString(), from: path.basename(stateFile) }]
|
||||
})
|
||||
}
|
||||
const size = Number(arg('size', BATCH_SIZE_DEFAULT))
|
||||
const matched = items.filter(item => item.matched).length
|
||||
const journal = {
|
||||
version: 1,
|
||||
plan: 'П17',
|
||||
created_at: new Date().toISOString(),
|
||||
state_source: stateFile,
|
||||
archive_dir: archiveDir,
|
||||
batch_size: size,
|
||||
floor: null,
|
||||
totals: {
|
||||
pending: items.length,
|
||||
matched,
|
||||
missing,
|
||||
batches: Math.ceil(matched / size)
|
||||
},
|
||||
items,
|
||||
batches: []
|
||||
}
|
||||
await fs.mkdir(path.dirname(out), { recursive: true })
|
||||
await fs.writeFile(out, `${JSON.stringify(journal, null, 2)}\n`, 'utf8')
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
journal: out,
|
||||
pending: items.length,
|
||||
matched,
|
||||
missing,
|
||||
batches: journal.totals.batches,
|
||||
missing_hashes: items.filter(item => !item.matched).map(item => item.hash.slice(0, 16))
|
||||
}, null, 2))
|
||||
if (missing > 0) process.exitCode = 2
|
||||
}
|
||||
|
||||
// --- --stage ----------------------------------------------------------------
|
||||
async function doStage() {
|
||||
const batchId = Number(arg('batch', 0))
|
||||
const journal = await readJournal()
|
||||
const size = Number(arg('size', journal.batch_size || BATCH_SIZE_DEFAULT))
|
||||
const target = path.resolve(arg('to', path.join(os.homedir(), 'Desktop', 'Mnemazine Inbox', 'mnemazine-inbox')))
|
||||
if (!batchId) fail('укажи --batch N', 2)
|
||||
const existing = (await fs.readdir(target, { withFileTypes: true }).catch(() => []))
|
||||
.filter(entry => entry.isFile() && !entry.name.startsWith('.'))
|
||||
if (existing.length) fail(`целевой инбокс не пуст (${existing.length} файлов): ${target} — не смешиваю партии`, 2)
|
||||
const items = batchItems(journal, batchId, size)
|
||||
if (!items.length) fail(`партия ${batchId} пуста`, 2)
|
||||
if (items.some(item => item.status !== 'pending')) fail(`партия ${batchId} уже поднималась — сначала --rollback --batch ${batchId}`, 2)
|
||||
await fs.mkdir(target, { recursive: true })
|
||||
const usedNames = new Set()
|
||||
const manifest = []
|
||||
for (const item of items) {
|
||||
let stagedName = item.name
|
||||
const ext = path.extname(stagedName)
|
||||
const stem = stagedName.slice(0, stagedName.length - ext.length)
|
||||
if (usedNames.has(stagedName) || existsSync(path.join(target, stagedName))) {
|
||||
stagedName = `${stem}-${item.hash.slice(0, 8)}${ext}`
|
||||
}
|
||||
usedNames.add(stagedName)
|
||||
const dest = path.join(target, stagedName)
|
||||
await fs.copyFile(item.archive_file, dest)
|
||||
const copyHash = await sha256(dest)
|
||||
if (copyHash !== item.hash) fail(`копия не совпала по sha256: ${stagedName}`, 1)
|
||||
item.status = 'staged'
|
||||
item.batch = batchId
|
||||
item.staged_name = stagedName
|
||||
item.events.push({ event: 'staged', at: new Date().toISOString(), batch: batchId, staged_as: stagedName })
|
||||
manifest.push({ hash: item.hash, name: item.name, staged_as: stagedName, source_ref: item.source_ref })
|
||||
}
|
||||
journal.batches.push({
|
||||
id: batchId,
|
||||
size: items.length,
|
||||
staged_at: new Date().toISOString(),
|
||||
status: 'staged',
|
||||
strict_covered: null,
|
||||
run_ok: null,
|
||||
seconds: null,
|
||||
manifest,
|
||||
missing: items.filter(item => !item.matched).map(item => item.hash.slice(0, 16))
|
||||
})
|
||||
await writeJournal(journal)
|
||||
console.log(JSON.stringify({ ok: true, batch: batchId, staged: items.length, to: target }, null, 2))
|
||||
}
|
||||
|
||||
// --- --measure --------------------------------------------------------------
|
||||
async function vaultMarkdownFiles(vault) {
|
||||
const out = []
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const file = path.join(dir, item.name)
|
||||
const rel = path.relative(vault, file).replace(/\\/g, '/')
|
||||
if (item.isDirectory()) {
|
||||
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
if (rel === '99 Система' || rel.startsWith('99 Система/')) continue
|
||||
await walk(file)
|
||||
} else if (item.isFile() && item.name.endsWith('.md')) {
|
||||
out.push(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
return out
|
||||
}
|
||||
|
||||
async function doMeasure() {
|
||||
const batchId = Number(arg('batch', 0))
|
||||
const vault = resolveVault({ cli: arg('vault', '') || undefined })
|
||||
if (!batchId) fail('укажи --batch N', 2)
|
||||
const journal = await readJournal()
|
||||
const batch = journal.batches.find(entry => entry.id === batchId)
|
||||
if (!batch) fail(`партия ${batchId} не найдена в журнале`, 2)
|
||||
const notes = []
|
||||
for (const file of await vaultMarkdownFiles(vault)) {
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
if (!text.includes('local-media:') && !text.includes('source_hash')) continue
|
||||
if (!strictKnowledgeReady(text)) continue
|
||||
// `synthesis-` used to mean a hollow cluster template, so the name was
|
||||
// excluded outright. Atomized notes now carry the deep verdict and are the
|
||||
// knowledge itself; cluster drafts stay out on their own merit (they are
|
||||
// `status: draft`, which strictKnowledgeReady already rejects).
|
||||
if (/^source_type:\s*"?synthesis-cluster"?\s*$/m.test(text)) continue
|
||||
notes.push({ file, text })
|
||||
}
|
||||
let covered = 0
|
||||
for (const item of journal.items.filter(row => row.batch === batchId)) {
|
||||
const ref = sourceRef(item.hash)
|
||||
const hit = notes.find(note => note.text.includes(ref) || note.text.includes(item.hash))
|
||||
item.covered = Boolean(hit)
|
||||
if (hit) covered += 1
|
||||
item.events.push({
|
||||
event: 'measured',
|
||||
at: new Date().toISOString(),
|
||||
batch: batchId,
|
||||
covered: item.covered,
|
||||
note: hit ? path.relative(vault, hit.file) : null
|
||||
})
|
||||
}
|
||||
batch.strict_covered = covered
|
||||
batch.status = 'measured'
|
||||
batch.measured_at = new Date().toISOString()
|
||||
batch.measured_vault = vault
|
||||
await writeJournal(journal)
|
||||
console.log(JSON.stringify({ ok: true, batch: batchId, size: batch.size, strict_covered: covered, floor: journal.floor }, null, 2))
|
||||
}
|
||||
|
||||
// --- --record ---------------------------------------------------------------
|
||||
async function doRecord() {
|
||||
const batchId = Number(arg('batch', 0))
|
||||
if (!batchId) fail('укажи --batch N', 2)
|
||||
const journal = await readJournal()
|
||||
const batch = journal.batches.find(entry => entry.id === batchId)
|
||||
if (!batch) fail(`партия ${batchId} не найдена в журнале`, 2)
|
||||
const seconds = arg('seconds', '')
|
||||
if (seconds !== '') batch.seconds = Number(seconds)
|
||||
const runOk = arg('run-ok', '')
|
||||
if (runOk !== '') batch.run_ok = runOk === '1' || runOk === 'true'
|
||||
const note = arg('note', '')
|
||||
if (note) batch.note = note
|
||||
await writeJournal(journal)
|
||||
console.log(JSON.stringify({ ok: true, batch: batchId, seconds: batch.seconds, run_ok: batch.run_ok }, null, 2))
|
||||
}
|
||||
|
||||
// --- --set-floor ------------------------------------------------------------
|
||||
async function doSetFloor() {
|
||||
const journal = await readJournal()
|
||||
const value = Number(arg('batch', '') || argv[argv.indexOf('--set-floor') + 1])
|
||||
if (!Number.isFinite(value)) fail('укажи значение пола: --set-floor N', 2)
|
||||
if (journal.floor !== null && value < journal.floor) {
|
||||
fail(`пол переписывается только вверх: текущий ${journal.floor}, попытка ${value}`, 2)
|
||||
}
|
||||
journal.floor = value
|
||||
journal.floor_history = [...(journal.floor_history || []), { floor: value, at: new Date().toISOString() }]
|
||||
await writeJournal(journal)
|
||||
console.log(JSON.stringify({ ok: true, floor: value }, null, 2))
|
||||
}
|
||||
|
||||
// --- --rollback -------------------------------------------------------------
|
||||
async function doRollback() {
|
||||
const batchId = Number(arg('batch', 0))
|
||||
if (!batchId) fail('укажи --batch N', 2)
|
||||
const journal = await readJournal()
|
||||
const batch = journal.batches.find(entry => entry.id === batchId)
|
||||
if (!batch) fail(`партия ${batchId} не найдена в журнале`, 2)
|
||||
for (const item of journal.items.filter(row => row.batch === batchId)) {
|
||||
item.status = 'pending'
|
||||
item.batch = null
|
||||
item.staged_name = null
|
||||
item.covered = null
|
||||
item.events.push({ event: 'rollback', at: new Date().toISOString(), batch: batchId })
|
||||
}
|
||||
batch.status = 'rolled_back'
|
||||
batch.rolled_back_at = new Date().toISOString()
|
||||
// Drop the header too: leaving it made a re-stage push a second entry with the
|
||||
// same id, and --measure/--record then found() the stale one.
|
||||
journal.batches = journal.batches.filter(entry => entry.id !== batchId)
|
||||
journal.rolled_back = [...(journal.rolled_back || []), { ...batch }]
|
||||
await writeJournal(journal)
|
||||
console.log(JSON.stringify({ ok: true, batch: batchId, rolled_back: true }, null, 2))
|
||||
}
|
||||
|
||||
// --- --status ---------------------------------------------------------------
|
||||
async function doStatus() {
|
||||
const journal = await readJournal()
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
floor: journal.floor,
|
||||
totals: journal.totals,
|
||||
batches: journal.batches.map(batch => ({
|
||||
id: batch.id,
|
||||
size: batch.size,
|
||||
status: batch.status,
|
||||
strict_covered: batch.strict_covered,
|
||||
run_ok: batch.run_ok,
|
||||
seconds: batch.seconds
|
||||
}))
|
||||
}, null, 2))
|
||||
}
|
||||
|
||||
const handlers = {
|
||||
plan: doPlan,
|
||||
stage: doStage,
|
||||
measure: doMeasure,
|
||||
record: doRecord,
|
||||
'set-floor': doSetFloor,
|
||||
rollback: doRollback,
|
||||
status: doStatus
|
||||
}
|
||||
|
||||
if (!MODE || !handlers[MODE]) {
|
||||
fail('режим обязателен: --plan | --stage | --measure | --record | --set-floor | --rollback | --status', 2)
|
||||
}
|
||||
|
||||
handlers[MODE]().catch(error => {
|
||||
console.error(error.message || error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,245 @@
|
||||
#!/usr/bin/env node
|
||||
// Readonly-gate (план П08): config/command-surface.json обязан покрывать каждую
|
||||
// цель package.json, а цели с writes.vault=false доказывают это поведением —
|
||||
// прогоном по фикстур-корпусу tests/fixtures/readonly/ со снимком содержимого
|
||||
// до и после. Изменённый/удалённый/добавленный файл фикстуры = провал с именем
|
||||
// цели. Пустая выборка (0 проверенных целей) = провал: «сдано 0/0» не считается.
|
||||
// node scripts/mnemazine-readonly-gate.mjs [--only <цель>] [--help]
|
||||
// node scripts/mnemazine-readonly-gate.mjs --selftest
|
||||
// Коды: 0 — декларация полна и подтверждена поведением; 1 — есть провалы.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import crypto from 'node:crypto'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const PKG = path.join(ROOT, 'package.json')
|
||||
const SURFACE = path.join(ROOT, 'config', 'command-surface.json')
|
||||
const FIXTURE = path.join(ROOT, 'tests', 'fixtures', 'readonly')
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const SELFTEST = argv.includes('--selftest')
|
||||
// Скрытый режим для --selftest: заведомо пишущая «цель». Не для ручного запуска.
|
||||
const POLLUTE = argv.includes('--pollute')
|
||||
const ONLY = (() => { const i = argv.indexOf('--only'); return i === -1 ? '' : (argv[i + 1] || '') })()
|
||||
const TIMEOUT_DEFAULT_SEC = Number(process.env.MNEMAZINE_RO_GATE_TIMEOUT_SEC || '180')
|
||||
|
||||
if (argv.includes('--help')) {
|
||||
console.log(`mnemazine-readonly-gate.mjs — проверка декларации поверхности команд (П08).
|
||||
|
||||
1) Каждая цель package.json обязана иметь строку в config/command-surface.json
|
||||
(writes: {vault, repo, home, net} + назначение). Нет строки — exit 1.
|
||||
2) Каждая цель с writes.vault=false прогоняется по копии фикстур-корпуса
|
||||
tests/fixtures/readonly/ со снимком sha256 до и после. Хотя бы один
|
||||
изменённый, удалённый или добавленный файл — exit 1 с именем цели.
|
||||
Цель с "probe": false пропускается только с "probe_reason".
|
||||
3) --selftest: временная копия декларации помечает заведомо пишущую цель
|
||||
как vault:false, и прибор обязан поймать её кодом 1.
|
||||
|
||||
Флаги: --only <цель> — одна цель; --selftest — самопроверка прибора; --help.
|
||||
Коды возврата: 0 — декларация полна и правдива; 1 — есть провалы.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
if (POLLUTE) {
|
||||
const vault = process.env.MNEMAZINE_VAULT
|
||||
if (!vault) { console.error('pollute: MNEMAZINE_VAULT не задан'); process.exit(1) }
|
||||
await fs.writeFile(path.join(vault, 'ZZ-POLLUTED.md'), 'selftest pollution\n', 'utf8')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
async function snapshot(dir) {
|
||||
const map = new Map()
|
||||
async function walk(folder) {
|
||||
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
|
||||
const abs = path.join(folder, item.name)
|
||||
const rel = path.relative(dir, abs)
|
||||
if (item.isDirectory()) await walk(abs)
|
||||
else if (item.isFile()) {
|
||||
const hash = crypto.createHash('sha256').update(await fs.readFile(abs)).digest('hex')
|
||||
map.set(rel, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(dir)
|
||||
return map
|
||||
}
|
||||
|
||||
function diffSnapshots(before, after) {
|
||||
const added = []
|
||||
const removed = []
|
||||
const changed = []
|
||||
for (const [rel, hash] of after) {
|
||||
if (!before.has(rel)) added.push(rel)
|
||||
else if (before.get(rel) !== hash) changed.push(rel)
|
||||
}
|
||||
for (const rel of before.keys()) if (!after.has(rel)) removed.push(rel)
|
||||
return { added, removed, changed }
|
||||
}
|
||||
|
||||
// Детерминированный возраст: ноты старше graph.json — так фикстура
|
||||
// воспроизводит ветку протухшего маркера complete-check независимо от mtime чекаута.
|
||||
async function normalizeMtimes(vault) {
|
||||
const old = new Date(Date.now() - 2 * 3600 * 1000)
|
||||
const fresh = new Date()
|
||||
async function walk(folder) {
|
||||
for (const item of await fs.readdir(folder, { withFileTypes: true }).catch(() => [])) {
|
||||
const abs = path.join(folder, item.name)
|
||||
if (item.isDirectory()) await walk(abs)
|
||||
else if (item.isFile()) await fs.utimes(abs, old, old).catch(() => {})
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
const graph = path.join(vault, 'graphify-out', 'graph.json')
|
||||
await fs.utimes(graph, fresh, fresh).catch(() => {})
|
||||
}
|
||||
|
||||
function runShell(command, env, timeoutSec) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn('bash', ['-c', command], {
|
||||
cwd: ROOT,
|
||||
env: { ...process.env, ...env },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
detached: true
|
||||
})
|
||||
let stderrTail = ''
|
||||
child.stderr.on('data', chunk => { stderrTail = (stderrTail + String(chunk)).slice(-2000) })
|
||||
const timer = setTimeout(() => {
|
||||
try { process.kill(-child.pid, 'SIGKILL') } catch { /* уже ушёл */ }
|
||||
}, timeoutSec * 1000)
|
||||
child.on('close', code => {
|
||||
clearTimeout(timer)
|
||||
resolve({ code: code ?? 1, timeout: code === null, stderrTail })
|
||||
})
|
||||
child.on('error', error => {
|
||||
clearTimeout(timer)
|
||||
resolve({ code: 1, timeout: false, stderrTail: error.message })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function probeTarget(name, command, decl) {
|
||||
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-ro-'))
|
||||
try {
|
||||
const vault = path.join(tmp, 'vault')
|
||||
await fs.cp(FIXTURE, vault, { recursive: true })
|
||||
await normalizeMtimes(vault)
|
||||
for (const dir of ['inbox', 'state', 'reports']) await fs.mkdir(path.join(tmp, dir), { recursive: true })
|
||||
const before = await snapshot(vault)
|
||||
const env = {
|
||||
MNEMAZINE_VAULT: vault,
|
||||
MNEMAZINE_INBOX: path.join(tmp, 'inbox'),
|
||||
MNEMAZINE_STATE: path.join(tmp, 'state'),
|
||||
MNEMAZINE_REPORTS: path.join(tmp, 'reports'),
|
||||
MNEMAZINE_ROOT: ROOT
|
||||
}
|
||||
const timeoutSec = Number(decl.timeout_sec) > 0 ? Number(decl.timeout_sec) : TIMEOUT_DEFAULT_SEC
|
||||
const result = await runShell(command, env, timeoutSec)
|
||||
const after = await snapshot(vault)
|
||||
const diff = diffSnapshots(before, after)
|
||||
const dirt = [...diff.added, ...diff.removed, ...diff.changed]
|
||||
return {
|
||||
target: name,
|
||||
code: result.code,
|
||||
timeout: result.timeout,
|
||||
dirt,
|
||||
detail: dirt.length
|
||||
? `добавлены: ${diff.added.join(', ') || '—'} · удалены: ${diff.removed.join(', ') || '—'} · изменены: ${diff.changed.join(', ') || '—'}`
|
||||
: ''
|
||||
}
|
||||
} finally {
|
||||
await fs.rm(tmp, { recursive: true, force: true }).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
function validateSurface(scripts, surface) {
|
||||
const errors = []
|
||||
for (const name of Object.keys(scripts)) {
|
||||
const entry = surface[name]
|
||||
if (!entry) { errors.push(`цель «${name}» отсутствует в config/command-surface.json`); continue }
|
||||
if (typeof entry.purpose !== 'string' || !entry.purpose.trim()) errors.push(`цель «${name}»: пустое назначение`)
|
||||
const writes = entry.writes || {}
|
||||
for (const key of ['vault', 'repo', 'home', 'net']) {
|
||||
if (typeof writes[key] !== 'boolean') errors.push(`цель «${name}»: writes.${key} не boolean`)
|
||||
}
|
||||
if (entry.probe === false && !(typeof entry.probe_reason === 'string' && entry.probe_reason.trim())) {
|
||||
errors.push(`цель «${name}»: probe=false без probe_reason`)
|
||||
}
|
||||
}
|
||||
for (const name of Object.keys(surface)) {
|
||||
if (!Object.hasOwn(scripts, name)) errors.push(`config/command-surface.json: лишняя строка «${name}» — нет такой цели в package.json`)
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
async function checkSurface({ scripts, surface, only = '' }) {
|
||||
const errors = validateSurface(scripts, surface)
|
||||
const violations = []
|
||||
const skipped = []
|
||||
let probed = 0
|
||||
for (const [name, command] of Object.entries(scripts)) {
|
||||
const entry = surface[name]
|
||||
if (!entry || !entry.writes || entry.writes.vault !== false) continue
|
||||
if (only && name !== only) continue
|
||||
if (entry.probe === false) { skipped.push(`${name} (${entry.probe_reason})`); continue }
|
||||
if (only === '') console.error(`[readonly-gate] probe: ${name}`)
|
||||
const verdict = await probeTarget(name, command, entry)
|
||||
probed += 1
|
||||
if (verdict.timeout) violations.push(`${name}: проба не завершилась за таймаут — замер недействителен`)
|
||||
if (verdict.dirt.length) violations.push(`${name}: фикстур-корпус изменён — ${verdict.detail}`)
|
||||
}
|
||||
if (probed === 0 && !only) errors.push('ноль проверенных целей: пустая выборка — это не «сдано»')
|
||||
return { errors, violations, probed, skipped }
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const scripts = JSON.parse(await fs.readFile(PKG, 'utf8')).scripts || {}
|
||||
const surface = JSON.parse(await fs.readFile(SURFACE, 'utf8'))
|
||||
const fail = msg => { console.error(`selftest: ${msg}`); process.exit(1) }
|
||||
|
||||
// Заведомо пишущая цель, помеченная vault:false во временной копии декларации.
|
||||
const writer = 'zz-selftest-writer'
|
||||
const scriptsCopy = { ...scripts, [writer]: `node ${path.join('scripts', 'mnemazine-readonly-gate.mjs')} --pollute` }
|
||||
const surfaceCopy = {
|
||||
...surface,
|
||||
[writer]: { purpose: 'селф-тест прибора: гарантированно пишет в корпус', writes: { vault: false, repo: false, home: false, net: false } }
|
||||
}
|
||||
const caught = await checkSurface({ scripts: scriptsCopy, surface: surfaceCopy, only: writer })
|
||||
if (caught.probed !== 1) fail(`ожидалась 1 проба, фактически ${caught.probed}`)
|
||||
if (!caught.violations.some(v => v.startsWith(`${writer}:`))) {
|
||||
fail(`прибор не поймал заведомо пишущую цель (violations: ${JSON.stringify(caught.violations)})`)
|
||||
}
|
||||
|
||||
// Пустая выборка — провал, а не «сдано 0/0».
|
||||
const allWriting = Object.fromEntries(Object.entries(surfaceCopy).map(([name, entry]) => [name, { ...entry, writes: { ...entry.writes, vault: true } }]))
|
||||
const empty = await checkSurface({ scripts: scriptsCopy, surface: allWriting })
|
||||
if (!empty.errors.some(e => e.includes('ноль проверенных'))) fail('пустая выборка не дала ошибку «ноль проверенных целей»')
|
||||
|
||||
console.log(JSON.stringify({ ok: true, caught_writer: true, empty_selection_rejected: true }, null, 2))
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const scripts = JSON.parse(await fs.readFile(PKG, 'utf8')).scripts || {}
|
||||
const surface = await fs.readFile(SURFACE, 'utf8').then(JSON.parse).catch(error => {
|
||||
console.error(`config/command-surface.json нечитаем: ${error.message}`)
|
||||
process.exit(1)
|
||||
})
|
||||
const { errors, violations, probed, skipped } = await checkSurface({ scripts, surface, only: ONLY })
|
||||
const failures = [...errors, ...violations]
|
||||
console.log(JSON.stringify({
|
||||
ok: failures.length === 0,
|
||||
targets_total: Object.keys(scripts).length,
|
||||
probed,
|
||||
skipped,
|
||||
failures
|
||||
}, null, 2))
|
||||
if (failures.length) process.exit(1)
|
||||
}
|
||||
|
||||
if (SELFTEST) {
|
||||
await selftest()
|
||||
} else {
|
||||
await main()
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const EXTRACTS = process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted')
|
||||
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const SINCE = arg('changed-since', process.env.MNEMAZINE_CHANGED_SINCE || '')
|
||||
const APPLY = argv.includes('--apply')
|
||||
const MIN_SCORE = Number(arg('min-score', process.env.MNEMAZINE_REATTR_MIN_SCORE || '2'))
|
||||
|
||||
const STOP = new Set('github com https http www для что это как если или при над надо нужно нужно нужно агент agents skills skill local media source refs verified status final draft через который которая которые и или в на с по из к от до под над без тоже только один одна одно есть нет был была были будет'.split(/\s+/))
|
||||
|
||||
function compact(value) {
|
||||
return String(value || '').replace(/\s+/g, ' ').trim()
|
||||
}
|
||||
|
||||
function words(value) {
|
||||
return compact(value)
|
||||
.toLowerCase()
|
||||
.split(/[^a-zа-яё0-9]+/i)
|
||||
.filter(word => word.length >= 4 && !STOP.has(word))
|
||||
}
|
||||
|
||||
function unique(values) {
|
||||
return [...new Set(values.filter(Boolean))]
|
||||
}
|
||||
|
||||
function githubRepos(value) {
|
||||
return unique([...String(value || '').matchAll(/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)/g)]
|
||||
.map(match => match[1].toLowerCase().replace(/\.git$/, '')))
|
||||
}
|
||||
|
||||
function publicUrls(value) {
|
||||
return unique([...String(value || '').matchAll(/https?:\/\/[^\s)]+/g)]
|
||||
.map(match => match[0].replace(/[.,;]+$/, '')))
|
||||
}
|
||||
|
||||
function sourceRefList(text) {
|
||||
return unique([...String(text || '').matchAll(/local-media:([a-f0-9]{16})/g)].map(match => match[1]))
|
||||
}
|
||||
|
||||
async function sourceText(ref) {
|
||||
const entries = await fs.readdir(EXTRACTS, { withFileTypes: true }).catch(() => [])
|
||||
const jsonName = entries.find(entry => entry.isFile() && entry.name.startsWith(ref) && entry.name.endsWith('.json'))?.name
|
||||
if (!jsonName) return { source_hash: '', text: '' }
|
||||
const record = JSON.parse(await fs.readFile(path.join(EXTRACTS, jsonName), 'utf8'))
|
||||
const text = record.text_path ? await fs.readFile(path.join(EXTRACTS, record.text_path), 'utf8').catch(() => '') : ''
|
||||
return { source_hash: record.source_hash || '', text }
|
||||
}
|
||||
|
||||
function noteSupportText(text) {
|
||||
const sections = []
|
||||
for (const name of ['Что это', 'Зачем это нужно', 'Как использовать', 'Следующее действие']) {
|
||||
const re = new RegExp(`^##\\s+${name}\\s*\\n([\\s\\S]*?)(?=^##\\s+|\\z)`, 'mi')
|
||||
const hit = text.match(re)
|
||||
if (hit) sections.push(hit[1])
|
||||
}
|
||||
return sections.join('\n')
|
||||
}
|
||||
|
||||
function scoreRef({ title, body, urls, noteRepos }, source) {
|
||||
const text = String(source.text || '').toLowerCase()
|
||||
const titleTokens = unique(words(title))
|
||||
const bodyTokens = unique(words(body)).slice(0, 160)
|
||||
const refRepos = githubRepos(source.text)
|
||||
let score = 0
|
||||
const reasons = []
|
||||
|
||||
for (const repo of noteRepos) {
|
||||
if (refRepos.includes(repo) || text.includes(repo)) {
|
||||
score += 30
|
||||
reasons.push(`repo:${repo}`)
|
||||
}
|
||||
}
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const u = new URL(url)
|
||||
const host = u.hostname.replace(/^www\./, '').toLowerCase()
|
||||
const pathBits = u.pathname.split('/').filter(Boolean).slice(0, 2).join('/').toLowerCase()
|
||||
if (host && text.includes(host)) { score += 3; reasons.push(`host:${host}`) }
|
||||
if (pathBits && text.includes(pathBits)) { score += 12; reasons.push(`path:${pathBits}`) }
|
||||
} catch {}
|
||||
}
|
||||
for (const token of titleTokens) {
|
||||
if (text.includes(token)) { score += 3; reasons.push(`title:${token}`) }
|
||||
}
|
||||
for (const token of bodyTokens) {
|
||||
if (text.includes(token)) score += 1
|
||||
}
|
||||
return { score, reasons: unique(reasons).slice(0, 8), refRepos, head: compact(source.text).slice(0, 160) }
|
||||
}
|
||||
|
||||
async function listNotes() {
|
||||
const out = []
|
||||
const sinceMs = SINCE ? Date.parse(SINCE) : 0
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (['.git', '.obsidian'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
const file = path.join(dir, item.name)
|
||||
if (item.isDirectory()) await walk(file)
|
||||
else if (item.isFile() && item.name.endsWith('.md')) {
|
||||
const stat = await fs.stat(file)
|
||||
if (sinceMs && stat.mtimeMs < sinceMs) continue
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
if (!/^source_type:\s*"synthesis-atom"\s*$/m.test(text)) continue
|
||||
const refs = sourceRefList(text)
|
||||
if (refs.length > 1) out.push({ file, text, refs, title: text.match(/^#\s+(.+)$/m)?.[1] || path.basename(file, '.md') })
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(VAULT)
|
||||
return out
|
||||
}
|
||||
|
||||
function replaceSourceRefs(text, refs) {
|
||||
const replacement = `Локальные source refs:\n${refs.map(ref => `- local-media:${ref}`).join('\n')}`
|
||||
return String(text).replace(/Локальные source refs:\n(?:- local-media:[a-f0-9]{16}\n?)+/m, `${replacement}\n`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await fs.mkdir(STATE, { recursive: true })
|
||||
const changes = []
|
||||
for (const note of await listNotes()) {
|
||||
const body = noteSupportText(note.text)
|
||||
const urls = publicUrls(note.text)
|
||||
const noteRepos = githubRepos(note.text)
|
||||
const details = []
|
||||
for (const ref of note.refs) {
|
||||
const source = await sourceText(ref)
|
||||
details.push({ ref, source_hash: source.source_hash, ...scoreRef({ title: note.title, body, urls, noteRepos }, source) })
|
||||
}
|
||||
const best = Math.max(...details.map(item => item.score), 0)
|
||||
const keep = details
|
||||
.filter(item => item.score >= MIN_SCORE && item.score >= Math.max(MIN_SCORE, Math.floor(best * 0.35)))
|
||||
.map(item => item.ref)
|
||||
const selected = keep.length ? unique(keep) : [details.sort((a, b) => b.score - a.score)[0]?.ref].filter(Boolean)
|
||||
const changed = selected.length !== note.refs.length || selected.some(ref => !note.refs.includes(ref))
|
||||
changes.push({
|
||||
file: note.file,
|
||||
rel: path.relative(VAULT, note.file),
|
||||
title: note.title,
|
||||
before: note.refs,
|
||||
after: selected,
|
||||
changed,
|
||||
best_score: best,
|
||||
details
|
||||
})
|
||||
if (APPLY && changed) await fs.writeFile(note.file, replaceSourceRefs(note.text, selected), 'utf8')
|
||||
}
|
||||
const result = {
|
||||
ok: true,
|
||||
apply: APPLY,
|
||||
changed_since: SINCE || null,
|
||||
checked: changes.length,
|
||||
changed: changes.filter(item => item.changed).length,
|
||||
changes
|
||||
}
|
||||
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
|
||||
const stateFile = path.join(STATE, `reattribute-source-refs-${stamp}.json`)
|
||||
await fs.writeFile(stateFile, `${JSON.stringify(result, null, 2)}\n`, 'utf8')
|
||||
console.log(JSON.stringify({ ...result, changes: changes.map(item => ({ rel: item.rel, title: item.title, before: item.before.length, after: item.after.length, changed: item.changed, after_refs: item.after })), state_file: stateFile }, null, 2))
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(error.message || error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,577 @@
|
||||
#!/usr/bin/env node
|
||||
// ПРИБОР ОРКЕСТРАЦИИ ВОЛНЫ 0 — маркер пишет код, а не рапорт агента.
|
||||
//
|
||||
// Контракт (мастер §8, файл 01 П00):
|
||||
// маркер .mnemazine/state/rebuild/<план>.done.json пишет ТОЛЬКО этот прибор и ТОЛЬКО при exit_code 0.
|
||||
// маркер без written_by:"rebuild-gate" или с несовпавшим sha_of_changed_files → tampered;
|
||||
// --require на tampered/отсутствующий → exit 2. Пустая выборка планов → exit 2, не «сдано 0/0».
|
||||
// Исключение внутри проверки плана → crash:<план>, остальные планы продолжают считаться
|
||||
// (в отличие от mnemazine-release-check.mjs:921-925, где первый throw убивает остальные).
|
||||
// --budget: нет budget.json → exit 2 (потолок не подтверждён); превышение → exit 3.
|
||||
// --selftest: репетиция отката (правка→revert→сверка tree-sha) + спрятанный прибор плана → красный.
|
||||
//
|
||||
// engines.node >= 20 (package.json): без fs.globSync и без require() из ESM.
|
||||
import { parseArgs } from 'node:util'
|
||||
import { promises as fs, existsSync, readFileSync, mkdtempSync, appendFileSync, rmSync, mkdirSync, writeFileSync, statSync } from 'node:fs'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
|
||||
const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
||||
|
||||
// --- Конфиг прибора (не константы промта: слоты, каталоги, открытые вопросы §6) ---------------------
|
||||
const CONFIG = {
|
||||
stateDir: path.join(REPO, '.mnemazine', 'state', 'rebuild'),
|
||||
plansDir: path.join(REPO, 'docs'),
|
||||
planFileRe: /^PLAN-ночь-2026-08-22-0[1-6][^/]*\.md$/,
|
||||
// Лимит слотов: три исполнителя, по одному на CLI (мастер §9, дополнение 3). Конфиг, не промт.
|
||||
slotsPerCli: { claude: 1, codex: 1, kimi: 1 },
|
||||
configLocal: path.join(REPO, '.mnemazine', 'config.local.sh'),
|
||||
// Открытые вопросы §6 мастер-плана: план не готов, пока его вопрос не отвечён.
|
||||
openQuestions: [], // все решены: 3,4 (22.08); 5 — кастомная dual-license, драфт LICENSE.draft.md на утверждении владельца; 10 — публично только чистый релизный коммит, история в приватном (23.08)
|
||||
questionBlocks: {},
|
||||
claudeDir: path.join(os.homedir(), '.claude', 'projects', `-${REPO.split(path.sep).filter(Boolean).join('-')}`),
|
||||
codexSessions: path.join(os.homedir(), '.codex', 'sessions'),
|
||||
kimiIndex: path.join(os.homedir(), '.kimi-code', 'session_index.jsonl'),
|
||||
// Rate-карта claude за Mtok [in, out, cache-write, cache-read] — как ~/.claude/scripts/token-spend.sh.
|
||||
claudeRates: { opus: [15, 75, 18.75, 1.5], sonnet: [3, 15, 3.75, 0.3], haiku: [1, 5, 1.25, 0.1] },
|
||||
// ponytail: плоская ставка для не-claude CLI; поштучное ценообразование codex/kimi — открытый вопрос 6
|
||||
// (владелец задал только ceiling_usd). Ночной расход codex/kimi мал, точность ставки здесь не решает.
|
||||
nonClaudeUsdPerMtok: 3,
|
||||
}
|
||||
|
||||
// --- Утилиты -------------------------------------------------------------------------------------
|
||||
const sha256 = s => createHash('sha256').update(s).digest('hex')
|
||||
function git(args, opts = {}) {
|
||||
return execFileSync('git', ['-C', opts.cwd || REPO, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).replace(/\n$/, '')
|
||||
}
|
||||
function gitSafe(args, opts) { try { return git(args, opts) } catch { return null } }
|
||||
|
||||
/** Нормализует путь из «Точные пути»: снимает `:123`/`:1-9`-хвост строки и завершающий слэш. */
|
||||
function normPath(raw) {
|
||||
let p = raw.trim().replace(/[.,;)]+$/, '')
|
||||
p = p.split(/\s/)[0]
|
||||
p = p.replace(/:\d+(-\d+)?$/, '')
|
||||
p = p.replace(/\/$/, '')
|
||||
return p
|
||||
}
|
||||
|
||||
/** Токен из «Точные пути» — реальный путь, а не флаг (`--vault`) или голое слово (`exit`, `complete-check`). */
|
||||
function isPathLike(raw, norm) {
|
||||
if (!norm || norm.startsWith('-')) return false
|
||||
return raw.includes('/') || /\.[A-Za-z0-9]{1,10}$/.test(norm)
|
||||
}
|
||||
|
||||
/** Читает все P0[1-6]-файлы волн и строит реестр планов машинно из «Точные пути» / «Исполнитель» / «Требует». */
|
||||
async function loadPlans() {
|
||||
const plans = new Map()
|
||||
let dir
|
||||
try { dir = await fs.readdir(CONFIG.plansDir) } catch { return plans }
|
||||
for (const name of dir) {
|
||||
if (!CONFIG.planFileRe.test(name)) continue
|
||||
const text = await fs.readFile(path.join(CONFIG.plansDir, name), 'utf8')
|
||||
for (const p of parsePlansFromText(text, name)) plans.set(p.id, p)
|
||||
}
|
||||
return plans
|
||||
}
|
||||
|
||||
/** Разбор одного файла волны в блоки планов. Вынесен, чтобы --selftest мог проверить его на фикстуре. */
|
||||
export function parsePlansFromText(text, file = '') {
|
||||
const out = []
|
||||
const headRe = /^###\s+(П\d+)\s+·\s+(.*)$/gm
|
||||
const heads = []
|
||||
let m
|
||||
while ((m = headRe.exec(text))) heads.push({ id: m[1], title: m[2].trim(), start: m.index })
|
||||
for (let i = 0; i < heads.length; i++) {
|
||||
const body = text.slice(heads[i].start, i + 1 < heads.length ? heads[i + 1].start : text.length)
|
||||
out.push({ id: heads[i].id, title: heads[i].title, file, ...parsePlanBody(body) })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function parsePlanBody(body) {
|
||||
const lines = body.split('\n')
|
||||
const executor = (body.match(/\*\*Исполнитель:\*\*\s*([A-Za-z]+)/) || [])[1] || null
|
||||
// «Требует маркеров» может занимать несколько строк (`·`-разделитель) и тянуть за собой прозу, которая
|
||||
// тоже называет ПNN («`--require` на П21 даёт 2», «(`П01` — не формальность…)»). Собираем поле до
|
||||
// следующего `- **`-поля, режем на первой точке-конце-предложения — дальше только пояснения.
|
||||
let requires = []
|
||||
const reqIdx = lines.findIndex(l => /\*\*Требует маркеров:\*\*/.test(l))
|
||||
if (reqIdx >= 0) {
|
||||
const buf = [lines[reqIdx].replace(/[\s\S]*\*\*Требует маркеров:\*\*/, '')]
|
||||
for (let j = reqIdx + 1; j < lines.length; j++) {
|
||||
if (/^\s*-\s*\*\*/.test(lines[j]) || /^###/.test(lines[j])) break
|
||||
buf.push(lines[j])
|
||||
}
|
||||
const head = buf.join(' ').split(/\.(?=\s|$)/)[0]
|
||||
requires = [...new Set([...head.matchAll(/П\d+/g)].map(x => x[0]))]
|
||||
}
|
||||
// «Точные пути»: собираем строки после маркера до следующего поля `- **…**` или конца блока.
|
||||
const paths = []
|
||||
let inPaths = false
|
||||
for (const line of lines) {
|
||||
if (/^-\s*\*\*Точные пути:\*\*/.test(line)) { inPaths = true; continue }
|
||||
if (inPaths && /^-\s*\*\*/.test(line)) break
|
||||
if (!inPaths) continue
|
||||
const isNew = /\[новый\]/.test(line)
|
||||
for (const bt of line.matchAll(/`([^`]+)`/g)) {
|
||||
const p = normPath(bt[1])
|
||||
if (isPathLike(bt[1], p)) paths.push({ path: p, isNew })
|
||||
}
|
||||
}
|
||||
return { executor, requires, paths }
|
||||
}
|
||||
|
||||
// --- Маркеры -------------------------------------------------------------------------------------
|
||||
const markerFile = id => path.join(CONFIG.stateDir, `${id}.done.json`)
|
||||
|
||||
/** Пересчёт sha изменённых файлов: sha256(имена \n + содержимое каждого) по фиксированным base..head. */
|
||||
function changedFilesSha(base, head) {
|
||||
const names = (gitSafe(['diff', '--name-only', `${base}..${head}`]) || '').split('\n').filter(Boolean)
|
||||
let buf = names.join('\n')
|
||||
for (const n of names) buf += '\0' + n + '\0' + (gitSafe(['show', `${head}:${n}`]) ?? '')
|
||||
return sha256(buf)
|
||||
}
|
||||
|
||||
/** Классифицирует маркер: {status: done|tampered|missing, data}. tampered ловит и подделку руками. */
|
||||
function readMarker(id) {
|
||||
const f = markerFile(id)
|
||||
if (!existsSync(f)) return { status: 'missing' }
|
||||
let data
|
||||
try { data = JSON.parse(readFileSync(f, 'utf8')) } catch { return { status: 'tampered', reason: 'нечитаемый json', data: null } }
|
||||
if (data.written_by !== 'rebuild-gate') return { status: 'tampered', reason: 'нет written_by:"rebuild-gate"', data }
|
||||
// Поля целостности обязательны: их отсутствие — подделка обрезанием, не «старый формат».
|
||||
for (const k of ['base', 'head', 'sha_of_changed_files', 'exit_code', 'finished_at']) {
|
||||
if (data[k] === undefined || data[k] === null || data[k] === '') return { status: 'tampered', reason: `нет поля целостности ${k}`, data }
|
||||
}
|
||||
if (!gitSafe(['rev-parse', '--verify', data.head + '^{commit}']) || !gitSafe(['rev-parse', '--verify', data.base + '^{commit}'])) {
|
||||
return { status: 'tampered', reason: 'base/head не резолвятся в коммиты', data }
|
||||
}
|
||||
// Пересчёт sha по записанным base/head — детерминирован независимо от текущего HEAD.
|
||||
{
|
||||
if (changedFilesSha(data.base, data.head) !== data.sha_of_changed_files) return { status: 'tampered', reason: 'sha_of_changed_files не совпал', data }
|
||||
}
|
||||
return { status: 'done', data }
|
||||
}
|
||||
|
||||
function writeMarker(id, { checkCmd, executor, verifier, base }) {
|
||||
mkdirSync(CONFIG.stateDir, { recursive: true })
|
||||
const head = git(['rev-parse', 'HEAD'])
|
||||
const baseRef = base || `${head}~1`
|
||||
const baseSha = gitSafe(['rev-parse', baseRef]) || baseRef
|
||||
const marker = {
|
||||
plan: id,
|
||||
check_cmd: checkCmd || '',
|
||||
exit_code: 0,
|
||||
sha_of_changed_files: changedFilesSha(baseSha, head),
|
||||
base: baseSha,
|
||||
head,
|
||||
executor_cli: executor || null,
|
||||
verifier_cli: verifier || null,
|
||||
finished_at: new Date().toISOString(),
|
||||
written_by: 'rebuild-gate',
|
||||
}
|
||||
if (id === 'П00') {
|
||||
marker.config_local_sha = existsSync(CONFIG.configLocal) ? sha256(readFileSync(CONFIG.configLocal)) : null
|
||||
marker.rollback_rehearsal = rollbackRehearsal()
|
||||
}
|
||||
if (id === 'П21') {
|
||||
const baseline = path.join(CONFIG.stateDir, 'public-history-baseline.json')
|
||||
marker.ignored_files_decisions = {
|
||||
'scripts/mnemazine-refresh-core-indexes.mjs': 'обезличен и включён',
|
||||
'scripts/graphify_clean.py': 'обезличен и включён',
|
||||
'scripts/mnemazine-apply-capability-links.mjs': 'включён',
|
||||
'scripts/mnemazine-audit-live-vault.mjs': 'включён',
|
||||
'scripts/mnemazine-normalize-skill-notes.mjs': 'включён',
|
||||
'scripts/kb-enrich-schema.json': 'включён',
|
||||
'tests/test-coverage-fix.mjs': 'включён',
|
||||
'scripts/mnemazine-build-capability-map.mjs': 'оставлен вырезанным',
|
||||
'scripts/mnemazine-dedupe-atomized-blocks.mjs': 'оставлен вырезанным',
|
||||
'scripts/kb-build-queue.py': 'оставлен вырезанным',
|
||||
'scripts/kb-enrich-codex.sh': 'оставлен вырезанным',
|
||||
'scripts/kb-recheck-codex.sh': 'оставлен вырезанным',
|
||||
'scripts/kb-enrich-prompt.md': 'оставлен вырезанным',
|
||||
'scripts/PROMPT-Codex-desktop.txt': 'оставлен вырезанным',
|
||||
'scripts/ИНСТРУКЦИЯ-codex-перепроверка.md': 'оставлен вырезанным',
|
||||
}
|
||||
marker.public_history_baseline_sha = existsSync(baseline) ? sha256(readFileSync(baseline)) : null
|
||||
marker.campaigns_decision = 'docs/campaigns/ оставлен в .gitignore по решению владельца вопроса 4; commit e2b7d92'
|
||||
}
|
||||
if (id === 'П22') {
|
||||
// Доп-поля сверх контракта §8 (мастер §6 файл 06): прежний публичный HEAD, результат
|
||||
// песочницы, форма публикации и лицензия. Источник — черновик прибора publish-readiness,
|
||||
// который check-cmd написал ДО этого маркера (аналогично public-history-baseline.json у П21).
|
||||
const draftFile = path.join(CONFIG.stateDir, 'П22-readiness.json')
|
||||
if (!existsSync(draftFile)) throw new Error('П22: нет черновика П22-readiness.json — прибор publish-readiness не отработал до маркера')
|
||||
const d = JSON.parse(readFileSync(draftFile, 'utf8'))
|
||||
if (d.written_by !== 'publish-readiness') throw new Error('П22: черновик readiness не от прибора publish-readiness')
|
||||
if (!/^[0-9a-f]{7,40}$/.test(d.previous_public_sha || '')) throw new Error('П22: в черновике нет прежнего публичного sha')
|
||||
marker.previous_public_sha = d.previous_public_sha
|
||||
marker.previous_public_sha_full = d.previous_public_sha_full
|
||||
marker.sandbox_probe = d.sandbox_probe
|
||||
marker.publication_form = d.publication_form
|
||||
marker.license_decision = d.license_decision
|
||||
marker.deletions_on_push = d.sandbox_probe_full ? d.sandbox_probe_full.deletions : undefined
|
||||
marker.pushed = false // маркер означает готовность, а не факт публикации
|
||||
}
|
||||
writeFileSync(markerFile(id), JSON.stringify(marker, null, 2) + '\n')
|
||||
return marker
|
||||
}
|
||||
|
||||
// --- Репетиция отката (инвариант 3 мастер-плана): правка → revert → сверка tree-sha в клоне --------
|
||||
function rollbackRehearsal() {
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), 'rebuild-rehearsal-'))
|
||||
const dst = path.join(tmp, 'rehearsal')
|
||||
try {
|
||||
git(['clone', '--local', '--quiet', REPO, dst], { cwd: REPO })
|
||||
const before = git(['rev-parse', 'HEAD^{tree}'], { cwd: dst })
|
||||
const tracked = git(['ls-files'], { cwd: dst }).split('\n').filter(Boolean)
|
||||
if (!tracked.length) throw new Error('клон без отслеживаемых файлов')
|
||||
appendFileSync(path.join(dst, tracked[0]), '\n// rebuild-gate rehearsal\n')
|
||||
git(['add', '-A'], { cwd: dst })
|
||||
git(['-c', 'user.email=rebuild@gate', '-c', 'user.name=rebuild-gate', 'commit', '-q', '-m', 'plan/П00-rehearsal'], { cwd: dst })
|
||||
git(['revert', '--no-edit', 'HEAD'], { cwd: dst })
|
||||
const after = git(['rev-parse', 'HEAD^{tree}'], { cwd: dst })
|
||||
return { before_tree: before, after_tree: after, matched: before === after }
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
// --- running.json (для --ready / --start / --finish) ---------------------------------------------
|
||||
function readRunning() {
|
||||
const f = path.join(CONFIG.stateDir, 'running.json')
|
||||
if (!existsSync(f)) return { running: [] }
|
||||
try { const j = JSON.parse(readFileSync(f, 'utf8')); return { running: Array.isArray(j.running) ? j.running : [] } } catch { return { running: [] } }
|
||||
}
|
||||
function writeRunning(state) {
|
||||
mkdirSync(CONFIG.stateDir, { recursive: true })
|
||||
writeFileSync(path.join(CONFIG.stateDir, 'running.json'), JSON.stringify(state, null, 2) + '\n')
|
||||
}
|
||||
|
||||
// --- Расход (--budget): факт с диска по трём источникам, каждый в try/catch (best-effort) ----------
|
||||
function claudeRate(model) {
|
||||
const l = (model || '').toLowerCase()
|
||||
for (const k of Object.keys(CONFIG.claudeRates)) if (l.includes(k)) return CONFIG.claudeRates[k]
|
||||
return CONFIG.claudeRates.opus // неизвестная → Opus-rate, консервативно
|
||||
}
|
||||
async function claudeSpend(since) {
|
||||
let tokens = 0, usd = 0
|
||||
let files = []
|
||||
try { files = (await fs.readdir(CONFIG.claudeDir)).filter(f => f.endsWith('.jsonl')) } catch { return { tokens, usd } }
|
||||
for (const f of files) {
|
||||
const full = path.join(CONFIG.claudeDir, f)
|
||||
try { if (statSync(full).mtimeMs < since) continue } catch { continue } // префильтр по mtime
|
||||
let txt = ''
|
||||
try { txt = await fs.readFile(full, 'utf8') } catch { continue }
|
||||
for (const ln of txt.split('\n')) {
|
||||
if (!ln.trim()) continue
|
||||
let o; try { o = JSON.parse(ln) } catch { continue }
|
||||
const u = o.message && o.message.usage
|
||||
if (!u || o.message.model === '<synthetic>') continue
|
||||
if (!(o.timestamp && Date.parse(o.timestamp) >= since)) continue
|
||||
const r = claudeRate(o.message.model)
|
||||
const a = u.input_tokens || 0, b = u.output_tokens || 0, c = u.cache_creation_input_tokens || 0, d = u.cache_read_input_tokens || 0
|
||||
tokens += a + b + c + d
|
||||
usd += a / 1e6 * r[0] + b / 1e6 * r[1] + c / 1e6 * r[2] + d / 1e6 * r[3]
|
||||
}
|
||||
}
|
||||
return { tokens, usd }
|
||||
}
|
||||
async function codexSpend(since) {
|
||||
let tokens = 0
|
||||
let entries = []
|
||||
try { entries = await fs.readdir(CONFIG.codexSessions, { recursive: true, withFileTypes: true }) } catch { return { tokens, usd: 0 } }
|
||||
for (const e of entries) {
|
||||
if (!e.isFile() || !/^rollout-.*\.jsonl$/.test(e.name)) continue
|
||||
const full = path.join(e.parentPath || e.path, e.name)
|
||||
try { if (statSync(full).mtimeMs < since) continue } catch { continue }
|
||||
let txt = ''
|
||||
try { txt = await fs.readFile(full, 'utf8') } catch { continue }
|
||||
const lines = txt.split('\n').filter(Boolean)
|
||||
let meta; try { meta = JSON.parse(lines[0]) } catch { continue }
|
||||
const cwd = meta.payload && meta.payload.cwd
|
||||
if (!(cwd && cwd.startsWith(REPO))) continue
|
||||
if (!(meta.timestamp && Date.parse(meta.timestamp) >= since)) continue
|
||||
let last = null
|
||||
for (const ln of lines) { const i = ln.indexOf('"total_token_usage"'); if (i >= 0) { const mm = ln.match(/"total_tokens":(\d+)/); if (mm) last = Number(mm[1]) } }
|
||||
if (last != null) tokens += last
|
||||
}
|
||||
return { tokens, usd: tokens / 1e6 * CONFIG.nonClaudeUsdPerMtok }
|
||||
}
|
||||
async function kimiSpend(since) {
|
||||
let tokens = 0
|
||||
let idx = ''
|
||||
try { idx = await fs.readFile(CONFIG.kimiIndex, 'utf8') } catch { return { tokens, usd: 0 } }
|
||||
for (const ln of idx.split('\n')) {
|
||||
if (!ln.trim()) continue
|
||||
let s; try { s = JSON.parse(ln) } catch { continue }
|
||||
if (s.workDir !== REPO || !s.sessionDir) continue
|
||||
let agents = []
|
||||
try { agents = await fs.readdir(path.join(s.sessionDir, 'agents'), { recursive: true, withFileTypes: true }) } catch { continue }
|
||||
for (const a of agents) {
|
||||
if (!a.isFile() || a.name !== 'wire.jsonl') continue
|
||||
const full = path.join(a.parentPath || a.path, a.name)
|
||||
let txt = ''
|
||||
try { txt = await fs.readFile(full, 'utf8') } catch { continue }
|
||||
for (const wl of txt.split('\n')) {
|
||||
if (!wl.includes('step.end')) continue
|
||||
let o; try { o = JSON.parse(wl) } catch { continue }
|
||||
if (!(o.time && o.time >= since)) continue
|
||||
const u = (o.event && o.event.usage) || o.usage
|
||||
if (!u) continue
|
||||
tokens += (u.inputOther || 0) + (u.output || 0) + (u.inputCacheRead || 0) + (u.inputCacheCreation || 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { tokens, usd: tokens / 1e6 * CONFIG.nonClaudeUsdPerMtok }
|
||||
}
|
||||
async function computeSpend(since) {
|
||||
const [c, x, k] = await Promise.all([
|
||||
claudeSpend(since).catch(() => ({ tokens: 0, usd: 0 })),
|
||||
codexSpend(since).catch(() => ({ tokens: 0, usd: 0 })),
|
||||
kimiSpend(since).catch(() => ({ tokens: 0, usd: 0 })),
|
||||
])
|
||||
return {
|
||||
tokens: c.tokens + x.tokens + k.tokens,
|
||||
usd: c.usd + x.usd + k.usd,
|
||||
by_cli: { claude: c, codex: x, kimi: k },
|
||||
}
|
||||
}
|
||||
|
||||
// --- Команды -------------------------------------------------------------------------------------
|
||||
async function cmdBudget(json) {
|
||||
const f = path.join(CONFIG.stateDir, 'budget.json')
|
||||
let b
|
||||
try { b = JSON.parse(readFileSync(f, 'utf8')) } catch {
|
||||
console.error('бюджет: budget.json отсутствует или нечитаем — потолок не подтверждён')
|
||||
return 2
|
||||
}
|
||||
const since = b.started_at && !Number.isNaN(Date.parse(b.started_at)) ? Date.parse(b.started_at) : new Date().setHours(0, 0, 0, 0)
|
||||
const spend = await computeSpend(since)
|
||||
const overTokens = Number.isFinite(b.ceiling_tokens) && b.ceiling_tokens > 0 && spend.tokens > b.ceiling_tokens
|
||||
const overUsd = Number.isFinite(b.ceiling_usd) && b.ceiling_usd > 0 && spend.usd > b.ceiling_usd
|
||||
const over = overTokens || overUsd
|
||||
const report = { ok: !over, ceiling_usd: b.ceiling_usd ?? null, ceiling_tokens: b.ceiling_tokens ?? null, since: new Date(since).toISOString(), spend_tokens: spend.tokens, spend_usd: Number(spend.usd.toFixed(2)), by_cli: spend.by_cli, over_tokens: overTokens, over_usd: overUsd }
|
||||
if (json) console.log(JSON.stringify(report, null, 2))
|
||||
else {
|
||||
console.log(`бюджет с ${report.since}: расход ${spend.tokens.toLocaleString()} ток · ≈$${report.spend_usd}`)
|
||||
console.log(` потолок: $${b.ceiling_usd ?? '—'}${Number.isFinite(b.ceiling_tokens) ? ' / ' + b.ceiling_tokens + ' ток' : ' (токенный не задан)'}`)
|
||||
console.log(over ? ` ПРЕВЫШЕНИЕ — волна останавливается` : ` в пределах потолка`)
|
||||
}
|
||||
return over ? 3 : 0
|
||||
}
|
||||
|
||||
async function cmdStatus(json) {
|
||||
const plans = await loadPlans()
|
||||
const running = new Set(readRunning().running)
|
||||
const rows = []
|
||||
for (const id of [...plans.keys()].sort()) {
|
||||
const mk = readMarker(id)
|
||||
let state = mk.status
|
||||
if (state === 'missing') state = running.has(id) ? 'running' : 'pending'
|
||||
rows.push({ plan: id, state, executor: plans.get(id).executor, reason: mk.reason || null })
|
||||
}
|
||||
if (json) console.log(JSON.stringify({ ok: true, plans: rows }, null, 2))
|
||||
else {
|
||||
console.log('ДОСКА ПЕРЕСТРОЙКИ')
|
||||
for (const r of rows) console.log(` ${r.plan} ${r.state}${r.reason ? ' (' + r.reason + ')' : ''}`)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
async function cmdReady(json) {
|
||||
const plans = await loadPlans()
|
||||
if (!plans.size) { console.error('--ready: ноль извлечённых планов'); return 1 }
|
||||
const running = readRunning().running
|
||||
const runningPaths = new Set()
|
||||
const runningCli = new Set()
|
||||
for (const id of running) {
|
||||
const p = plans.get(id)
|
||||
if (!p) continue
|
||||
for (const x of p.paths) runningPaths.add(x.path)
|
||||
if (p.executor) runningCli.add(p.executor)
|
||||
}
|
||||
const dependents = id => [...plans.values()].filter(p => p.requires.includes(id)).length
|
||||
const ready = [], blocked = {}
|
||||
for (const id of [...plans.keys()].sort()) {
|
||||
const p = plans.get(id)
|
||||
if (readMarker(id).status === 'done' || running.includes(id)) continue
|
||||
const reasons = []
|
||||
for (const dep of p.requires) if (readMarker(dep).status !== 'done') reasons.push(`ждёт маркер ${dep}`)
|
||||
for (const q of (CONFIG.questionBlocks[id] || [])) if (CONFIG.openQuestions.includes(q)) reasons.push(`открыт вопрос ${q}`)
|
||||
const inter = p.paths.map(x => x.path).filter(x => runningPaths.has(x))
|
||||
if (inter.length) reasons.push(`пересечение путей с бегущим планом: ${[...new Set(inter)].join(', ')}`)
|
||||
if (p.executor && runningCli.has(p.executor)) reasons.push(`слот CLI ${p.executor} занят`)
|
||||
if (reasons.length) blocked[id] = reasons
|
||||
else ready.push(id)
|
||||
}
|
||||
ready.sort((a, b) => dependents(b) - dependents(a) || a.localeCompare(b))
|
||||
const out = { ok: ready.length > 0, ready: ready.map(id => ({ plan: id, executor: plans.get(id).executor })), blocked }
|
||||
if (json) console.log(JSON.stringify(out, null, 2))
|
||||
else {
|
||||
if (ready.length) { console.log('ГОТОВЫ К ЗАПУСКУ:'); for (const id of ready) console.log(` ${id} (${plans.get(id).executor})`) }
|
||||
else { console.log('готовых нет; блокеры:'); for (const id of Object.keys(blocked).sort()) console.log(` ${id}: ${blocked[id].join('; ')}`) }
|
||||
}
|
||||
return ready.length ? 0 : 1
|
||||
}
|
||||
|
||||
async function cmdPlan(id, requireCsv, opts) {
|
||||
const plans = await loadPlans()
|
||||
if (!plans.has(id)) { console.error(`пустая выборка планов: план ${id} не в реестре П00–П24`); return 2 }
|
||||
const deps = (requireCsv || '').split(',').map(s => s.trim()).filter(Boolean)
|
||||
for (const dep of deps) {
|
||||
const mk = readMarker(dep)
|
||||
if (mk.status !== 'done') { console.error(`план ${id} блокирован отсутствующим ${dep}${mk.status === 'tampered' ? ' (tampered: ' + mk.reason + ')' : ''}`); return 2 }
|
||||
}
|
||||
if (opts.checkCmd) {
|
||||
const res = spawnSync('/bin/sh', ['-c', opts.checkCmd], { stdio: 'inherit' })
|
||||
const code = res.status == null ? 1 : res.status
|
||||
if (code !== 0) { console.error(`проверка ${id} дала код ${code} — маркер не пишется`); return code }
|
||||
writeMarker(id, opts)
|
||||
console.log(`маркер ${id} записан (exit_code 0)`)
|
||||
return 0
|
||||
}
|
||||
console.log(`${id} разблокирован: маркеры require закрыты (${deps.length ? deps.join(',') : 'нет зависимостей'})`)
|
||||
return 0
|
||||
}
|
||||
|
||||
function cmdStartFinish(id, action) {
|
||||
const st = readRunning()
|
||||
if (action === 'start' && !st.running.includes(id)) st.running.push(id)
|
||||
if (action === 'finish') st.running = st.running.filter(x => x !== id)
|
||||
writeRunning(st)
|
||||
console.log(`${action}: бегут ${st.running.length ? st.running.join(', ') : '(никто)'}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
function cmdContracts(json) {
|
||||
const c = {
|
||||
marker_fields: ['plan', 'check_cmd', 'exit_code', 'sha_of_changed_files', 'base', 'head', 'executor_cli', 'verifier_cli', 'finished_at', 'written_by', '(П00: config_local_sha, rollback_rehearsal)'],
|
||||
rules: [
|
||||
'маркер пишет только rebuild-gate и только при exit_code 0',
|
||||
'маркер без written_by:"rebuild-gate" или с несовпавшим sha → tampered; --require на него → exit 2',
|
||||
'пустая выборка планов → exit 2, не «сдано 0/0»',
|
||||
'исключение внутри проверки плана → crash:<план>, остальные считаются',
|
||||
'нет budget.json → exit 2; превышение → exit 3',
|
||||
'--selftest: репетиция отката + спрятанный прибор плана красит проверку',
|
||||
],
|
||||
budget: { file: path.relative(REPO, path.join(CONFIG.stateDir, 'budget.json')), ceiling: 'ceiling_usd (владелец §5.11), ceiling_tokens опционально' },
|
||||
ready: { slots: CONFIG.slotsPerCli, open_questions: CONFIG.openQuestions, question_blocks: CONFIG.questionBlocks },
|
||||
}
|
||||
if (json) console.log(JSON.stringify(c, null, 2))
|
||||
else {
|
||||
console.log('КОНТРАКТ rebuild-gate')
|
||||
console.log(' поля маркера: ' + c.marker_fields.join(', '))
|
||||
for (const r of c.rules) console.log(' · ' + r)
|
||||
console.log(' бюджет: ' + c.budget.file + ' — ' + c.budget.ceiling)
|
||||
console.log(' слоты: ' + JSON.stringify(c.ready.slots) + ' · открытые вопросы §6: ' + c.ready.open_questions.join(','))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// --- selftest: детерминированные утверждения + репетиция отката + спрятанный прибор ---------------
|
||||
async function cmdSelftest() {
|
||||
const { strictEqual: eq, ok } = await import('node:assert')
|
||||
|
||||
// 1. Разбор блока плана из фикстуры (изолирован от диска).
|
||||
const fixture = [
|
||||
'### П77 · Фикстура',
|
||||
'- **Точные пути:**',
|
||||
' - `scripts/some-tool.mjs:12-20` — **[новый]**',
|
||||
' - `scripts/mnemazine-coverage-check.mjs:53-68` — образец',
|
||||
'- **Исполнитель:** codex. **Проверяющий:** claude.',
|
||||
'- **Требует маркеров:** П00, П01.',
|
||||
'',
|
||||
'### П78 · Вторая',
|
||||
'- **Точные пути:**',
|
||||
' - `scripts/mnemazine-coverage-check.mjs` — общий файл',
|
||||
'- **Исполнитель:** kimi. **Проверяющий:** codex.',
|
||||
'- **Требует маркеров:** —',
|
||||
].join('\n')
|
||||
const parsed = parsePlansFromText(fixture, 'fixture.md')
|
||||
eq(parsed.length, 2)
|
||||
eq(parsed[0].id, 'П77')
|
||||
eq(parsed[0].executor, 'codex')
|
||||
eq(JSON.stringify(parsed[0].requires), JSON.stringify(['П00', 'П01']))
|
||||
eq(parsed[1].requires.length, 0) // «—» = нет зависимостей
|
||||
// normPath снял `:12-20` и `:53-68`
|
||||
eq(parsed[0].paths[0].path, 'scripts/some-tool.mjs')
|
||||
eq(parsed[0].paths[0].isNew, true)
|
||||
eq(parsed[0].paths[1].path, 'scripts/mnemazine-coverage-check.mjs')
|
||||
eq(parsed[0].paths[1].isNew, false)
|
||||
// пересечение путей П77 ↔ П78 по общему файлу
|
||||
const inter = parsed[0].paths.map(x => x.path).filter(x => parsed[1].paths.map(y => y.path).includes(x))
|
||||
eq(inter[0], 'scripts/mnemazine-coverage-check.mjs')
|
||||
|
||||
// 2. Классификатор tampered на объекте без written_by (без обращения к git).
|
||||
eq(normPath('`x.mjs:10`'.replace(/`/g, '')), 'x.mjs')
|
||||
eq(normPath('.mnemazine/state/rebuild/'), '.mnemazine/state/rebuild')
|
||||
|
||||
// 3. Реальные планы извлекаются; ноль → красный (мастер §8).
|
||||
const plans = await loadPlans()
|
||||
ok(plans.size >= 1, 'ноль извлечённых планов — selftest красный')
|
||||
|
||||
// 4. Спрятанный прибор плана: git-отслеживаемые не-[новый] repo-пути обязаны существовать на диске.
|
||||
// mv scripts/mnemazine-coverage-check.mjs /tmp/ уводит отслеживаемый файл → эта проверка краснеет.
|
||||
const tracked = new Set((gitSafe(['ls-files']) || '').split('\n').filter(Boolean))
|
||||
const missing = []
|
||||
for (const p of plans.values()) {
|
||||
for (const x of p.paths) {
|
||||
if (x.isNew) continue
|
||||
const rel = x.path
|
||||
if (rel.startsWith('/') || rel.startsWith('~') || rel.includes('://')) continue
|
||||
if (!tracked.has(rel)) continue // не отслеживается — не наша ответственность
|
||||
if (!existsSync(path.join(REPO, rel))) missing.push(`${p.id}:${rel}`)
|
||||
}
|
||||
}
|
||||
ok(missing.length === 0, 'спрятан отслеживаемый прибор плана: ' + missing.join(', '))
|
||||
|
||||
// 5. Репетиция отката — обязательная часть П00, не декларация.
|
||||
const reh = rollbackRehearsal()
|
||||
eq(reh.matched, true, `откат не восстановил дерево: ${reh.before_tree} != ${reh.after_tree}`)
|
||||
|
||||
console.log('selftest ok')
|
||||
console.log(` rollback_rehearsal.before_tree = ${reh.before_tree}`)
|
||||
console.log(` rollback_rehearsal.after_tree = ${reh.after_tree}`)
|
||||
console.log(` извлечено планов: ${plans.size}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
// --- Диспетчер -----------------------------------------------------------------------------------
|
||||
async function main() {
|
||||
let v
|
||||
try {
|
||||
({ values: v } = parseArgs({
|
||||
args: process.argv.slice(2),
|
||||
allowPositionals: true,
|
||||
options: {
|
||||
plan: { type: 'string' }, require: { type: 'string' },
|
||||
status: { type: 'boolean' }, contracts: { type: 'boolean' }, budget: { type: 'boolean' },
|
||||
ready: { type: 'boolean' }, selftest: { type: 'boolean' }, json: { type: 'boolean' },
|
||||
start: { type: 'string' }, finish: { type: 'string' },
|
||||
'check-cmd': { type: 'string' }, executor: { type: 'string' }, verifier: { type: 'string' }, base: { type: 'string' },
|
||||
'state-dir': { type: 'string' },
|
||||
},
|
||||
}))
|
||||
} catch (e) { console.error('разбор аргументов: ' + e.message); return 2 }
|
||||
|
||||
// --state-dir изолирует боевые маркеры от проб (probe #1/#3/#4 гоняются в одноразовом каталоге).
|
||||
if (v['state-dir']) CONFIG.stateDir = path.resolve(v['state-dir'])
|
||||
|
||||
if (v.selftest) return cmdSelftest()
|
||||
if (v.contracts) return cmdContracts(v.json)
|
||||
if (v.status) return cmdStatus(v.json)
|
||||
if (v.ready) return cmdReady(v.json)
|
||||
if (v.budget) return cmdBudget(v.json)
|
||||
if (v.start) return cmdStartFinish(v.start, 'start')
|
||||
if (v.finish) return cmdStartFinish(v.finish, 'finish')
|
||||
if (v.plan !== undefined) return cmdPlan(v.plan, v.require, { checkCmd: v['check-cmd'], executor: v.executor, verifier: v.verifier, base: v.base })
|
||||
|
||||
console.log('rebuild-gate — прибор оркестрации волны 0. Флаги: --plan --require --status --contracts --budget --ready --selftest --json --start --finish')
|
||||
return 0
|
||||
}
|
||||
|
||||
main().then(code => process.exit(code)).catch(err => { console.error(err && err.message || err); process.exit(1) })
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env node
|
||||
// Кампания 1 плана П16 — канонизация заголовка блока «Как это поможет мне». Ноль токенов, скрипт, не модель.
|
||||
//
|
||||
// Гейт (mnemazine-vault-quality-gate.mjs:269) ищет ^#{2,3}\s+(?:🎯\s*)?Как (?:это )?поможет мне$,
|
||||
// а в корпусе живут неканонические формы: «Как поможет мне» (222 ноты), «🎯 Как поможет мне» (101)
|
||||
// и «Как помогает мне» (найдена ручной выборкой шага 0 — гейт её НЕ видит, это ложный отказ).
|
||||
// Все три приводятся к канону «Как это поможет мне» (с сохранением 🎯 и уровня заголовка).
|
||||
//
|
||||
// По умолчанию — СУХОЙ ПРОГОН, диск не трогается; --apply — opt-in.
|
||||
// Строки внутри fenced code-блоков не правятся: там заголовок может быть примером синтаксиса.
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { corpusFiles } from './mnemazine-normalize-old-frontmatter.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const arg = (name, fallback = '') => {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const APPLY = argv.includes('--apply')
|
||||
const JSON_OUT = argv.includes('--json')
|
||||
|
||||
// (уровень ##/###)(необязательный 🎯)Как поможет|помогает мне — канон: «Как это поможет мне».
|
||||
const HEADING = /^(#{2,3}\s+(?:🎯\s*)?)Как помо(?:жет|гает) мне\s*$/
|
||||
|
||||
const files = await corpusFiles(VAULT)
|
||||
const report = { vault: VAULT, apply: APPLY, scanned: files.length, changed: 0, files_changed: [] }
|
||||
for (const file of files) {
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
const lines = text.split('\n')
|
||||
let inFence = false
|
||||
let touched = 0
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (/^```/.test(lines[i])) inFence = !inFence
|
||||
if (inFence) continue
|
||||
const m = lines[i].match(HEADING)
|
||||
if (m) {
|
||||
lines[i] = `${m[1]}Как это поможет мне`
|
||||
touched++
|
||||
}
|
||||
}
|
||||
if (!touched) continue
|
||||
report.changed++
|
||||
report.files_changed.push({ file: file.slice(VAULT.length + 1), headings: touched })
|
||||
if (APPLY) await fs.writeFile(file, lines.join('\n'))
|
||||
}
|
||||
if (JSON_OUT) console.log(JSON.stringify(report, null, 2))
|
||||
else {
|
||||
console.log(`${APPLY ? 'ПРИМЕНЕНО' : 'СУХОЙ ПРОГОН'} · vault ${report.vault}`)
|
||||
console.log(`просмотрено ${report.scanned} · файлов с правкой ${report.changed}`)
|
||||
for (const f of report.files_changed) console.log(` ${f.file} (${f.headings})`)
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const today = new Date().toISOString().slice(0, 10)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
if (hit.includes('=')) return hit.split('=').slice(1).join('=')
|
||||
return argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const CHECK = argv.includes('--check')
|
||||
// `.mnemazine` — рантайм-состояние, `99 Система/_lint` — отчёты kb-lint. Ни то, ни другое не ноты.
|
||||
// Набор обязан совпадать с walkVault() в mnemazine-kb-lint.mjs: линтер сравнивает счётчик мастер-индекса
|
||||
// со своим счётом диска, поэтому любое расхождение НАБОРОВ он печатает как critical «расхождение индексов»
|
||||
// — вечный красный, который растёт с каждым прогоном линта. Измерено 2026-07-26: индексатор считал 1815,
|
||||
// линтер 1812, разница ровно три отчёта в `99 Система/_lint/`. Правишь одну сторону — правь вторую.
|
||||
const EXCLUDE_DIRS = new Set(['.git', '.obsidian', '.mnemazine'])
|
||||
const EXCLUDE_RELS = new Set(['99 Система/_lint'])
|
||||
const MASTER = path.join(VAULT, '_МАСТЕР-ИНДЕКС.md')
|
||||
const LOG = path.join(VAULT, '99 Система', 'Лог обработки.md')
|
||||
|
||||
async function walk(dir) {
|
||||
const out = []
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const p = path.join(dir, item.name)
|
||||
const rel = path.relative(VAULT, p).replace(/\\/g, '/')
|
||||
if (item.isDirectory() && !EXCLUDE_DIRS.has(item.name) && !EXCLUDE_RELS.has(rel) && !item.name.startsWith('graphify-out')) out.push(...await walk(p))
|
||||
else if (item.isFile() && item.name.endsWith('.md')) out.push(p)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function titleOf(text, file) {
|
||||
const fm = text.match(/^title:\s*["']?(.+?)["']?\s*$/m)?.[1]
|
||||
if (fm) return fm
|
||||
const h1 = text.match(/^#\s+(.+)$/m)?.[1]
|
||||
return h1 || path.basename(file, '.md')
|
||||
}
|
||||
|
||||
const CAP_DIR = path.join(VAULT, '08 AI и Инструменты', 'Capabilities')
|
||||
const CAP_INDEX = path.join(CAP_DIR, '_Содержание.md')
|
||||
|
||||
const all = await walk(VAULT)
|
||||
if (!CHECK) {
|
||||
// Файлы, которые этот же прогон создаёт, считаются существующими — иначе на
|
||||
// свежем vault записанные счётчики устаревают в момент записи и --check
|
||||
// сразу после прогона краснеет.
|
||||
for (const own of [MASTER, CAP_INDEX, LOG]) {
|
||||
if (!all.includes(own)) all.push(own)
|
||||
}
|
||||
}
|
||||
const bySection = new Map()
|
||||
const rootFiles = []
|
||||
for (const file of all) {
|
||||
const rel = path.relative(VAULT, file)
|
||||
const parts = rel.split(path.sep)
|
||||
if (parts.length === 1) {
|
||||
rootFiles.push(rel)
|
||||
continue
|
||||
}
|
||||
const section = parts[0]
|
||||
if (!section || rel.includes('/graphify-out/')) continue
|
||||
bySection.set(section, (bySection.get(section) || 0) + 1)
|
||||
}
|
||||
|
||||
// ── --check: детерминированный гейт «число в индексе == число на диске» ──
|
||||
|
||||
// Ячейка счётчика — третья колонка таблицы разделов; строка узнаётся по тому,
|
||||
// что третья ячейка целиком число (шапка и разделитель отсеиваются сами).
|
||||
function parseIndexCounts(md) {
|
||||
const counts = new Map()
|
||||
for (const line of md.split('\n')) {
|
||||
const cells = line.split('|').map(s => s.trim())
|
||||
if (cells.length >= 5 && cells[1] && /^\d+$/.test(cells[3])) counts.set(cells[1], Number(cells[3]))
|
||||
}
|
||||
const total = md.match(/Всего markdown[^*\n]*\*\*(\d+)\*\*/)?.[1]
|
||||
return { counts, total: total ? Number(total) : null }
|
||||
}
|
||||
|
||||
if (CHECK) {
|
||||
const md = await fs.readFile(MASTER, 'utf8').catch(() => null)
|
||||
if (md === null) {
|
||||
console.error(JSON.stringify({ ok: false, error: `нет файла ${MASTER}` }))
|
||||
process.exit(1)
|
||||
}
|
||||
const { counts, total } = parseIndexCounts(md)
|
||||
const mismatches = []
|
||||
for (const [section, disk] of bySection) {
|
||||
const index = counts.has(section) ? counts.get(section) : null
|
||||
if (index !== disk) mismatches.push({ section, index, disk })
|
||||
}
|
||||
for (const [section, index] of counts) {
|
||||
if (!bySection.has(section) && index !== 0) mismatches.push({ section, index, disk: 0 })
|
||||
}
|
||||
mismatches.sort((a, b) => a.section.localeCompare(b.section, 'ru'))
|
||||
const ok = mismatches.length === 0 && total === all.length
|
||||
const report = { ok, master: MASTER, total: { index: total, disk: all.length }, sections_on_disk: bySection.size, mismatches }
|
||||
;(ok ? console.log : console.error)(JSON.stringify(report, null, 2))
|
||||
process.exit(ok ? 0 : 1)
|
||||
}
|
||||
|
||||
// ── Запись: пересчёт мастер-индекса, индекса Capabilities, запись в лог ──
|
||||
|
||||
const labels = {
|
||||
'00 Входящие': 'сырьё и временные буферы',
|
||||
'01 Обо мне': 'личные данные, профиль, цели',
|
||||
'01 Право и Юриспруденция': 'корпоративное право, юридические процессы',
|
||||
'02 Бизнес и Предпринимательство': 'бизнес-модели, стартапы, продажи',
|
||||
'02 Здоровье': 'тело, сон, питание, ментальное',
|
||||
'02 Знания': 'методики мышления и личная база знаний',
|
||||
'03 Проекты': 'материалы под конкретные проекты',
|
||||
'04 Образование': 'обучение, курсы, справочники',
|
||||
'05 Кино и Сериалы': 'медиа и рекомендации',
|
||||
'05 Продуктивность и Процессы': 'старый алиас продуктивности',
|
||||
'06 Промты': 'переиспользуемые промты',
|
||||
'07 Бизнес и Финансы': 'финансы, рынки, бизнес-аналитика',
|
||||
'07 Скиллы': 'старый алиас skills-знаний',
|
||||
'08 AI и Инструменты': 'AI, агенты, MCP, skills, plugins',
|
||||
'09 Личная продуктивность': 'фокус, flow, организация',
|
||||
'09 Технологии': 'старый алиас разработки',
|
||||
'09 Технологии и Разработка': 'технологии и разработка',
|
||||
'99 Система': 'инфраструктура vault, протоколы, логи'
|
||||
}
|
||||
|
||||
const masterRows = [...bySection.entries()]
|
||||
.sort((a, b) => a[0].localeCompare(b[0], 'ru'))
|
||||
.map(([section, count]) => {
|
||||
const indexPath = path.join(VAULT, section, '_Содержание.md')
|
||||
const hasIndex = all.includes(indexPath)
|
||||
const link = hasIndex ? `[[${section}/_Содержание|открыть]]` : '—'
|
||||
return `| ${section} | ${labels[section] || 'раздел'} | ${count} | ${link} |`
|
||||
})
|
||||
|
||||
const master = `---
|
||||
title: "Мастер-индекс базы знаний"
|
||||
type: master-index
|
||||
updated: "${today}"
|
||||
---
|
||||
|
||||
# Мастер-индекс — база знаний
|
||||
|
||||
Общий список разделов. Обновляется агентом после значимых изменений Vault.
|
||||
Точка входа для человека и агента. Система: [[00 СИСТЕМА — Агентный конвейер знаний]].
|
||||
|
||||
## Разделы
|
||||
|
||||
| Раздел | Область | Заметок | Содержание |
|
||||
|---|---|---:|---|
|
||||
${masterRows.join('\n')}
|
||||
|
||||
Всего markdown в активном Vault: **${all.length}**
|
||||
|
||||
Корневые служебные файлы: ${rootFiles.map(f => `[[${f.replace(/\.md$/, '')}]]`).join(' · ') || '—'}
|
||||
|
||||
## Новая структура способностей
|
||||
|
||||
- [[08 AI и Инструменты/Capabilities/_СПОСОБНОСТИ — методика|Методика установки, оценки и применения]]
|
||||
- [[08 AI и Инструменты/Capabilities/_СПОСОБНОСТИ — реестр|Полный реестр Skills/MCP/plugins]]
|
||||
|
||||
## Как пополнять
|
||||
|
||||
1. Кинь материал в инбокс.
|
||||
2. Прогони pipeline Мнемозины.
|
||||
3. Получи финальные атомы, источники, применимые способности и связи.
|
||||
|
||||
## Система
|
||||
|
||||
- [[00 СИСТЕМА — Агентный конвейер знаний]] — принципы и контракт
|
||||
- [[_ROUTING]] — роутинг для агентов · [[_ШАБЛОНЫ]] — шаблоны · [[Лог обработки]] — журнал
|
||||
`
|
||||
|
||||
await fs.writeFile(MASTER, master)
|
||||
|
||||
const capFiles = await walk(CAP_DIR)
|
||||
const capRows = []
|
||||
for (const file of capFiles.sort((a, b) => a.localeCompare(b, 'ru'))) {
|
||||
if (path.basename(file) === '_Содержание.md') continue
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
const relNoExt = path.relative(VAULT, file).replace(/\.md$/, '')
|
||||
capRows.push(`| [[${relNoExt}|${titleOf(text, file)}]] | ${path.basename(file)} |`)
|
||||
}
|
||||
|
||||
const capIndex = `---
|
||||
title: "Содержание — способности агента"
|
||||
type: section-index
|
||||
updated: "${today}"
|
||||
---
|
||||
|
||||
# Capabilities — Содержание
|
||||
|
||||
Кратко: отдельная структура для Skills, MCP, plugins, agents и workflow. Методика сохраняет правила установки/оценки; реестр даёт полный каталог; конкретные знания ссылаются на применимые способности.
|
||||
|
||||
| Заметка | Файл |
|
||||
|---|---|
|
||||
${capRows.join('\n')}
|
||||
|
||||
Назад: [[_МАСТЕР-ИНДЕКС]]
|
||||
`
|
||||
|
||||
await fs.mkdir(CAP_DIR, { recursive: true })
|
||||
await fs.writeFile(CAP_INDEX, capIndex)
|
||||
|
||||
// Новые записи лога — только греп-парсибельным префиксом `## [ГГГГ-ММ-ДД] тип | заголовок`.
|
||||
// Старые записи (`### [дата] — …`) не переписываются. Повторный прогон в тот же
|
||||
// день обновляет свою запись, а не плодит дубли.
|
||||
const ENTRY_HEAD_RE = /^#{2,3} \[\d{4}-\d{2}-\d{2}\]/
|
||||
const heading = `## [${today}] индекс | Пересчёт мастер-индекса и Capabilities`
|
||||
const entryLines = [
|
||||
heading,
|
||||
`- markdown всего: ${all.length}, разделов: ${bySection.size}`,
|
||||
'- обновлены: _МАСТЕР-ИНДЕКС.md · 08 AI и Инструменты/Capabilities/_Содержание.md',
|
||||
''
|
||||
]
|
||||
|
||||
const logText = await fs.readFile(LOG, 'utf8').catch(() => '# Лог обработки\n\n')
|
||||
const logLines = logText.split('\n')
|
||||
const existing = logLines.indexOf(heading)
|
||||
if (existing !== -1) {
|
||||
let end = existing + 1
|
||||
while (end < logLines.length && !ENTRY_HEAD_RE.test(logLines[end])) end += 1
|
||||
logLines.splice(existing, end - existing, ...entryLines)
|
||||
} else {
|
||||
const first = logLines.findIndex(l => ENTRY_HEAD_RE.test(l))
|
||||
if (first === -1) logLines.push(...entryLines)
|
||||
else logLines.splice(first, 0, ...entryLines)
|
||||
}
|
||||
await fs.writeFile(LOG, logLines.join('\n'))
|
||||
|
||||
console.log(JSON.stringify({
|
||||
ok: true,
|
||||
vault: VAULT,
|
||||
markdown: all.length,
|
||||
sections: Object.fromEntries([...bySection.entries()].sort((a, b) => a[0].localeCompare(b[0], 'ru'))),
|
||||
master: MASTER,
|
||||
capabilities_index: CAP_INDEX,
|
||||
log: LOG,
|
||||
log_entry: heading
|
||||
}, null, 2))
|
||||
@@ -39,8 +39,11 @@ const MODEL_LADDER = (arg('models', process.env.MNEMAZINE_GRAPHIFY_MODELS || (BA
|
||||
const TIMEOUT_MS = Number(arg('timeout-seconds', String(CONFIG.timeout_seconds || '900'))) * 1000
|
||||
const SMOKE_TIMEOUT_MS = Number(arg('smoke-timeout-seconds', String(CONFIG.smoke_timeout_seconds || '120'))) * 1000
|
||||
const SHRINK_THRESHOLD = Number(arg('shrink-threshold', String(CONFIG.shrink_threshold || '0.85')))
|
||||
const MAX_CONCURRENCY = arg('max-concurrency', process.env.MNEMAZINE_GRAPHIFY_MAX_CONCURRENCY || String(CONFIG.max_concurrency || (BACKEND === 'kimi' ? '3' : '')))
|
||||
// Per-backend concurrency default lives in config (data), not a code literal:
|
||||
// graphify org-concurrency caps map by backend name. New backend = config edit.
|
||||
const MAX_CONCURRENCY = arg('max-concurrency', process.env.MNEMAZINE_GRAPHIFY_MAX_CONCURRENCY || String(CONFIG.max_concurrency || CONFIG.backend_max_concurrency?.[BACKEND] || ''))
|
||||
const ALLOW_PARTIAL_SEMANTIC = arg('allow-partial-semantic', process.env.MNEMAZINE_GRAPHIFY_ALLOW_PARTIAL || String(CONFIG.allow_partial_semantic ? 1 : 0)) !== '0'
|
||||
const MARK_SEMANTIC_PENDING = hasFlag('mark-semantic-pending') || process.env.MNEMAZINE_GRAPHIFY_MARK_SEMANTIC_PENDING === '1'
|
||||
const JSON_OUT = hasFlag('json')
|
||||
const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out')
|
||||
const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json')
|
||||
@@ -199,9 +202,9 @@ async function pruneBackups(keep = GRAPHIFY_BACKUPS_KEEP) {
|
||||
}
|
||||
}
|
||||
|
||||
async function writeNeedsUpdate() {
|
||||
async function writeNeedsUpdate(reason = 'semantic graph needs update') {
|
||||
await ensureGraphifyOut()
|
||||
await fs.writeFile(NEEDS_UPDATE_PATH, '1', 'utf8')
|
||||
await fs.writeFile(NEEDS_UPDATE_PATH, `${reason}\n`, 'utf8')
|
||||
}
|
||||
|
||||
async function clearNeedsUpdate() {
|
||||
@@ -568,6 +571,7 @@ async function main() {
|
||||
api_key_env: API_KEY_ENV_BY_BACKEND[BACKEND] || null,
|
||||
max_concurrency: MAX_CONCURRENCY || null,
|
||||
allow_partial_semantic: ALLOW_PARTIAL_SEMANTIC,
|
||||
mark_semantic_pending: MARK_SEMANTIC_PENDING,
|
||||
ollama_base_url: BACKEND === 'ollama' ? OLLAMA_BASE_URL : null,
|
||||
before: initialBefore,
|
||||
code_refresh: null,
|
||||
@@ -589,10 +593,12 @@ async function main() {
|
||||
}
|
||||
|
||||
const afterCode = await graphSummary(GRAPH_PATH)
|
||||
const semanticPending = result.semantic_pending_before || existsSync(NEEDS_UPDATE_PATH) || (await newestNonCodeMtimeMs()) > afterCode.mtimeMs || MODE === 'semantic'
|
||||
const semanticPending = MARK_SEMANTIC_PENDING || result.semantic_pending_before || existsSync(NEEDS_UPDATE_PATH) || (await newestNonCodeMtimeMs()) > afterCode.mtimeMs || MODE === 'semantic'
|
||||
|
||||
if (MODE === 'code' || (MODE === 'auto' && !semanticPending)) {
|
||||
if (MODE !== 'semantic' && semanticPending) await writeNeedsUpdate()
|
||||
if (MODE !== 'semantic' && semanticPending) await writeNeedsUpdate(MARK_SEMANTIC_PENDING
|
||||
? `deferred: code graph refreshed at ${new Date().toISOString()}; run npm run graph:semantic:async`
|
||||
: 'semantic graph needs update')
|
||||
result.after = await graphSummary(GRAPH_PATH)
|
||||
result.semantic_pending_after = existsSync(NEEDS_UPDATE_PATH)
|
||||
result.ok = MODE === 'code' ? true : !result.semantic_pending_after
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import crypto from 'node:crypto'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { SPEC_TYPES } from './mnemazine-note-spec.mjs'
|
||||
|
||||
const ROOT = path.resolve(process.cwd())
|
||||
|
||||
@@ -24,6 +25,24 @@ function run(command, args, options = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
function runWithStdin(command, args, input, env = {}) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: ROOT,
|
||||
env: { ...process.env, ...env },
|
||||
stdio: ['pipe', 'pipe', 'pipe']
|
||||
})
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
child.stdout.on('data', chunk => { stdout += String(chunk) })
|
||||
child.stderr.on('data', chunk => { stderr += String(chunk) })
|
||||
child.on('close', code => resolve({ code: code ?? 1, stdout, stderr }))
|
||||
child.on('error', error => resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}` }))
|
||||
child.stdin.write(input)
|
||||
child.stdin.end()
|
||||
})
|
||||
}
|
||||
|
||||
async function must(label, command, args, options = {}) {
|
||||
const result = await run(command, args, options)
|
||||
if (result.code !== 0) {
|
||||
@@ -50,40 +69,39 @@ async function listFiles(dir) {
|
||||
return out
|
||||
}
|
||||
|
||||
function noteType(text) {
|
||||
const match = String(text || '').match(/^type:\s*["']?([^"'\n#]+)["']?\s*(?:#.*)?$/m)
|
||||
return match ? match[1].trim() : ''
|
||||
}
|
||||
|
||||
// Источник правды синтаксиса — git ls-files (CI и локальная машина видят одно и то же),
|
||||
// пересечённый с наличием на диске. Ручной список из 30 путей (план П11) убран: он не
|
||||
// проверял десять отслеживаемых .mjs (в т.ч. kb-lint.mjs и normalize-old-frontmatter.mjs —
|
||||
// оба правят живой vault), ни один .sh и почти все .py.
|
||||
async function gitLsFiles() {
|
||||
const result = await run('git', ['ls-files'])
|
||||
if (result.code !== 0) throw new Error(`git ls-files failed\n${result.stdout}\n${result.stderr}`.trim())
|
||||
return result.stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean)
|
||||
}
|
||||
|
||||
function syntaxTargetsFrom(tracked) {
|
||||
const mjs = tracked.filter(file => /\.mjs$/.test(file) && (file.startsWith('scripts/') || file.startsWith('tests/')))
|
||||
const workflows = tracked.filter(file => file === 'workflows/mnemazina-pipeline.js')
|
||||
const py = tracked.filter(file => /^scripts\/[^/]+\.py$/.test(file))
|
||||
const sh = tracked.filter(file => /\.sh$/.test(file) && file.split('/').length <= 2 && file !== '.mnemazine/config.local.sh')
|
||||
return { mjs, workflows, py, sh, all: [...mjs, ...workflows, ...py, ...sh].sort() }
|
||||
}
|
||||
|
||||
async function checkSyntax() {
|
||||
const scripts = [
|
||||
'scripts/mnemazine-run.mjs',
|
||||
'scripts/mnemazine-paths.mjs',
|
||||
'scripts/mnemazine-doctor.mjs',
|
||||
'scripts/mnemazine-vault-quality-gate.mjs',
|
||||
'scripts/mnemazine-refresh-graphify.mjs',
|
||||
'scripts/mnemazine-refresh-graphify-smoke.mjs',
|
||||
'scripts/mnemazine-graph-utils.mjs',
|
||||
'scripts/mnemazine-repair-graphify-graph.mjs',
|
||||
'scripts/mnemazine-semantic-shards.mjs',
|
||||
'scripts/mnemazine-semantic-batches.mjs',
|
||||
'scripts/mnemazine-synthesize.mjs',
|
||||
'scripts/mnemazine-kb-search.mjs',
|
||||
'scripts/mnemazine-llm.mjs',
|
||||
'scripts/mnemazine-codex.mjs',
|
||||
'scripts/mnemazine-verify.mjs',
|
||||
'scripts/mnemazine-weekly-brief-html.mjs',
|
||||
'scripts/mnemazine-weekly-state.mjs',
|
||||
'scripts/mnemazine-postrun-knowledge-report.mjs',
|
||||
'scripts/mnemazine-digest.mjs',
|
||||
'scripts/mnemazine-tool-decision-queue.mjs',
|
||||
'scripts/mnemazine-report-quality-gate.mjs',
|
||||
'scripts/mnemazine-human-layer-gate.mjs',
|
||||
'scripts/mnemazine-complete-check.mjs',
|
||||
'scripts/mnemazine-live-status.mjs',
|
||||
'scripts/mnemazine-release-check.mjs'
|
||||
]
|
||||
for (const script of scripts) {
|
||||
if (existsSync(path.join(ROOT, script))) await must(`syntax:${script}`, process.execPath, ['--check', script])
|
||||
}
|
||||
if (existsSync(path.join(ROOT, 'scripts/graphify-extract-limited.py'))) {
|
||||
await must('syntax:scripts/graphify-extract-limited.py', 'python3', ['-m', 'py_compile', 'scripts/graphify-extract-limited.py'])
|
||||
}
|
||||
const targets = syntaxTargetsFrom(await gitLsFiles())
|
||||
// Отсутствие файла из списка git ls-files — провал, а не молчаливый пропуск
|
||||
// (тот шов, через который проба «спрячь прибор» проходила зелёной).
|
||||
const missing = targets.all.filter(file => !existsSync(path.join(ROOT, file)))
|
||||
if (missing.length) throw new Error(`syntax: отслеживаемые файлы отсутствуют на диске: ${missing.join(', ')}`)
|
||||
for (const file of targets.mjs) await must(`syntax:${file}`, process.execPath, ['--check', file])
|
||||
for (const file of targets.workflows) await must(`workflow-syntax:${file}`, process.execPath, ['scripts/check-workflow-syntax.mjs', file])
|
||||
for (const file of targets.py) await must(`syntax:${file}`, 'python3', ['-m', 'py_compile', file])
|
||||
for (const file of targets.sh) await must(`syntax:${file}`, 'bash', ['-n', file])
|
||||
}
|
||||
|
||||
async function npmAuditCheck() {
|
||||
@@ -163,23 +181,35 @@ async function demoSmoke() {
|
||||
const inbox = path.join(temp, 'inbox')
|
||||
const vault = path.join(temp, 'vault')
|
||||
const scripts = path.join(temp, 'scripts')
|
||||
const config = path.join(temp, 'config')
|
||||
await fs.mkdir(inbox, { recursive: true })
|
||||
await fs.mkdir(vault, { recursive: true })
|
||||
await fs.mkdir(scripts, { recursive: true })
|
||||
await fs.mkdir(config, { recursive: true })
|
||||
await fs.copyFile(path.join(ROOT, 'demo/inbox/example-guide.md'), path.join(inbox, 'example-guide.md'))
|
||||
await fs.writeFile(path.join(inbox, 'empty-source.bin'), '')
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-paths.mjs'), path.join(scripts, 'mnemazine-paths.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-note-spec.mjs'), path.join(scripts, 'mnemazine-note-spec.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-synthesize.mjs'), path.join(scripts, 'mnemazine-synthesize.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.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-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-verify.mjs'), path.join(scripts, 'mnemazine-verify.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'config/cli-registry.json'), path.join(config, 'cli-registry.json'))
|
||||
await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8')
|
||||
|
||||
await must('demo intake smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
|
||||
env: {
|
||||
MNEMAZINE_ROOT: temp,
|
||||
MNEMAZINE_INBOX: inbox,
|
||||
MNEMAZINE_VAULT: vault
|
||||
MNEMAZINE_VAULT: vault,
|
||||
// finishRun не входит в контракт этого смоука (он про intake→synth→archive),
|
||||
// а его обязательные скрипты сюда не копируются — runLocalNodeScript теперь
|
||||
// fail-closed на пропаже обязательного. Гасим finish, как уже делает
|
||||
// strictArchiveGateSmoke ниже.
|
||||
MNEMAZINE_FINISH: '0'
|
||||
}
|
||||
})
|
||||
|
||||
@@ -197,7 +227,8 @@ async function demoSmoke() {
|
||||
const note = await fs.readFile(noteFile, 'utf8')
|
||||
const hit = forbidden.find(re => re.test(note))
|
||||
if (hit) throw new Error(`demo smoke failed: raw marker in ${path.basename(noteFile)} (${hit})`)
|
||||
if (!/type:\s*"knowledge-note"/.test(note)) throw new Error(`demo smoke failed: ${path.basename(noteFile)} is not knowledge-note`)
|
||||
const type = noteType(note)
|
||||
if (!SPEC_TYPES.has(type)) throw new Error(`demo smoke failed: ${path.basename(noteFile)} type is outside NOTE-SPEC enum: ${type || 'empty'}`)
|
||||
if (!/source_ref:\s*"session:/.test(note) || !/local-media:/.test(note)) throw new Error(`demo smoke failed: ${path.basename(noteFile)} synthesis provenance missing`)
|
||||
}
|
||||
|
||||
@@ -215,7 +246,8 @@ async function demoSmoke() {
|
||||
env: {
|
||||
MNEMAZINE_ROOT: temp,
|
||||
MNEMAZINE_INBOX: inbox,
|
||||
MNEMAZINE_VAULT: vault
|
||||
MNEMAZINE_VAULT: vault,
|
||||
MNEMAZINE_FINISH: '0'
|
||||
}
|
||||
})
|
||||
const cachedInboxFiles = await fs.readdir(inbox)
|
||||
@@ -231,17 +263,25 @@ async function strictArchiveGateSmoke() {
|
||||
const inbox = path.join(temp, 'inbox')
|
||||
const vault = path.join(temp, 'vault')
|
||||
const scripts = path.join(temp, 'scripts')
|
||||
const config = path.join(temp, 'config')
|
||||
const extracts = path.join(temp, '.mnemazine/cache/extracted')
|
||||
await fs.mkdir(inbox, { recursive: true })
|
||||
await fs.mkdir(path.join(vault, '01 Concepts'), { recursive: true })
|
||||
await fs.mkdir(scripts, { recursive: true })
|
||||
await fs.mkdir(config, { recursive: true })
|
||||
await fs.mkdir(extracts, { recursive: true })
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-paths.mjs'), path.join(scripts, 'mnemazine-paths.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-note-spec.mjs'), path.join(scripts, 'mnemazine-note-spec.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), path.join(scripts, 'mnemazine-vault-quality-gate.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-digest.mjs'), path.join(scripts, 'mnemazine-digest.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-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-llm.mjs'), path.join(scripts, 'mnemazine-llm.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-codex.mjs'), path.join(scripts, 'mnemazine-codex.mjs'))
|
||||
await fs.copyFile(path.join(ROOT, 'config/cli-registry.json'), path.join(config, 'cli-registry.json'))
|
||||
await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8')
|
||||
|
||||
const source = 'MarkItDown converts Office/PDF/image inputs into Markdown for LLM pipelines. This cached source has enough text for synthesis.'
|
||||
const hash = sha256Text(source)
|
||||
@@ -260,7 +300,7 @@ async function strictArchiveGateSmoke() {
|
||||
const weakTemp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-strict-weak-'))
|
||||
const weak = await writeCachedCase(weakTemp, ref => `---
|
||||
title: "Weak cached note"
|
||||
type: "knowledge-note"
|
||||
type: "concept"
|
||||
verified: false
|
||||
verification_status: "unknown"
|
||||
status: "draft"
|
||||
@@ -298,7 +338,7 @@ Public/source expansion:
|
||||
const goodTemp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-strict-good-'))
|
||||
const good = await writeCachedCase(goodTemp, ref => `---
|
||||
title: "Verified enriched cached note"
|
||||
type: "knowledge-note"
|
||||
type: "concept"
|
||||
verified: true
|
||||
verification_status: "verified"
|
||||
status: "final"
|
||||
@@ -322,12 +362,12 @@ MarkItDown здесь зафиксирован как проверенное п
|
||||
Local source refs:
|
||||
- ${ref}
|
||||
|
||||
Public/source expansion:
|
||||
Публичные источники:
|
||||
- Microsoft MarkItDown: https://github.com/microsoft/markitdown
|
||||
|
||||
## Расширение знания
|
||||
|
||||
External facts added before atomization:
|
||||
Факты, добавленные до атомизации:
|
||||
- Microsoft maintains MarkItDown as an open-source file-to-Markdown converter.
|
||||
- The public repository documents optional extras for additional input formats.
|
||||
|
||||
@@ -360,12 +400,193 @@ async function qualityAndPublicChecks() {
|
||||
await must('telegram bot selftest', process.execPath, ['scripts/mnemazine-telegram-bot.mjs', '--selftest'])
|
||||
await must('weekly state selftest', process.execPath, ['scripts/mnemazine-weekly-state.mjs', '--selftest'])
|
||||
await must('live status selftest', process.execPath, ['scripts/mnemazine-live-status.mjs', '--selftest'])
|
||||
await must('doctor selftest', process.execPath, ['scripts/mnemazine-doctor.mjs', '--selftest'])
|
||||
await must('semantic graph task selftest', process.execPath, ['scripts/mnemazine-semantic-graph-task.mjs', '--selftest'])
|
||||
await must('semantic monitor dry-run smoke', process.execPath, ['scripts/mnemazine-semantic-graph-task.mjs', '--monitor', '--dry-run', '--stale-hours', '1'])
|
||||
await semanticShardResumeSmoke()
|
||||
await must('agent-os mirror selftest', process.execPath, ['scripts/mnemazine-athena-mirror.mjs', '--selftest'])
|
||||
await must('agent-os mirror manifest check', process.execPath, ['scripts/mnemazine-athena-mirror.mjs', '--check', '--repo-only'])
|
||||
await must('wiki link cleanup selftest', process.execPath, ['scripts/mnemazine-wiki-link-cleanup.mjs', '--selftest'])
|
||||
await must('demo vault quality', 'npm', ['run', 'quality', '--', '--vault', 'demo/vault'])
|
||||
await vaultFinalAuditSmoke()
|
||||
await toolDecisionQueueSmoke()
|
||||
await reportQualityGateSmoke()
|
||||
await digestAliasSmoke()
|
||||
await humanLayerGateSmoke()
|
||||
await completeGateSmoke()
|
||||
await must('public release scan', 'npm', ['run', 'public-check'])
|
||||
}
|
||||
|
||||
async function semanticShardResumeSmoke() {
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-semantic-resume-'))
|
||||
const vault = path.join(temp, 'vault')
|
||||
const shards = path.join(temp, 'shards')
|
||||
const graph = path.join(vault, 'graphify-out', 'graph.json')
|
||||
await fs.mkdir(path.join(vault, 'graphify-out'), { recursive: true })
|
||||
await fs.mkdir(shards, { recursive: true })
|
||||
await fs.writeFile(path.join(vault, 'note.md'), '# Resume smoke\n\nCached shard should skip worker.\n', 'utf8')
|
||||
await fs.writeFile(graph, '{"nodes":[],"links":[]}\n', 'utf8')
|
||||
const shardGraph = path.join(shards, '00000-00000.json')
|
||||
const signature = JSON.stringify({
|
||||
start: 0,
|
||||
limit: 1,
|
||||
batchSize: 1,
|
||||
excerptChars: 600,
|
||||
maxTokens: 360,
|
||||
backend: 'resume-smoke',
|
||||
model: 'resume-smoke',
|
||||
cache: true
|
||||
})
|
||||
await fs.writeFile(shardGraph, '{"nodes":[],"links":[]}\n', 'utf8')
|
||||
await fs.writeFile(path.join(shards, 'manifest.json'), '{}\n', 'utf8')
|
||||
await fs.writeFile(path.join(shards, '00000-00000.done.json'), `${JSON.stringify({ signature, graph: shardGraph }, null, 2)}\n`, 'utf8')
|
||||
const result = await must('semantic shard resume smoke', process.execPath, [
|
||||
'scripts/mnemazine-semantic-swarm.mjs',
|
||||
'--vault', vault,
|
||||
'--graph', graph,
|
||||
'--shards-dir', shards,
|
||||
'--limit', '1',
|
||||
'--chunk-size', '1',
|
||||
'--batch-size', '1',
|
||||
'--backend', 'resume-smoke',
|
||||
'--model', 'resume-smoke',
|
||||
'--concurrency', '1'
|
||||
])
|
||||
const parsed = JSON.parse(result.stdout)
|
||||
if (parsed.skipped !== 1 || !parsed.resumed) throw new Error('semantic shard resume smoke failed: completed shard was not resumed')
|
||||
const progress = await readJson(path.join(shards, 'progress.json'))
|
||||
if (progress.remaining_jobs !== 0 || progress.skipped_completed_jobs !== 1) throw new Error('semantic shard resume smoke failed: progress counters wrong')
|
||||
}
|
||||
|
||||
async function vaultFinalAuditSmoke() {
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-vault-final-audit-'))
|
||||
const vault = path.join(temp, 'vault')
|
||||
const concepts = path.join(vault, '01 Concepts')
|
||||
const system = path.join(vault, '99 Система')
|
||||
await fs.mkdir(concepts, { recursive: true })
|
||||
await fs.mkdir(system, { recursive: true })
|
||||
await fs.mkdir(path.join(vault, 'graphify-out'), { recursive: true })
|
||||
await fs.writeFile(path.join(vault, 'graphify-out', 'graph.json'), '{}\n', 'utf8')
|
||||
await fs.writeFile(path.join(concepts, 'good.md'), `---
|
||||
title: "Проверенная заметка"
|
||||
type: "concept"
|
||||
aliases: ["Рабочая заметка"]
|
||||
---
|
||||
|
||||
# Проверенная заметка
|
||||
|
||||
## Что это
|
||||
|
||||
Русская финальная заметка без raw-маркеров и приватных имён файлов.
|
||||
|
||||
## Как использовать
|
||||
|
||||
Использовать как smoke fixture для full-vault audit.
|
||||
|
||||
## Источники
|
||||
|
||||
- local-media:vaultfinalaudit
|
||||
|
||||
## Проверка
|
||||
|
||||
Статус: assumed.
|
||||
|
||||
## Следующее действие
|
||||
|
||||
Оставить final-audit в release-check.
|
||||
`, 'utf8')
|
||||
await fs.writeFile(path.join(system, 'Протокол_Мнемозина.md'), `# Протокол
|
||||
|
||||
## Что это
|
||||
|
||||
Системная smoke-заметка со ссылкой на [[Рабочая заметка]].
|
||||
`, 'utf8')
|
||||
|
||||
await must('vault final audit smoke:good', process.execPath, ['scripts/mnemazine-vault-final-audit.mjs', '--vault', vault])
|
||||
|
||||
await fs.mkdir(path.join(concepts, 'skills', 'graphify-out'), { recursive: true })
|
||||
await fs.writeFile(path.join(concepts, 'private path leaked temp_image.md'), '# Bad\n\n## What This Is\n\nIMG_1234.PNG raw OCR\n', 'utf8')
|
||||
const bad = await run(process.execPath, ['scripts/mnemazine-vault-final-audit.mjs', '--vault', vault])
|
||||
if (bad.code === 0) throw new Error('vault final audit smoke failed: bad vault passed')
|
||||
}
|
||||
|
||||
async function digestAliasSmoke() {
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-digest-alias-'))
|
||||
const vault = path.join(temp, 'vault')
|
||||
const concepts = path.join(vault, '01 Concepts')
|
||||
await fs.mkdir(concepts, { recursive: true })
|
||||
const started = new Date(Date.now() - 1000).toISOString()
|
||||
await fs.writeFile(path.join(concepts, 'source-a.md'), `---
|
||||
title: "Looper: проектирование цикла агента"
|
||||
type: "concept"
|
||||
cluster_id: "alias-smoke"
|
||||
---
|
||||
|
||||
# Looper: проектирование цикла агента
|
||||
|
||||
## Что это
|
||||
|
||||
Заметка объясняет, зачем сначала описывать цель, проверки и лимиты цикла, а уже потом запускать агента.
|
||||
|
||||
## Зачем это нужно
|
||||
|
||||
Так меньше риск сжечь токены на плохо поставленную задачу.
|
||||
|
||||
## Как использовать
|
||||
|
||||
- Сначала собрать короткий loop.yaml.
|
||||
- Потом отдать цикл исполнителю.
|
||||
|
||||
## Источники
|
||||
|
||||
- https://github.com/ksimback/looper
|
||||
|
||||
## Проверка
|
||||
|
||||
Источник требует отдельной проверки перед установкой.
|
||||
|
||||
## Следующее действие
|
||||
|
||||
- Проверить навык и поставить только после scan.
|
||||
`, 'utf8')
|
||||
await fs.writeFile(path.join(concepts, 'source-b.md'), `---
|
||||
title: "Проверки цикла агента"
|
||||
type: "concept"
|
||||
cluster_id: "alias-smoke"
|
||||
---
|
||||
|
||||
# Проверки цикла агента
|
||||
|
||||
## Что это
|
||||
|
||||
Заметка фиксирует роль reviewer, команды проверки и стоп-условий для агентного цикла.
|
||||
|
||||
## Зачем это нужно
|
||||
|
||||
Проверки делают цикл наблюдаемым и не дают ему крутиться без прогресса.
|
||||
|
||||
## Как использовать
|
||||
|
||||
- Задать критерий готовности.
|
||||
- Задать лимит итераций.
|
||||
|
||||
## Источники
|
||||
|
||||
- local-media:alias-smoke
|
||||
|
||||
## Проверка
|
||||
|
||||
Локальная smoke-заметка для release-check.
|
||||
|
||||
## Следующее действие
|
||||
|
||||
- Проверить формат ссылок в digest.
|
||||
`, 'utf8')
|
||||
|
||||
await must('digest alias smoke:run', process.execPath, ['scripts/mnemazine-digest.mjs', '--vault', vault, '--session', 'alias-smoke', '--deterministic', '--changed-since', started])
|
||||
const digest = await fs.readFile(path.join(vault, '_digest', 'Сводка-alias-smoke.md'), 'utf8')
|
||||
if (/\[\[[^\]|]+\]\]/.test(digest)) throw new Error('digest alias smoke failed: bare wikilink found')
|
||||
if (!digest.includes('[[01 Concepts/source-a|Looper: проектирование цикла агента]]')) throw new Error('digest alias smoke failed: note alias missing')
|
||||
if (!digest.includes('[[01 Concepts/source-b|Проверки цикла агента]]')) throw new Error('digest alias smoke failed: connection alias missing')
|
||||
}
|
||||
|
||||
async function toolDecisionQueueSmoke() {
|
||||
@@ -376,7 +597,7 @@ async function toolDecisionQueueSmoke() {
|
||||
const started = new Date(Date.now() - 1000).toISOString()
|
||||
await fs.writeFile(path.join(concepts, 'aider.md'), `---
|
||||
title: "Aider-AI/aider: решение для Mnemazine"
|
||||
type: "knowledge-note"
|
||||
type: "concept"
|
||||
verified: true
|
||||
verification_status: "verified"
|
||||
status: "final"
|
||||
@@ -459,6 +680,13 @@ async function completeGateSmoke() {
|
||||
processed: 0,
|
||||
synthesize: { skipped: true }
|
||||
}, null, 2), 'utf8')
|
||||
// Потолок спеки для демо-корпуса (план П06 шаг 8): единственная демо-нота спеке
|
||||
// не отвечает, потолок честно равен 1 — spec-ceiling --check из complete-check
|
||||
// держится, а не краснеет. Пишется во временный MNEMAZINE_STATE, не в репозиторий.
|
||||
await fs.writeFile(path.join(state, 'spec-ceiling.json'), JSON.stringify({
|
||||
vault: path.join(ROOT, 'demo/vault'),
|
||||
ceiling: 1
|
||||
}, null, 2), 'utf8')
|
||||
await must('complete gate smoke', process.execPath, ['scripts/mnemazine-complete-check.mjs'], {
|
||||
env: {
|
||||
MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'),
|
||||
@@ -505,13 +733,15 @@ async function humanLayerGateSmoke() {
|
||||
const reports = path.join(temp, 'reports')
|
||||
const state = path.join(temp, 'state')
|
||||
const concepts = path.join(vault, '01 Concepts')
|
||||
const digest = path.join(vault, '_digest')
|
||||
await fs.mkdir(concepts, { recursive: true })
|
||||
await fs.mkdir(digest, { recursive: true })
|
||||
await fs.mkdir(reports, { recursive: true })
|
||||
await fs.mkdir(state, { recursive: true })
|
||||
const started = new Date(Date.now() - 1000).toISOString()
|
||||
await fs.writeFile(path.join(concepts, 'good.md'), `---
|
||||
title: "Хорошая русская заметка"
|
||||
type: "knowledge-note"
|
||||
type: "concept"
|
||||
status: "final"
|
||||
verified: true
|
||||
verification_status: "verified"
|
||||
@@ -542,6 +772,96 @@ verification_status: "verified"
|
||||
## Следующее действие
|
||||
|
||||
- Оставить human-layer gate в release-check.
|
||||
`, 'utf8')
|
||||
await fs.writeFile(path.join(concepts, 'github-atom.md'), `---
|
||||
title: "tech-leads-club/agent-skills: что реально обещает README"
|
||||
type: "concept"
|
||||
status: "final"
|
||||
verified: true
|
||||
verification_status: "verified"
|
||||
---
|
||||
|
||||
# tech-leads-club/agent-skills: что реально обещает README
|
||||
|
||||
## Что это
|
||||
|
||||
README позиционирует tech-leads-club/agent-skills как проверенный каталог skills для AI coding agents. Рабочий смысл простой: это кандидат на разбор, а не команда сразу ставить глобально.
|
||||
|
||||
## Зачем это нужно
|
||||
|
||||
Скриншот со stars ещё не знание. Нужны первоисточник, свежесть репозитория, лицензия, открытые issues и понятный риск доверия.
|
||||
|
||||
## Как использовать
|
||||
|
||||
- Проверить заявленную валидацию skills.
|
||||
- Отдельно посмотреть security-claim про уязвимости marketplace skills.
|
||||
- Связать каталог с одним нашим workflow до установки.
|
||||
|
||||
## Источники
|
||||
|
||||
Локальные source refs:
|
||||
- local-media:humanlayergithub
|
||||
|
||||
Публичные источники:
|
||||
- github.com: https://github.com/tech-leads-club/agent-skills
|
||||
|
||||
## Расширение знания
|
||||
|
||||
Факты, добавленные до атомизации:
|
||||
- GitHub README описывает проект как проверенный каталог skills для coding agents.
|
||||
- Метаданные GitHub добавляют проверяемые признаки свежести и поддержки.
|
||||
|
||||
## Проверка
|
||||
|
||||
- Статус проверки: verified.
|
||||
|
||||
## Следующее действие
|
||||
|
||||
- Добавить репозиторий в очередь разбора возможностей с одним критерием: принять или отклонить.
|
||||
`, 'utf8')
|
||||
await fs.writeFile(path.join(digest, 'Сводка-smoke.md'), `---
|
||||
title: "Сводка знаний — smoke"
|
||||
type: "knowledge-digest"
|
||||
source_ref: "digest:smoke"
|
||||
---
|
||||
|
||||
# Сводка знаний — smoke
|
||||
|
||||
## Что это
|
||||
|
||||
Сводка связывает новые заметки после прогона и показывает, какие выводы уже можно открыть как карту знаний.
|
||||
|
||||
## Зачем это нужно
|
||||
|
||||
Она нужна как быстрый слой повторного использования: видно, какие заметки появились, что они дают и где лежат связи.
|
||||
|
||||
## Как использовать
|
||||
|
||||
- Открыть связанные заметки из списка ниже.
|
||||
- Взять сильные следующие действия в работу.
|
||||
- Проверить слабые связи перед публикацией.
|
||||
|
||||
## Источник
|
||||
|
||||
- source_ref: digest:smoke
|
||||
- processed_notes: 2
|
||||
|
||||
## Проверка
|
||||
|
||||
Сводка построена локально из заметок vault. Это не внешняя факт-проверка, а навигационная карта после прогона.
|
||||
|
||||
## Связанные заметки
|
||||
|
||||
- [[Mnemazine Protocol]]
|
||||
|
||||
## Повторное использование
|
||||
|
||||
Обработано заметок: 2. Ниже — что узнано и как связано.
|
||||
|
||||
## Проверенная карточка инструмента
|
||||
|
||||
- Заметка: [[01 Concepts/synthesis-tech-leads-club-agent-skills-readme-backed-capability-summary-fd502aea4d]]
|
||||
- Связи: [[01 Concepts/synthesis-affaan-m-ecc-mnemazine-routing-decision-1c84a44c58]], [[01 Concepts/synthesis-browser-use-browser-use-operational-risk-and-maintenance-check-ebe5f6e21e]], [[01 Concepts/synthesis-ksimback-looper-verified-tool-identity-and-adoption-signal-3d2bc03aaf]], [[01 Concepts/synthesis-tech-leads-club-agent-skills-operational-risk-and-maintenance-check-cdedd86d2b]], [[01 Concepts/synthesis-browser-use-browser-use-readme-backed-capability-summary-fd502aea4d]], [[01 Concepts/synthesis-affaan-m-ecc-verified-tool-identity-and-adoption-signal-3d2bc03aaf]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-readme-backed-capability-summary-aabbccddeeff00112233445566778899]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-operational-risk-and-maintenance-check-aabbccddeeff00112233445566778899]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-verified-tool-identity-and-adoption-signal-aabbccddeeff00112233445566778899]], [[01 Concepts/synthesis-really-long-agent-workflow-loop-design-before-runtime-with-reviewer-model-judge-token-budget-no-progress-limit-and-session-state-files-mnemazine-routing-decision-aabbccddeeff00112233445566778899]]
|
||||
`, 'utf8')
|
||||
const report = path.join(reports, 'good.html')
|
||||
await fs.writeFile(report, [
|
||||
@@ -626,6 +946,241 @@ async function repoMetadataCheck() {
|
||||
}
|
||||
}
|
||||
|
||||
// Пять мета-приборов П11: каждый — отдельный скрипт с честным кодом возврата и --selftest.
|
||||
async function runMetaGate(scriptRel) {
|
||||
await must(scriptRel, process.execPath, [scriptRel])
|
||||
}
|
||||
async function rulesInventoryGate() { await runMetaGate('scripts/mnemazine-rules-inventory.mjs') }
|
||||
async function docContractGate() { await runMetaGate('scripts/mnemazine-doc-contract-check.mjs') }
|
||||
async function singleTruthGate() { await runMetaGate('scripts/mnemazine-single-truth-check.mjs') }
|
||||
async function lessonGateCheck() { await runMetaGate('scripts/mnemazine-lesson-gate.mjs') }
|
||||
async function checksInventoryGate() { await runMetaGate('scripts/mnemazine-checks-inventory.mjs') }
|
||||
async function modelPinCheck() { await runMetaGate('scripts/mnemazine-model-pin-check.mjs') }
|
||||
|
||||
const NEW_CHECKS = new Set(['rules-inventory', 'doc-contract-check', 'single-truth-check', 'lesson-gate', 'checks-inventory'])
|
||||
|
||||
// П24: every rsync/scp whose DESTINATION is the VPS in scripts/*.sh must be
|
||||
// preceded, in the same file, by a machine-class-gate call. A dangling outbound
|
||||
// transfer (gate cut out, rsync left) is a hole — hostile probe 5 breaks exactly
|
||||
// this. Also runs the gate's hermetic --selftest so a broken taxonomy reddens here.
|
||||
async function machineClassGateCheck() {
|
||||
const gate = path.join(ROOT, 'scripts', 'mnemazine-machine-class-gate.mjs')
|
||||
if (!existsSync(gate)) throw new Error('machine-class-gate: scripts/mnemazine-machine-class-gate.mjs отсутствует')
|
||||
await must('machine-class-gate selftest', process.execPath, [gate, '--selftest'])
|
||||
const shDir = path.join(ROOT, 'scripts')
|
||||
const files = (await fs.readdir(shDir)).filter(f => f.endsWith('.sh'))
|
||||
const violations = []
|
||||
for (const f of files) {
|
||||
const lines = (await fs.readFile(path.join(shDir, f), 'utf8')).split('\n')
|
||||
let gateSeen = false
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i]
|
||||
if (line.trim().startsWith('#')) continue // комментарий не считается ни вызовом гейта, ни отправкой
|
||||
if (line.includes('machine-class-gate')) gateSeen = true
|
||||
if (!/\b(rsync|scp)\b/.test(line)) continue
|
||||
const tokens = line.trim().split(/\s+/)
|
||||
const dest = tokens[tokens.length - 1] // outbound ⇔ VPS is the destination (last arg); inbound pulls have VPS as source
|
||||
if (/\$VPS/.test(dest) && !gateSeen) {
|
||||
violations.push(`scripts/${f}:${i + 1}: rsync/scp на $VPS без предшествующего вызова machine-class-gate`)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (violations.length) throw new Error('machine-class-gate: незащищённая отправка наружу:\n' + violations.join('\n'))
|
||||
}
|
||||
|
||||
// Порог пяти новых гейтов: 'blocking' по умолчанию. Перевод в 'warn' — одна строка
|
||||
// new_gate_enforcement в config/doc-claims.json (путь отката П11 на исторический долг).
|
||||
function readNewGateEnforcement() {
|
||||
try {
|
||||
const cfg = JSON.parse(readFileSync(path.join(ROOT, 'config', 'doc-claims.json'), 'utf8'))
|
||||
return cfg.new_gate_enforcement === 'warn' ? 'warn' : 'blocking'
|
||||
} catch {
|
||||
return 'blocking'
|
||||
}
|
||||
}
|
||||
|
||||
// --contracts: печать контракта всех зарегистрированных проверок без их запуска.
|
||||
// Строки syntax:<file> перечисляют реальную выборку git ls-files ∩ disk.
|
||||
async function printContracts(checks) {
|
||||
const targets = syntaxTargetsFrom(await gitLsFiles())
|
||||
for (const file of targets.all) {
|
||||
if (existsSync(path.join(ROOT, file))) console.log(`syntax:${file}`)
|
||||
}
|
||||
for (const [name] of checks) console.log(`check:${name}`)
|
||||
}
|
||||
|
||||
// --- П19 онбординг: шесть новых проверок --------------------------------------
|
||||
|
||||
// README: восемь новых разделов в обоих файлах, одинаковый набор npm-команд EN/RU,
|
||||
// одинаковое число строк в таблице агентов (заголовочный паритет этого не ловит).
|
||||
async function onboardingReadmeCheck() {
|
||||
const en = await fs.readFile(path.join(ROOT, 'README.md'), 'utf8')
|
||||
const ru = await fs.readFile(path.join(ROOT, 'README.ru.md'), 'utf8')
|
||||
const h2 = body => (body.match(/^##\s+.+$/gm) || []).map(s => s.toLowerCase())
|
||||
const enH2 = h2(en); const ruH2 = h2(ru)
|
||||
const sections = [
|
||||
['install goes', 'как проходит установка'],
|
||||
['my agents', 'мои агенты'],
|
||||
['privacy', 'приватность'],
|
||||
['if you improved me', 'если ты меня улучшил'],
|
||||
['something broke', 'сломалось'],
|
||||
['exit codes', 'коды возврата'],
|
||||
['bot:', 'бот:'],
|
||||
['vps:', 'vps:']
|
||||
]
|
||||
const missing = []
|
||||
for (const [enA, ruA] of sections) {
|
||||
if (!enH2.some(x => x.includes(enA))) missing.push(`README.md: раздел «${enA}»`)
|
||||
if (!ruH2.some(x => x.includes(ruA))) missing.push(`README.ru.md: раздел «${ruA}»`)
|
||||
}
|
||||
if (missing.length) throw new Error('onboarding-readme: нет разделов:\n' + missing.join('\n'))
|
||||
|
||||
const npmToks = body => body.match(/npm (?:run [\w:-]+|start)/g) || []
|
||||
const enToks = npmToks(en); const ruToks = npmToks(ru)
|
||||
const npmCmds = toks => [...new Set(toks)].sort()
|
||||
const enCmds = npmCmds(enToks); const ruCmds = npmCmds(ruToks)
|
||||
const onlyEn = enCmds.filter(c => !ruCmds.includes(c))
|
||||
const onlyRu = ruCmds.filter(c => !enCmds.includes(c))
|
||||
if (onlyEn.length || onlyRu.length) {
|
||||
throw new Error(`onboarding-readme: набор npm-команд разошёлся. только EN: ${onlyEn.join(', ') || '—'}; только RU: ${onlyRu.join(', ') || '—'}`)
|
||||
}
|
||||
|
||||
// Обязательные контрактные фрагменты: каждый обязан быть в ОБОИХ README (контракт П19,
|
||||
// блок «Команда проверки»). Команды сверяем по ЧИСЛУ вхождений — набор-симметрия выше
|
||||
// не ловит потерю одного из двух дублей (прецедент пробы: удаление одной из двух строк
|
||||
// `npm run doctor:full` из RU). Текст — по языковой паре EN|RU.
|
||||
const MANDATORY = [
|
||||
{ name: 'npm run doctor', cmd: 'npm run doctor' },
|
||||
{ name: 'npm run doctor:full', cmd: 'npm run doctor:full' },
|
||||
{ name: 'npm start', cmd: 'npm start' },
|
||||
{ name: 'таблица приватности', en: '| Channel | What leaves', ru: '| Канал | Что уходит' },
|
||||
{ name: 'VPS не делает: Apple Vision OCR', en: 'Apple Vision', ru: 'Apple Vision' },
|
||||
{ name: 'VPS не делает: whisper', en: 'whisper', ru: 'whisper' },
|
||||
{ name: 'VPS не делает: ollama', en: 'ollama', ru: 'ollama' }
|
||||
]
|
||||
const gaps = []
|
||||
for (const f of MANDATORY) {
|
||||
if (f.cmd) {
|
||||
const enN = enToks.filter(t => t === f.cmd).length
|
||||
const ruN = ruToks.filter(t => t === f.cmd).length
|
||||
if (enN === 0) gaps.push(`«${f.name}» → нет в README.md`)
|
||||
if (ruN === 0) gaps.push(`«${f.name}» → нет в README.ru.md`)
|
||||
if (enN && ruN && enN !== ruN) gaps.push(`«${f.name}» → вхождений EN ${enN} ≠ RU ${ruN} (README.ru.md)`)
|
||||
} else {
|
||||
if (!en.includes(f.en)) gaps.push(`«${f.name}» → нет в README.md`)
|
||||
if (!ru.includes(f.ru)) gaps.push(`«${f.name}» → нет в README.ru.md`)
|
||||
}
|
||||
}
|
||||
if (gaps.length) throw new Error('onboarding-readme: пропал обязательный контрактный фрагмент:\n' + gaps.map(g => ' ' + g).join('\n'))
|
||||
|
||||
const agentRows = (body, anchor) => {
|
||||
const lines = body.split('\n')
|
||||
const start = lines.findIndex(l => /^##\s/.test(l) && l.toLowerCase().includes(anchor))
|
||||
if (start === -1) return -1
|
||||
let n = 0
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if (/^##\s/.test(lines[i])) break
|
||||
if (/^\|/.test(lines[i])) n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
const enRows = agentRows(en, 'my agents'); const ruRows = agentRows(ru, 'мои агенты')
|
||||
if (enRows < 4 || ruRows < 4) throw new Error(`onboarding-readme: таблица агентов пуста (EN ${enRows}, RU ${ruRows})`)
|
||||
if (enRows !== ruRows) throw new Error(`onboarding-readme: строк в таблице агентов EN ${enRows} ≠ RU ${ruRows}`)
|
||||
}
|
||||
|
||||
// install.sh реально зовёт доктора и не печатает безусловное «installed».
|
||||
async function installVerifiesCheck() {
|
||||
const src = await fs.readFile(path.join(ROOT, 'install.sh'), 'utf8')
|
||||
if (!src.includes('mnemazine-doctor')) throw new Error('install-verifies: install.sh не ссылается на mnemazine-doctor')
|
||||
if (!src.includes('exit "$STATUS"')) throw new Error('install-verifies: install.sh не завершается кодом статуса')
|
||||
if (/^\s*echo\s+"Mnemazine installed\.?"/m.test(src)) throw new Error('install-verifies: безусловная печать «Mnemazine installed» без развилки')
|
||||
}
|
||||
|
||||
// Гейт согласия: молчание = отказ, ничего не создано в $HOME.
|
||||
async function installerConsentGateCheck() {
|
||||
const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-consent-home-'))
|
||||
const shim = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-consent-shim-'))
|
||||
const clone = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-consent-clone-'))
|
||||
for (const c of ['pip3', 'pip', 'launchctl', 'swiftc', 'brew', 'xcode-select']) {
|
||||
await fs.writeFile(path.join(shim, c), '#!/bin/sh\nexit 0\n', { mode: 0o755 })
|
||||
}
|
||||
const res = await run('bash', ['install.sh'], {
|
||||
env: { HOME: home, PATH: `${shim}:${process.env.PATH}`, MNEMAZINE_ROOT: clone, MNEMAZINE_SETUP_DRYRUN: '0', MNEMAZINE_FROM_SETUP: '0', MNEMAZINE_YES: '0' }
|
||||
})
|
||||
if (res.code !== 1) throw new Error(`installer-consent-gate: молчание должно давать exit 1, получено ${res.code}\n${res.stdout}\n${res.stderr}`)
|
||||
const created = await listFiles(home)
|
||||
if (created.length) throw new Error(`installer-consent-gate: отказ создал файлы в $HOME: ${created.join(', ')}`)
|
||||
}
|
||||
|
||||
// Каждая строка DEGRADED: несёт команду починки.
|
||||
async function installerWarningsCarryFixCheck() {
|
||||
const lines = (await fs.readFile(path.join(ROOT, 'install.sh'), 'utf8')).split('\n')
|
||||
const bad = []
|
||||
let degradeCalls = 0
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
if (/\bdegrade\s+"/.test(lines[i])) degradeCalls++
|
||||
if (lines[i].includes('DEGRADED:') && !lines[i].includes('fix:')) bad.push(`install.sh:${i + 1}: ${lines[i].trim()}`)
|
||||
}
|
||||
if (bad.length) throw new Error('installer-warnings-carry-fix: DEGRADED без команды:\n' + bad.join('\n'))
|
||||
if (degradeCalls < 1) throw new Error('installer-warnings-carry-fix: нет ни одного degrade-вызова')
|
||||
}
|
||||
|
||||
// Доктор различает три кода: 0/1/2.
|
||||
async function doctorThreeCodesCheck() {
|
||||
const src = await fs.readFile(path.join(ROOT, 'scripts/mnemazine-doctor.mjs'), 'utf8')
|
||||
if (!/process\.exit\(1\)/.test(src)) throw new Error('doctor-three-codes: нет ветки exit 1')
|
||||
if (!/process\.exit\(2\)/.test(src)) throw new Error('doctor-three-codes: нет ветки exit 2')
|
||||
if (!/warnings\.length\)\s*process\.exit\(2\)/.test(src)) throw new Error('doctor-three-codes: предупреждения не дают код 2')
|
||||
await must('doctor selftest (three codes)', process.execPath, ['scripts/mnemazine-doctor.mjs', '--selftest'])
|
||||
}
|
||||
|
||||
// Интейк: раздел приватности с четырьмя каналами; вопрос про бота исполним в трёх
|
||||
// ветках без сети и без записи в $HOME; README не обещает на VPS того, чего нет.
|
||||
async function onboardingIntakeCheck() {
|
||||
const en = await fs.readFile(path.join(ROOT, 'README.md'), 'utf8')
|
||||
const ru = await fs.readFile(path.join(ROOT, 'README.ru.md'), 'utf8')
|
||||
for (const [label, body] of [['README.md', en], ['README.ru.md', ru]]) {
|
||||
if (!/^##\s+.*(privacy|приватность)/im.test(body)) throw new Error(`onboarding-intake: в ${label} нет раздела приватности`)
|
||||
const channels = { deep: /deep/i, telegram: /telegram/i, 'agent-os': /agent-os/i, youtube: /youtube/i }
|
||||
for (const [name, re] of Object.entries(channels)) {
|
||||
if (!re.test(body)) throw new Error(`onboarding-intake: в ${label} раздел приватности не называет канал ${name}`)
|
||||
}
|
||||
}
|
||||
const vpsClaims = [
|
||||
/(Apple Vision|whisper|ollama)[^.\n]{0,80}(VPS|сервер|server|удал[её]нн)/i,
|
||||
/(VPS|сервер|server)[^.\n]{0,80}(Apple Vision|whisper|ollama)/i
|
||||
]
|
||||
for (const [label, body] of [['README.md', en], ['README.ru.md', ru]]) {
|
||||
const lines = body.split('\n')
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
for (const re of vpsClaims) {
|
||||
if (re.test(lines[i])) throw new Error(`onboarding-intake: ${label}:${i + 1} обещает на VPS то, чего там нет: ${lines[i].trim()}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
const home = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-intake-home-'))
|
||||
const shim = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-intake-shim-'))
|
||||
const netlog = path.join(shim, 'net.log')
|
||||
for (const c of ['ssh', 'scp', 'rsync', 'security', 'pip3', 'pip', 'launchctl', 'swiftc', 'brew', 'xcode-select', 'claude', 'codex']) {
|
||||
await fs.writeFile(path.join(shim, c), `#!/bin/sh\necho "$(basename "$0") $*" >> ${JSON.stringify(netlog)}\nexit 0\n`, { mode: 0o755 })
|
||||
}
|
||||
const branches = [
|
||||
['нет VPS', '1\n3\n1\nтокен-проба\n2\n'],
|
||||
['без бота', '1\n3\n2\n'],
|
||||
['есть VPS', '1\n3\n1\nтокен-проба\n1\nuser@host\n\nSHA256:fake\n']
|
||||
]
|
||||
for (const [name, answers] of branches) {
|
||||
const res = await runWithStdin('bash', ['setup.sh'], answers, {
|
||||
HOME: home, PATH: `${shim}:${process.env.PATH}`, MNEMAZINE_SETUP_DRYRUN: '1'
|
||||
})
|
||||
if (res.code !== 0) throw new Error(`onboarding-intake: ветка «${name}» упала кодом ${res.code}\n${(res.stderr || res.stdout).slice(-500)}`)
|
||||
}
|
||||
if (existsSync(netlog)) throw new Error('onboarding-intake: установщик сходил в сеть (net.log непустой)')
|
||||
const created = await listFiles(home)
|
||||
if (created.length) throw new Error(`onboarding-intake: установщик создал файлы в $HOME: ${created.join(', ')}`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const checks = [
|
||||
['syntax', checkSyntax],
|
||||
@@ -636,15 +1191,73 @@ async function main() {
|
||||
['strict-archive-gate', strictArchiveGateSmoke],
|
||||
['quality-public', qualityAndPublicChecks],
|
||||
['search-eval', searchEvalSmoke],
|
||||
['repo-metadata', repoMetadataCheck]
|
||||
['repo-metadata', repoMetadataCheck],
|
||||
['rules-inventory', rulesInventoryGate],
|
||||
['doc-contract-check', docContractGate],
|
||||
['single-truth-check', singleTruthGate],
|
||||
['lesson-gate', lessonGateCheck],
|
||||
['checks-inventory', checksInventoryGate],
|
||||
['model-pin', modelPinCheck],
|
||||
['machine-class-gate', machineClassGateCheck],
|
||||
['onboarding-readme', onboardingReadmeCheck],
|
||||
['install-verifies', installVerifiesCheck],
|
||||
['installer-consent-gate', installerConsentGateCheck],
|
||||
['installer-warnings-carry-fix', installerWarningsCarryFixCheck],
|
||||
['doctor-three-codes', doctorThreeCodesCheck],
|
||||
['onboarding-intake', onboardingIntakeCheck]
|
||||
]
|
||||
const passed = []
|
||||
for (const [name, fn] of checks) {
|
||||
await fn()
|
||||
passed.push(name)
|
||||
console.log(`ok ${name}`)
|
||||
|
||||
if (process.argv.includes('--contracts')) {
|
||||
await printContracts(checks)
|
||||
return
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, passed }, null, 2))
|
||||
|
||||
// --only <name>: запустить одну зарегистрированную проверку (режим приходит из
|
||||
// П19; до его закрытия обслуживает прямой вызов machine-class-gate из приёмки П24).
|
||||
const onlyIdx = process.argv.indexOf('--only')
|
||||
if (onlyIdx !== -1) {
|
||||
const requested = String(process.argv[onlyIdx + 1] || '').split(',').map(s => s.trim()).filter(Boolean)
|
||||
const selected = checks.filter(([n]) => requested.includes(n))
|
||||
// Пустая выборка — exit 2, а не «сдано 0/0 ✓»: опечатка в фильтре не должна
|
||||
// печатать «приём» (прецедент разбора Фемиды).
|
||||
if (selected.length === 0) { console.error(`empty --only selection: ${requested.join(',') || '(none)'}`); process.exit(2) }
|
||||
const okOnly = []
|
||||
const crashOnly = []
|
||||
for (const [name, fn] of selected) {
|
||||
try { await fn(); okOnly.push(name); console.log(`ok ${name}`) }
|
||||
catch (e) { crashOnly.push(name); console.error(`crash:${name}\n${e && e.message ? e.message : e}`) }
|
||||
}
|
||||
process.exit(crashOnly.length ? 1 : 0)
|
||||
}
|
||||
|
||||
// Изоляция: исключение одной проверки записывается crash:<имя> и не убивает остальные;
|
||||
// итоговый код ненулевой при любом crash. Новые гейты при enforcement:'warn' дают warn,
|
||||
// а не crash (мягкий режим), но по умолчанию блокируют.
|
||||
const enforcement = readNewGateEnforcement()
|
||||
const passed = []
|
||||
const warned = []
|
||||
const crashed = []
|
||||
for (const [name, fn] of checks) {
|
||||
try {
|
||||
await fn()
|
||||
passed.push(name)
|
||||
console.log(`ok ${name}`)
|
||||
} catch (error) {
|
||||
const message = error && error.message ? error.message : String(error)
|
||||
if (NEW_CHECKS.has(name) && enforcement === 'warn') {
|
||||
warned.push(name)
|
||||
console.error(`warn ${name} (мягкий режим): ${message}`)
|
||||
} else {
|
||||
crashed.push(name)
|
||||
console.error(`crash:${name}\n${message}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (crashed.length) {
|
||||
console.log(JSON.stringify({ ok: false, passed, warned, crashed }, null, 2))
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(JSON.stringify({ ok: true, passed, warned }, null, 2))
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
readGraph,
|
||||
writeGraph
|
||||
} from './mnemazine-graph-utils.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
@@ -21,7 +22,7 @@ function hasFlag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
const graphPath = path.resolve(arg('graph', path.join(process.env.HOME || '.', 'Мозг/graphify-out/graph.json')))
|
||||
const graphPath = path.resolve(arg('graph') || path.join(resolveVault({ requireExists: false }), 'graphify-out', 'graph.json'))
|
||||
const outPath = arg('out', '')
|
||||
const apply = hasFlag('apply')
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ function arg(name, fallback = '') {
|
||||
|
||||
const REPORT = arg('report', '')
|
||||
const REPORTS = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
|
||||
// fail-closed: «no reports found» больше не зелёный. Ноль отчётов = exit 2,
|
||||
// если не передан явный --allow-empty.
|
||||
const ALLOW_EMPTY = argv.includes('--allow-empty')
|
||||
|
||||
const rawMarkers = [
|
||||
/raw\s+ocr/i,
|
||||
@@ -81,8 +84,12 @@ async function checkReport(file) {
|
||||
|
||||
const reports = await listReports()
|
||||
if (!reports.length) {
|
||||
console.log(JSON.stringify({ ok: true, checked: 0, note: 'no reports found' }, null, 2))
|
||||
process.exit(0)
|
||||
if (ALLOW_EMPTY) {
|
||||
console.log(JSON.stringify({ ok: true, checked: 0, note: 'no reports found (--allow-empty)' }, null, 2))
|
||||
process.exit(0)
|
||||
}
|
||||
console.error(JSON.stringify({ ok: false, checked: 0, error: 'нет отчётов для проверки: 0 найдено (--allow-empty чтобы разрешить)' }, null, 2))
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const failures = []
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env node
|
||||
// Правило без прибора становится ошибкой сборки (план П11, метод-правило 3).
|
||||
//
|
||||
// Каждое императивное предложение из CLAUDE.md/AGENTS.md (must / must not / never /
|
||||
// do not / обязан / обязательно / никогда / не должен) обязано иметь запись в
|
||||
// config/rules-enforcement.json с живым `enforced_by` (<файл>:<строка> — файл есть,
|
||||
// строка в диапазоне, файл проходит node --check / bash -n / python3 -m py_compile).
|
||||
// Форма «утверждение → якорь в отдельном json», а НЕ `enforced_by:` внутри CLAUDE.md:
|
||||
// глобальная конституция держит бюджет ≤200 строк, машинные якоря её ломают.
|
||||
//
|
||||
// Новые правила мастер-плана §17.8 (класс данных) и §18 (subject) заведены сразу,
|
||||
// с полем pending_until: пока маркера их плана нет на диске — мёртвый enforced_by не
|
||||
// краснит; с маркером — краснит. Так правило не теряется между волнами и не блокирует
|
||||
// их порядок.
|
||||
//
|
||||
// Коды: 0 — все правила имеют живой прибор; 1 — правило без записи, либо запись с
|
||||
// мёртвым файлом/несуществующей строкой/непроходящим синтаксисом; 2 — ноль извлечённых
|
||||
// правил (пустая выборка = провал, не «сдано 0/0»).
|
||||
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const DOC_FILES = ['CLAUDE.md', 'AGENTS.md']
|
||||
const ENFORCEMENT = path.join(ROOT, 'config', 'rules-enforcement.json')
|
||||
const KEYWORDS = /\b(must not|must|never|do not|обязан|обязательно|никогда|не должен)\b/i
|
||||
|
||||
function splitSentences(text) {
|
||||
const out = []
|
||||
for (const rawLine of String(text).split(/\r?\n/)) {
|
||||
const line = rawLine.trim()
|
||||
if (!line || line.startsWith('#') || line.startsWith('```')) continue
|
||||
for (const piece of line.split(/(?<=[.!?;])\s+/)) {
|
||||
const t = piece.trim()
|
||||
if (t) out.push(t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function norm(s) {
|
||||
return String(s).replace(/\s+/g, ' ').trim().toLowerCase()
|
||||
}
|
||||
|
||||
function extractRules(docRoot) {
|
||||
const rules = []
|
||||
const seen = new Set()
|
||||
for (const rel of DOC_FILES) {
|
||||
const p = path.join(docRoot, rel)
|
||||
if (!existsSync(p)) continue
|
||||
for (const sentence of splitSentences(readFileSync(p, 'utf8'))) {
|
||||
if (!KEYWORDS.test(sentence)) continue
|
||||
const key = norm(sentence)
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
rules.push({ file: rel, sentence, norm: key })
|
||||
}
|
||||
}
|
||||
return rules
|
||||
}
|
||||
|
||||
function syntaxOk(rel) {
|
||||
const abs = path.join(ROOT, rel)
|
||||
const ext = path.extname(rel)
|
||||
let cmd, args
|
||||
if (ext === '.mjs' || ext === '.js') { cmd = process.execPath; args = ['--check', abs] }
|
||||
else if (ext === '.sh') { cmd = 'bash'; args = ['-n', abs] }
|
||||
else if (ext === '.py') { cmd = 'python3'; args = ['-m', 'py_compile', abs] }
|
||||
else return true // не-кодовый якорь: достаточно существования файла
|
||||
return spawnSync(cmd, args, { encoding: 'utf8' }).status === 0
|
||||
}
|
||||
|
||||
function enforcedByLive(anchor) {
|
||||
const m = String(anchor || '').match(/^(.+):(\d+)$/)
|
||||
if (!m) return `формат enforced_by не <файл>:<строка>: ${anchor}`
|
||||
const rel = m[1]
|
||||
const line = Number(m[2])
|
||||
const abs = path.join(ROOT, rel)
|
||||
if (!existsSync(abs)) return `enforced_by файл отсутствует: ${rel}`
|
||||
const lineCount = readFileSync(abs, 'utf8').split(/\r?\n/).length
|
||||
if (line < 1 || line > lineCount) return `enforced_by строка ${line} вне диапазона ${rel} (${lineCount} строк)`
|
||||
if (!syntaxOk(rel)) return `enforced_by файл не проходит синтаксис: ${rel}`
|
||||
return null
|
||||
}
|
||||
|
||||
function markerExists(plan) {
|
||||
return existsSync(path.join(ROOT, '.mnemazine', 'state', 'rebuild', `${plan}.done.json`))
|
||||
}
|
||||
|
||||
function evaluate({ docRoot, enforcement }) {
|
||||
const extracted = extractRules(docRoot)
|
||||
if (extracted.length === 0) return { code: 2, extracted, failures: ['ноль извлечённых правил из CLAUDE.md/AGENTS.md'] }
|
||||
const entries = Array.isArray(enforcement?.rules) ? enforcement.rules : []
|
||||
const failures = []
|
||||
|
||||
for (const rule of extracted) {
|
||||
const hit = entries.find(e => e.quote && rule.norm.includes(norm(e.quote)))
|
||||
if (!hit) failures.push(`правило без записи в rules-enforcement.json: "${rule.sentence}" (${rule.file})`)
|
||||
}
|
||||
|
||||
for (const e of entries) {
|
||||
const dormant = e.pending_until && !markerExists(e.pending_until)
|
||||
if (dormant) continue
|
||||
const why = enforcedByLive(e.enforced_by)
|
||||
if (why) failures.push(`${e.id || e.quote}: ${why}${e.pending_until ? ` (pending_until ${e.pending_until} снят)` : ''}`)
|
||||
}
|
||||
|
||||
return { code: failures.length ? 1 : 0, extracted, failures }
|
||||
}
|
||||
|
||||
function loadEnforcement() {
|
||||
if (!existsSync(ENFORCEMENT)) return { rules: [] }
|
||||
try { return JSON.parse(readFileSync(ENFORCEMENT, 'utf8')) } catch (e) { return { rules: [], _error: e.message } }
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
// Красный кролик: правило без прибора обязано покраснеть.
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), 'rules-inv-selftest-'))
|
||||
try {
|
||||
writeFileSync(path.join(tmp, 'CLAUDE.md'), '# X\n\nThe runner must never write outside the vault.\n', 'utf8')
|
||||
const r = evaluate({ docRoot: tmp, enforcement: { rules: [] } })
|
||||
if (r.code !== 1) {
|
||||
console.error(`selftest FAILED: красный кролик прошёл зелёным (code=${r.code})`)
|
||||
return 1
|
||||
}
|
||||
console.log('selftest ok: правило без прибора краснит (1)')
|
||||
return 0
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const argv = process.argv.slice(2)
|
||||
if (argv.includes('--selftest')) process.exit(selftest())
|
||||
|
||||
const enforcement = loadEnforcement()
|
||||
if (enforcement._error) {
|
||||
console.error(`config/rules-enforcement.json нечитаем: ${enforcement._error}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const r = evaluate({ docRoot: ROOT, enforcement })
|
||||
if (argv.includes('--json')) {
|
||||
console.log(JSON.stringify({ code: r.code, extracted: r.extracted.length, failures: r.failures }, null, 2))
|
||||
} else {
|
||||
console.log(`извлечено правил: ${r.extracted.length}; записей в реестре: ${(enforcement.rules || []).length}`)
|
||||
for (const rule of r.extracted) console.log(` rule: ${rule.sentence}`)
|
||||
if (r.failures.length) {
|
||||
console.error('ПРОВАЛЫ:')
|
||||
for (const f of r.failures) console.error(` - ${f}`)
|
||||
} else {
|
||||
console.log('все правила имеют живой прибор')
|
||||
}
|
||||
}
|
||||
process.exit(r.code)
|
||||
}
|
||||
|
||||
main()
|
||||
+351
-57
@@ -1,13 +1,32 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import crypto from 'node:crypto'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { llmAvailable, llmText } from './mnemazine-llm.mjs'
|
||||
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
import { requireEngines } from './mnemazine-local-engines.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
|
||||
// Config contradiction, caught by code — not by a warning string. Strict protocol
|
||||
// (REQUIRE_DEEP) and draft-only are mutually exclusive: draft-only writes nothing
|
||||
// to the vault and never archives, so a run that must fail-before-archive cannot
|
||||
// also be draft-only. Exit 2 (config error), distinct from a gate failure (1).
|
||||
// This gate MUST stay the FIRST exit-2 path: it runs before resolveVault and before
|
||||
// the vault-quality-gate, so an observed exit 2 provably means THIS contradiction
|
||||
// and nothing else (empty-vault gate also exits 2 — that ambiguity is why order
|
||||
// matters). Remove the exit below and the run falls through to a code that is not 2.
|
||||
const REQUIRE_DEEP = process.argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
|
||||
const DRAFT_ONLY = process.env.MNEMAZINE_DRAFT_ONLY === '1'
|
||||
if (REQUIRE_DEEP && DRAFT_ONLY) {
|
||||
console.error('strict protocol vs draft-only: MNEMAZINE_REQUIRE_DEEP=1 и MNEMAZINE_DRAFT_ONLY=1 несовместимы')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const INBOX = process.env.MNEMAZINE_INBOX || path.join(ROOT, 'inbox')
|
||||
const VAULT = resolveVault()
|
||||
const REPORTS = process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')
|
||||
@@ -21,13 +40,22 @@ const VIDEO_QUEUE = path.join(ROOT, '.mnemazine/cache/video-queue.jsonl')
|
||||
const EXTRACTS = process.env.MNEMAZINE_EXTRACTS || path.join(ROOT, '.mnemazine/cache/extracted')
|
||||
const SYNTHESIZE = process.env.MNEMAZINE_SYNTHESIZE !== '0'
|
||||
const FINISH = process.env.MNEMAZINE_FINISH !== '0'
|
||||
const RUN_ID = process.env.MNEMAZINE_RUN_ID || `run-${new Date().toISOString().replace(/[-:.TZ]/g, '').slice(0, 14)}`
|
||||
// Opt-in deep stage (atomization + web/LLM verification, README:230 pipeline).
|
||||
// Default OFF: the runner stays conservative — local only, no external calls.
|
||||
// Enable with `--deep` or MNEMAZINE_DEEP=1; forwarded to synthesize.
|
||||
// Default OFF for direct runs. Strict desktop protocol does not pass --deep;
|
||||
// it lets tierOf(file) choose deep work only for tier>=1.
|
||||
const DEEP = process.argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
|
||||
const REQUIRE_DEEP = process.argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
|
||||
const ENRICH_REQUIRED = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !process.argv.includes('--no-enrich')
|
||||
const DEEP_ALLOWED = DEEP || REQUIRE_DEEP
|
||||
const ENRICH_REQUIRED = DEEP_ALLOWED && process.env.MNEMAZINE_ENRICH !== '0' && !process.argv.includes('--no-enrich')
|
||||
const STRICT_ARCHIVE_KNOWLEDGE = (REQUIRE_DEEP || (DEEP && ENRICH_REQUIRED)) && process.env.MNEMAZINE_STRICT_ARCHIVE !== '0' && !process.argv.includes('--allow-raw-archive')
|
||||
// Local-first contract (П10): with require-local on, a run that meets a MISSING
|
||||
// local engine STOPS (exit 3) rather than silently reaching for the cloud. The
|
||||
// env name is shared with CI and the launchd job — it flips the switch without
|
||||
// changing the command; --require-local is the equivalent CLI flag.
|
||||
const REQUIRE_LOCAL = process.argv.includes('--require-local') || process.env.MNEMAZINE_REQUIRE_LOCAL_EXTRACTION === '1'
|
||||
// Every local engine seen missing this run — cloud-substituted or not. Stamped
|
||||
// onto last-run.json by writeRunState so a silent cloud fallback is never silent.
|
||||
const localEnginesMissing = new Set()
|
||||
const WHISPER_MODEL = process.env.MNEMAZINE_WHISPER_MODEL || ''
|
||||
const WHISPER_LANGUAGE = process.env.MNEMAZINE_WHISPER_LANGUAGE || 'ru'
|
||||
const VIDEO_FRAME_LIMIT = Number(process.env.MNEMAZINE_VIDEO_FRAME_LIMIT || '8')
|
||||
@@ -108,6 +136,10 @@ function isVideo(file) {
|
||||
return ['.mp4', '.mov', '.m4v', '.webm', '.mkv'].includes(path.extname(file).toLowerCase())
|
||||
}
|
||||
|
||||
function isAudio(file) {
|
||||
return ['.mp3', '.wav', '.m4a', '.aac', '.flac', '.ogg', '.opus'].includes(path.extname(file).toLowerCase())
|
||||
}
|
||||
|
||||
function isImage(file) {
|
||||
return ['.png', '.jpg', '.jpeg', '.heic', '.webp', '.tiff'].includes(path.extname(file).toLowerCase())
|
||||
}
|
||||
@@ -116,6 +148,23 @@ function isMarkitdownDocument(file) {
|
||||
return ['.pdf', '.docx', '.pptx', '.xlsx', '.html', '.htm'].includes(path.extname(file).toLowerCase())
|
||||
}
|
||||
|
||||
export function tierOf(file) {
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
if (['.md', '.txt', '.json', '.csv'].includes(ext)) return 0
|
||||
if (['.pdf', '.docx', '.pptx', '.xlsx'].includes(ext)) return 1
|
||||
if (isImage(file)) return 2
|
||||
if (isVideo(file) || isAudio(file)) return 3
|
||||
return 1
|
||||
}
|
||||
|
||||
function enginesFor(file) {
|
||||
if (tierOf(file) === 0) return ['text-read']
|
||||
if (isVideo(file) || isAudio(file)) return ['ffmpeg', 'whisper', 'vision-ocr']
|
||||
if (isImage(file)) return ['vision-ocr']
|
||||
if (isMarkitdownDocument(file)) return ['markitdown']
|
||||
return []
|
||||
}
|
||||
|
||||
function videoDurationSeconds(file) {
|
||||
const probe = spawnSync('ffmpeg', ['-i', file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
const match = `${probe.stderr}\n${probe.stdout}`.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/)
|
||||
@@ -190,6 +239,36 @@ async function extractVideo(file, hash) {
|
||||
return joinVideoParts(transcript, frames)
|
||||
}
|
||||
|
||||
async function extractAudio(file, hash) {
|
||||
await ensureDir(TRANSCRIPTS)
|
||||
await ensureDir(VIDEO_AUDIO)
|
||||
const transcriptPath = path.join(TRANSCRIPTS, `${hash}.txt`)
|
||||
if (existsSync(transcriptPath)) return await fs.readFile(transcriptPath, 'utf8')
|
||||
const audioPath = path.join(VIDEO_AUDIO, `${hash}.wav`)
|
||||
const ffmpeg = spawnSync('ffmpeg', [
|
||||
'-y',
|
||||
'-i', file,
|
||||
'-vn',
|
||||
'-ac', '1',
|
||||
'-ar', '16000',
|
||||
'-f', 'wav',
|
||||
audioPath
|
||||
], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
if (ffmpeg.status !== 0 || !existsSync(audioPath)) return ''
|
||||
const whisper = spawnSync('whisper', [
|
||||
audioPath,
|
||||
'--model', WHISPER_MODEL || 'tiny',
|
||||
'--language', WHISPER_LANGUAGE,
|
||||
'--output_dir', TRANSCRIPTS,
|
||||
'--output_format', 'txt',
|
||||
'--fp16', 'False',
|
||||
'--verbose', 'False'
|
||||
], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
const whisperOut = path.join(TRANSCRIPTS, `${hash}.txt`)
|
||||
if (whisper.status === 0 && existsSync(whisperOut)) return await fs.readFile(whisperOut, 'utf8')
|
||||
return ''
|
||||
}
|
||||
|
||||
async function extractVideoFrames(file, hash) {
|
||||
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
|
||||
if (!existsSync(ocr)) return ''
|
||||
@@ -233,25 +312,57 @@ function joinVideoParts(transcript, frameText) {
|
||||
return parts.join('\n\n')
|
||||
}
|
||||
|
||||
// Local-first extraction. Returns { text, engine_used, engines_missing }: a
|
||||
// MISSING engine (binary absent) is reported in engines_missing so the caller can
|
||||
// stop under require-local; a PRESENT engine that yields nothing leaves
|
||||
// engines_missing empty — that is «движок не нашёл», a different outcome that must
|
||||
// not be confused with «движка нет». Engine presence is the ONE truth in
|
||||
// mnemazine-local-engines.mjs (rule 8) — not re-encoded here.
|
||||
//
|
||||
// Text on the extraction/verification/citation path is passed through WHOLE — it
|
||||
// is never compressed or summarised on the way (measured 32–60% dangling links
|
||||
// after compressors). This is a rule, not a gate: keep it that way here and in
|
||||
// llmExtract below.
|
||||
async function extract(file) {
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
if (['.md', '.txt', '.json', '.csv'].includes(ext)) return await fs.readFile(file, 'utf8')
|
||||
if (isVideo(file)) return await extractVideo(file, await sha256(file))
|
||||
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
|
||||
if (existsSync(ocr) && isImage(file)) {
|
||||
const out = spawnSync(ocr, [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
if (out.status === 0) return out.stdout
|
||||
if (['.md', '.txt', '.json', '.csv'].includes(ext)) {
|
||||
return { text: await fs.readFile(file, 'utf8'), engine_used: 'text-read', engines_tried: ['text-read'], engines_missing: [] }
|
||||
}
|
||||
if (isVideo(file)) {
|
||||
const engines_missing = requireEngines(['ffmpeg', 'whisper', 'vision-ocr'])
|
||||
const text = await extractVideo(file, await sha256(file))
|
||||
return { text, engine_used: text ? 'video' : '', engines_tried: ['ffmpeg', 'whisper', 'vision-ocr'], engines_missing }
|
||||
}
|
||||
if (isAudio(file)) {
|
||||
const engines_missing = requireEngines(['ffmpeg', 'whisper'])
|
||||
const text = await extractAudio(file, await sha256(file))
|
||||
return { text, engine_used: text ? 'audio' : '', engines_tried: ['ffmpeg', 'whisper'], engines_missing }
|
||||
}
|
||||
if (isImage(file)) {
|
||||
const engines_missing = requireEngines(['vision-ocr'])
|
||||
if (!engines_missing.length) {
|
||||
const ocr = path.join(ROOT, '.mnemazine/bin/vision-ocr')
|
||||
const out = spawnSync(ocr, [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
if (out.status === 0) return { text: out.stdout, engine_used: 'vision-ocr', engines_tried: ['vision-ocr'], engines_missing: [] }
|
||||
}
|
||||
return { text: '', engine_used: '', engines_tried: ['vision-ocr'], engines_missing }
|
||||
}
|
||||
if (isMarkitdownDocument(file)) {
|
||||
const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
if (markitdown.status === 0 && markitdown.stdout.trim()) return markitdown.stdout
|
||||
const engines_missing = requireEngines(['markitdown'])
|
||||
if (!engines_missing.length) {
|
||||
const markitdown = spawnSync('markitdown', [file], { encoding: 'utf8', timeout: COMMAND_TIMEOUT_MS })
|
||||
if (markitdown.status === 0 && markitdown.stdout.trim()) return { text: markitdown.stdout, engine_used: 'markitdown', engines_tried: ['markitdown'], engines_missing: [] }
|
||||
}
|
||||
return { text: '', engine_used: '', engines_tried: ['markitdown'], engines_missing }
|
||||
}
|
||||
return ''
|
||||
return { text: '', engine_used: '', engines_tried: enginesFor(file), engines_missing: [] }
|
||||
}
|
||||
|
||||
// LLM recognition fallback (deep only). Used ONLY when local engines (Apple
|
||||
// Vision OCR / markitdown / whisper) produced nothing usable — keeps the default
|
||||
// path at 0 tokens. A vision-capable agent reads the file and transcribes it.
|
||||
// The transcription is returned WHOLE (no compression/summary on the way) — same
|
||||
// rule as extract(): compressors drop 32–60% of citation links.
|
||||
async function llmExtract(file) {
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
const kind = isImage(file) ? 'image' : isVideo(file) ? 'video frame still' : 'document'
|
||||
@@ -315,29 +426,6 @@ async function listVaultMarkdownFiles() {
|
||||
return out
|
||||
}
|
||||
|
||||
function noteSectionAfter(text, label) {
|
||||
const start = String(text || '').indexOf(label)
|
||||
if (start === -1) return ''
|
||||
const tail = text.slice(start + label.length)
|
||||
const next = tail.search(/\n##\s+/)
|
||||
return next === -1 ? tail : tail.slice(0, next)
|
||||
}
|
||||
|
||||
function strictKnowledgeReady(text) {
|
||||
const facts = noteSectionAfter(text, 'External facts added before atomization:')
|
||||
const sources = noteSectionAfter(text, 'Public/source expansion:')
|
||||
const factCount = facts
|
||||
.split('\n')
|
||||
.filter(line => /^\s*-\s+\S/.test(line) && !/No external enrichment facts recorded/i.test(line))
|
||||
.length
|
||||
return /^status:\s*"final"\s*$/m.test(text) &&
|
||||
/^verified:\s*true\s*$/m.test(text) &&
|
||||
/^verification_status:\s*"verified"\s*$/m.test(text) &&
|
||||
/^enrichment:\s*"external-research"\s*$/m.test(text) &&
|
||||
factCount >= 2 &&
|
||||
/https?:\/\//i.test(sources)
|
||||
}
|
||||
|
||||
async function hasFinalKnowledgeForHash(hash) {
|
||||
const ref = sourceRef(hash)
|
||||
for (const file of await listVaultMarkdownFiles()) {
|
||||
@@ -357,9 +445,19 @@ async function cachedExtractionText(entry) {
|
||||
return await fs.readFile(path.join(EXTRACTS, textPath), 'utf8').catch(() => '')
|
||||
}
|
||||
|
||||
function runLocalNodeScript(script, args = []) {
|
||||
export function runLocalNodeScript(script, args = []) {
|
||||
const file = path.join(ROOT, 'scripts', script)
|
||||
if (!existsSync(file)) return { skipped: true, reason: `${script} missing` }
|
||||
if (!existsSync(file)) {
|
||||
// Пропавший ОБЯЗАТЕЛЬНЫЙ скрипт — дыра, а не «пропущено»: throw (первый шаг
|
||||
// пошаговой аттестации, полная — П11). Всё, чего нет в REQUIRED_FINISH_SCRIPTS
|
||||
// (в т.ч. .gitignore-нутый refresh-core-indexes, отсутствующий на чужом клоне
|
||||
// по замыслу), остаётся мягким пропуском — иначе П03 сломал бы чужую установку,
|
||||
// а это тот же провал, что дыра.
|
||||
if (REQUIRED_FINISH_SCRIPTS.has(script)) {
|
||||
throw new Error(`required pipeline script missing: ${script}`)
|
||||
}
|
||||
return { skipped: true, reason: `${script} missing` }
|
||||
}
|
||||
const result = spawnSync(process.execPath, [file, ...args], { encoding: 'utf8', env: process.env, timeout: COMMAND_TIMEOUT_MS * 5 })
|
||||
return {
|
||||
skipped: false,
|
||||
@@ -400,14 +498,78 @@ function failRunState(payload, code = 1) {
|
||||
|
||||
async function writeRunState(state) {
|
||||
await ensureDir(STATE)
|
||||
await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
||||
// local_engine_missing is stamped on EVERY state write (single writer), so a
|
||||
// cloud fallback that stood in for an absent local engine is always on the record.
|
||||
const enriched = { ...state, local_engine_missing: [...localEnginesMissing] }
|
||||
await fs.writeFile(path.join(STATE, 'last-run.json'), `${JSON.stringify(enriched, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
function validateDeepRun({ synthesize, processed }) {
|
||||
function sidecarPresentFor(file, hash) {
|
||||
if (!hash) return false
|
||||
if (existsSync(path.join(EXTRACTS, `${hash}.txt`))) return true
|
||||
if ((isVideo(file) || isAudio(file)) && existsSync(path.join(TRANSCRIPTS, `${hash}.txt`))) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function c2paManifestPresent(file) {
|
||||
if (!isImage(file) && !isVideo(file)) return undefined
|
||||
const dir = path.dirname(file)
|
||||
const name = path.basename(file)
|
||||
const stem = name.replace(/\.[^.]+$/, '')
|
||||
const candidates = [
|
||||
`${file}.c2pa`,
|
||||
`${file}.c2pa.json`,
|
||||
path.join(dir, `${stem}.c2pa`),
|
||||
path.join(dir, `${stem}.c2pa.json`),
|
||||
path.join(dir, `${stem}.manifest.json`)
|
||||
]
|
||||
for (const candidate of candidates) {
|
||||
if (!existsSync(candidate)) continue
|
||||
try { readFileSync(candidate) } catch {}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
async function appendRunObservation(row) {
|
||||
await ensureDir(STATE)
|
||||
await fs.appendFile(path.join(STATE, 'run-observability.jsonl'), `${JSON.stringify(row)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
function observationFor(file, hash, overrides = {}) {
|
||||
const ext = path.extname(file).toLowerCase()
|
||||
const tier = tierOf(file)
|
||||
const row = {
|
||||
ts: new Date().toISOString(),
|
||||
run_id: RUN_ID,
|
||||
file,
|
||||
ext,
|
||||
tier,
|
||||
sidecar_present: sidecarPresentFor(file, hash),
|
||||
engines_tried: enginesFor(file),
|
||||
engine_used: '',
|
||||
llm_extract_used: false,
|
||||
deep: DEEP_ALLOWED && tier >= 1,
|
||||
...overrides
|
||||
}
|
||||
const c2pa = c2paManifestPresent(file)
|
||||
if (typeof c2pa === 'boolean') row.c2pa_manifest = c2pa
|
||||
return row
|
||||
}
|
||||
|
||||
function validateDeepRun({ synthesize, processed, inboxCount, cachedOnly = 0, observations = [] }) {
|
||||
const failures = []
|
||||
if (!DEEP) failures.push('deep mode was required but run did not use --deep')
|
||||
if (processed <= 0) return failures
|
||||
if (!synthesize || synthesize.skipped) failures.push('deep synthesis did not run')
|
||||
const deepRows = observations.filter(row => row.tier >= 1)
|
||||
const missingDeep = deepRows.filter(row => row.deep !== true)
|
||||
if (missingDeep.length) failures.push(`deep stage missing for ${missingDeep.length} tier>=1 units`)
|
||||
if (processed <= 0) {
|
||||
// Zero processed with a non-empty inbox is a strict-run failure: something was
|
||||
// there to handle and nothing was. Zero-in / zero-out stays legal.
|
||||
if (inboxCount > 0 && cachedOnly <= 0) failures.push('нечего обработать при непустом инбоксе')
|
||||
return failures
|
||||
}
|
||||
if (deepRows.length === 0) return failures
|
||||
if (!synthesize || (synthesize.skipped && Number(synthesize.atomized || 0) <= 0 && Number(synthesize.written || 0) <= 0)) failures.push('deep synthesis did not run')
|
||||
if (synthesize?.degraded) failures.push('deep synthesis degraded to local template')
|
||||
if (processed > 0 && Number(synthesize?.atomized || 0) <= 0) failures.push('deep synthesis produced zero atoms')
|
||||
if (processed > 0 && ENRICH_REQUIRED && Number(synthesize?.enriched || 0) <= 0) failures.push('deep enrichment produced zero enriched clusters')
|
||||
@@ -499,11 +661,56 @@ async function writeActionBrief(finishResult) {
|
||||
return out
|
||||
}
|
||||
|
||||
// Скрипты, которые finishRun обязан найти в scripts/. Все восемь git-tracked —
|
||||
// значит на чистом клоне они присутствуют, и пропажа любого = реальная дыра, а не
|
||||
// частичная копия. Это единственный источник правды об «обязательном»: то, чего
|
||||
// здесь нет (напр. .gitignore:48 mnemazine-refresh-core-indexes.mjs, которого на
|
||||
// чужом клоне нет по замыслу), runLocalNodeScript мягко пропускает.
|
||||
const REQUIRED_FINISH_SCRIPTS = new Set([
|
||||
'mnemazine-tool-decision-queue.mjs',
|
||||
'mnemazine-vault-quality-gate.mjs',
|
||||
'mnemazine-refresh-graphify.mjs',
|
||||
'mnemazine-semantic-graph-task.mjs',
|
||||
'mnemazine-weekly-brief-html.mjs',
|
||||
'mnemazine-report-quality-gate.mjs',
|
||||
'mnemazine-postrun-knowledge-report.mjs',
|
||||
'mnemazine-human-layer-gate.mjs'
|
||||
])
|
||||
|
||||
// Один элемент finish.* «в порядке», если: он был легально пропущен (стадия
|
||||
// выключена env-ом или скрипт не обязателен), отработал зелёным, ИЛИ это граф с
|
||||
// кодом 2 — задокументированный semantic-pending при --mark-semantic-pending.
|
||||
function finishGateOk(key, entry) {
|
||||
if (!entry || typeof entry !== 'object') return false
|
||||
if (entry.skipped === true) return true
|
||||
if (entry.ok === true) return true
|
||||
if (key === 'graph' && entry.code === 2) return true
|
||||
return false
|
||||
}
|
||||
|
||||
// result.ok больше не литерал: прогон зелёный только если ноль файлов упало И
|
||||
// каждый обязательный элемент finish.* в легальном состоянии. Коды гейтов,
|
||||
// собранные finishRun, наконец читаются — до архива они решали, после архива
|
||||
// теперь не «советуют», а считаются. finish === null (черновая ветка/FINISH=0):
|
||||
// решает только failed.
|
||||
function computeRunOk(failed, finish) {
|
||||
if (Number(failed || 0) !== 0) return false
|
||||
if (!finish || finish.skipped === true) return true
|
||||
for (const [key, entry] of Object.entries(finish)) {
|
||||
if (key === 'brief') continue // путь к файлу, не гейт
|
||||
if (!finishGateOk(key, entry)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function finishRun(runStartedAt) {
|
||||
const result = {}
|
||||
result.tool_queue = runLocalNodeScript('mnemazine-tool-decision-queue.mjs', ['--changed-since', runStartedAt, '--session', new Date().toISOString().slice(0, 10)])
|
||||
result.quality = runLocalNodeScript('mnemazine-vault-quality-gate.mjs', ['--changed-since', runStartedAt, '--max-failures', '50'])
|
||||
result.graph = runLocalNodeScript('mnemazine-refresh-graphify.mjs', ['--vault', VAULT, '--mode', 'auto', '--json'])
|
||||
result.graph = runLocalNodeScript('mnemazine-refresh-graphify.mjs', ['--vault', VAULT, '--mode', process.env.MNEMAZINE_FINISH_GRAPH_MODE || 'code', '--mark-semantic-pending', '--json'])
|
||||
result.semantic_graph_task = process.env.MNEMAZINE_FINISH_SEMANTIC_ASYNC === '0'
|
||||
? { skipped: true, reason: 'disabled by MNEMAZINE_FINISH_SEMANTIC_ASYNC=0' }
|
||||
: runLocalNodeScript('mnemazine-semantic-graph-task.mjs', ['--start', '--vault', VAULT])
|
||||
result.weekly = runLocalNodeScript('mnemazine-weekly-brief-html.mjs')
|
||||
const weeklyReport = result.weekly?.stdout?.match(/\/[^\s]+\.html/)?.[0]
|
||||
result.report_quality = weeklyReport
|
||||
@@ -535,17 +742,30 @@ async function main() {
|
||||
const toArchive = []
|
||||
const synthSourceRefs = new Set()
|
||||
let failed = 0
|
||||
const canLlmExtract = DEEP && llmAvailable()
|
||||
const observations = []
|
||||
const canLlmExtract = llmAvailable()
|
||||
for (const [index, entry] of entries.entries()) {
|
||||
const file = path.join(INBOX, entry.name)
|
||||
let observation = observationFor(file, '', { engines_tried: enginesFor(file) })
|
||||
// Per-file isolation: one file's recognition failure must NEVER break the
|
||||
// others. Any throw here is contained — the file stays in inbox for a retry.
|
||||
try {
|
||||
const hash = await sha256(file)
|
||||
observation = observationFor(file, hash)
|
||||
if (cache[hash]) {
|
||||
if (await hasFinalKnowledgeForHash(hash)) {
|
||||
toArchive.push({ file, hash })
|
||||
cachedOnly += 1
|
||||
observation.engine_used = 'cache'
|
||||
observations.push(observation)
|
||||
await appendRunObservation(observation)
|
||||
continue
|
||||
}
|
||||
if (DRAFT_ONLY && cache[hash].status === 'draft_complete') {
|
||||
cachedOnly += 1
|
||||
observation.engine_used = 'cache'
|
||||
observations.push(observation)
|
||||
await appendRunObservation(observation)
|
||||
continue
|
||||
}
|
||||
const cachedText = await cachedExtractionText(cache[hash])
|
||||
@@ -553,16 +773,34 @@ async function main() {
|
||||
synthSourceRefs.add(cache[hash].source_ref || sourceRef(hash))
|
||||
toArchive.push({ file, hash })
|
||||
processed += 1
|
||||
observation.engine_used = 'cache'
|
||||
observations.push(observation)
|
||||
await appendRunObservation(observation)
|
||||
continue
|
||||
}
|
||||
delete cache[hash]
|
||||
}
|
||||
// Local-first recognition (0 tokens): Apple Vision OCR / markitdown / whisper.
|
||||
let text = await extract(file)
|
||||
const extraction = await extract(file)
|
||||
observation.engines_tried = extraction.engines_tried || observation.engines_tried
|
||||
observation.engine_used = extraction.engine_used || ''
|
||||
let text = extraction.text
|
||||
// Two outcomes are now distinct. A MISSING engine is not «движок ничего не
|
||||
// нашёл»: under require-local we STOP here (exit 3, before any state write)
|
||||
// instead of letting the cloud silently stand in. Otherwise the cloud may
|
||||
// take over — but the substitution is recorded on run state, not silent.
|
||||
if (extraction.engines_missing.length) {
|
||||
for (const name of extraction.engines_missing) localEnginesMissing.add(name)
|
||||
if (REQUIRE_LOCAL) {
|
||||
console.error(JSON.stringify({ require_local_stop: true, file: entry.name, local_engine_missing: extraction.engines_missing }))
|
||||
process.exit(3)
|
||||
}
|
||||
}
|
||||
// Only if local produced nothing usable AND deep is on: LLM recognition.
|
||||
if (!hasUsableExtraction(text) && canLlmExtract && (isImage(file) || isVideo(file) || isMarkitdownDocument(file))) {
|
||||
if (!hasUsableExtraction(text) && observation.deep && canLlmExtract && (isImage(file) || isVideo(file) || isAudio(file) || isMarkitdownDocument(file))) {
|
||||
try {
|
||||
const llmText = await llmExtract(file)
|
||||
observation.llm_extract_used = true
|
||||
if (hasUsableExtraction(llmText)) text = llmText
|
||||
} catch (err) {
|
||||
console.error(JSON.stringify({ file: entry.name, llm_extract_error: String(err.message).slice(0, 200) }))
|
||||
@@ -579,9 +817,13 @@ async function main() {
|
||||
toArchive.push({ file, hash })
|
||||
processed += 1
|
||||
}
|
||||
observations.push(observation)
|
||||
await appendRunObservation(observation)
|
||||
} catch (err) {
|
||||
// Isolated failure: log, leave file in inbox, keep going.
|
||||
failed += 1
|
||||
observations.push(observation)
|
||||
await appendRunObservation(observation)
|
||||
console.error(JSON.stringify({ file: entry.name, extract_error: String(err.message).slice(0, 200) }))
|
||||
}
|
||||
if (PROGRESS_EVERY > 0 && (index + 1) % PROGRESS_EVERY === 0) {
|
||||
@@ -589,12 +831,13 @@ async function main() {
|
||||
}
|
||||
}
|
||||
await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8')
|
||||
const hasDeepUnits = observations.some(row => row.deep === true && row.engine_used)
|
||||
let synthesize = { skipped: true, reason: processed > 0 ? 'disabled' : 'no newly extracted sources' }
|
||||
if (SYNTHESIZE && processed > 0) {
|
||||
// Stages: extraction+understanding already done above; synthesize runs
|
||||
// research/verification/atomization (deep) and writes vault atoms.
|
||||
const synthArgs = [path.join(ROOT, 'scripts/mnemazine-synthesize.mjs')]
|
||||
if (DEEP) synthArgs.push('--deep')
|
||||
if (hasDeepUnits) synthArgs.push('--deep')
|
||||
const synthEnv = { ...process.env }
|
||||
if (synthSourceRefs.size) synthEnv.MNEMAZINE_SYNTH_SOURCE_REFS = [...synthSourceRefs].join(',')
|
||||
const synth = spawnSync(process.execPath, synthArgs, { encoding: 'utf8', env: synthEnv })
|
||||
@@ -608,18 +851,28 @@ async function main() {
|
||||
vaultMarkdownFiles = null
|
||||
}
|
||||
if (REQUIRE_DEEP) {
|
||||
const deepFailures = validateDeepRun({ synthesize, processed })
|
||||
const deepFailures = validateDeepRun({ synthesize, processed, cachedOnly, inboxCount: entries.length, observations })
|
||||
if (deepFailures.length) {
|
||||
await writeRunState({ ok: false, failures: deepFailures, 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, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() })
|
||||
console.error(JSON.stringify({ ok: false, failures: deepFailures, synthesize }, null, 2))
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
const quality = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), '--changed-since', runStartedAt, '--max-failures', '50'], { stdio: 'inherit', env: process.env })
|
||||
const qualityArgs = [path.join(ROOT, 'scripts/mnemazine-vault-quality-gate.mjs'), '--changed-since', runStartedAt, '--max-failures', '50']
|
||||
if (processed === 0 && cachedOnly > 0) qualityArgs.push('--allow-empty')
|
||||
const quality = spawnSync(process.execPath, qualityArgs, { stdio: 'inherit', env: process.env })
|
||||
if (quality.status !== 0) {
|
||||
await writeRunState({ ok: false, failure: 'run vault quality failed', 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, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() })
|
||||
process.exit(quality.status || 1)
|
||||
}
|
||||
if (DRAFT_ONLY) {
|
||||
for (const item of toArchive) if (cache[item.hash]) cache[item.hash].status = 'draft_complete'
|
||||
await fs.writeFile(CACHE, JSON.stringify(cache, null, 2), 'utf8')
|
||||
const result = { ok: computeRunOk(failed, null), draft_only: true, inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: 0, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
|
||||
await writeRunState(result)
|
||||
console.log(JSON.stringify(result, null, 2))
|
||||
return
|
||||
}
|
||||
const missingFinalNotes = []
|
||||
vaultMarkdownFiles = null
|
||||
for (const item of toArchive) {
|
||||
@@ -633,7 +886,7 @@ async function main() {
|
||||
}
|
||||
// Deep + final stage before archive: Russian humanizer digest + human-layer
|
||||
// gate. If this fails, sources stay in inbox for a safe retry.
|
||||
if (DEEP) {
|
||||
if (hasDeepUnits) {
|
||||
const digest = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-digest.mjs'), '--changed-since', runStartedAt], { stdio: 'inherit', env: process.env })
|
||||
if (digest.status !== 0) {
|
||||
await failRunState({
|
||||
@@ -646,6 +899,42 @@ async function main() {
|
||||
extra: { failure: 'digest failed before archive' }
|
||||
}, digest.status || 1)
|
||||
}
|
||||
// План П13 fixup: humanize-пас МЕЖДУ генерацией ноты и sweep. Конвейер (digest/
|
||||
// LLM) рождает слоп и падал бы о собственный sweep. Пас очеловечивает каждую
|
||||
// свежую ноту ДО сторожа: гейт → автоправка → повторный гейт; не чинится за 2
|
||||
// итерации → прогон честно падает 1 с именем ноты. Sweep ниже остаётся байтовым
|
||||
// бэкстопом на дочищенном тексте.
|
||||
const humanizePass = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), '--pass', '--vault', VAULT, '--changed-since', runStartedAt], { encoding: 'utf8', env: process.env })
|
||||
if (humanizePass.stdout) process.stdout.write(humanizePass.stdout)
|
||||
if (humanizePass.stderr) process.stderr.write(humanizePass.stderr)
|
||||
if (humanizePass.status !== 0) {
|
||||
await failRunState({
|
||||
inbox: entries.length,
|
||||
processed,
|
||||
cached_only: cachedOnly,
|
||||
failed,
|
||||
synthesize,
|
||||
started_at: runStartedAt,
|
||||
extra: { failure: 'humanize pass could not clear slop before archive' }
|
||||
}, humanizePass.status || 1)
|
||||
}
|
||||
// План П13 шаг 6: гейт сохранности/читаемости по нотам, изменённым с runStartedAt.
|
||||
// Фатален настоящий слоп (hard bans кроме сквозного em-dash); em-dash и низкий score —
|
||||
// advisory, чтобы сторож не краснил живой прогон на дочищенном тексте.
|
||||
const preserve = spawnSync(process.execPath, [path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), '--sweep', '--vault', VAULT, '--changed-since', runStartedAt], { encoding: 'utf8', env: process.env })
|
||||
if (preserve.stdout) process.stdout.write(preserve.stdout)
|
||||
if (preserve.stderr) process.stderr.write(preserve.stderr)
|
||||
if (preserve.status !== 0) {
|
||||
await failRunState({
|
||||
inbox: entries.length,
|
||||
processed,
|
||||
cached_only: cachedOnly,
|
||||
failed,
|
||||
synthesize,
|
||||
started_at: runStartedAt,
|
||||
extra: { failure: 'humanize preservation gate failed before archive' }
|
||||
}, preserve.status || 1)
|
||||
}
|
||||
const refs = [...new Set(toArchive.map(item => sourceRef(item.hash)))]
|
||||
const humanArgs = [path.join(ROOT, 'scripts/mnemazine-human-layer-gate.mjs'), '--notes-only', '--changed-since', runStartedAt]
|
||||
if (refs.length) humanArgs.push('--source-ref', refs.join(','))
|
||||
@@ -667,12 +956,17 @@ async function main() {
|
||||
const archived = []
|
||||
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
|
||||
const finish = FINISH ? await finishRun(runStartedAt) : { skipped: true }
|
||||
const result = { ok: true, inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
|
||||
const result = { ok: 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)
|
||||
console.log(JSON.stringify(result, null, 2))
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
// Запуск main только когда файл исполняется напрямую (node .../mnemazine-run.mjs),
|
||||
// а не импортируется. Импорт нужен пробе runLocalNodeScript (harness на две строки)
|
||||
// и любому будущему потребителю экспортов — он не должен гонять пайплайн.
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
main().catch(err => {
|
||||
console.error(err)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -30,8 +30,12 @@ const BATCH_SIZE = Math.max(1, Number(arg('batch-size', process.env.MNEMAZINE_SE
|
||||
const START = Math.max(0, Number(arg('start', '0')))
|
||||
const LIMIT = Number(arg('limit', '0'))
|
||||
const EXCERPT_CHARS = Math.max(300, Number(arg('excerpt-chars', process.env.MNEMAZINE_SEMANTIC_EXCERPT_CHARS || '900')))
|
||||
const MAX_TOKENS = Math.max(120, Number(arg('max-tokens', process.env.MNEMAZINE_SEMANTIC_MAX_TOKENS || '360')))
|
||||
const CACHE_DIR = path.resolve(arg('cache-dir', process.env.MNEMAZINE_SEMANTIC_CACHE_DIR || path.join(VAULT, '.mnemazine/semantic-cache')))
|
||||
const USE_CACHE = !flag('no-cache')
|
||||
const DRY_RUN = flag('dry-run')
|
||||
const CLUSTER_ONLY = !flag('no-cluster')
|
||||
const CACHE_VERSION = 1
|
||||
|
||||
async function walk(dir) {
|
||||
const out = []
|
||||
@@ -88,7 +92,7 @@ async function ollamaJson(noteText) {
|
||||
const body = {
|
||||
model: MODEL,
|
||||
temperature: 0,
|
||||
max_tokens: 360,
|
||||
max_tokens: MAX_TOKENS,
|
||||
messages: [{
|
||||
role: 'user',
|
||||
content: `Extract 3-5 durable concept nodes and 2-4 relationships from this note. Return ONLY JSON: {"nodes":[{"id":"short-id","label":"Label"}],"edges":[{"source":"id","target":"id","relation":"relates_to"}]}.\n\nNote:\n${noteText}`
|
||||
@@ -106,7 +110,13 @@ async function ollamaJson(noteText) {
|
||||
|
||||
async function extractFile(file) {
|
||||
const rel = path.relative(VAULT, file)
|
||||
const text = excerpt(await fs.readFile(file, 'utf8'))
|
||||
const raw = await fs.readFile(file, 'utf8')
|
||||
const text = excerpt(raw)
|
||||
const cache = cachePath(rel, raw)
|
||||
if (USE_CACHE) {
|
||||
const cached = await readCache(cache)
|
||||
if (cached) return { rel, graph: cached.graph, cached: true, cache }
|
||||
}
|
||||
const parsed = BACKEND === 'ollama'
|
||||
? await ollamaJson(text)
|
||||
: (() => { throw new Error(`unsupported backend ${BACKEND}`) })()
|
||||
@@ -133,7 +143,45 @@ async function extractFile(file) {
|
||||
source_file: rel
|
||||
}))
|
||||
.filter(edge => edge.source && edge.target && edge.source !== edge.target)
|
||||
return { rel, graph: { nodes, links } }
|
||||
const graph = { nodes, links }
|
||||
if (USE_CACHE) await writeCache(cache, { rel, graph })
|
||||
return { rel, graph, cached: false, cache }
|
||||
}
|
||||
|
||||
function cachePath(rel, rawText) {
|
||||
const key = crypto.createHash('sha256').update(JSON.stringify({
|
||||
version: CACHE_VERSION,
|
||||
rel,
|
||||
backend: BACKEND,
|
||||
model: MODEL,
|
||||
excerpt_chars: EXCERPT_CHARS,
|
||||
max_tokens: MAX_TOKENS,
|
||||
text_sha256: crypto.createHash('sha256').update(rawText).digest('hex')
|
||||
})).digest('hex')
|
||||
return path.join(CACHE_DIR, `${key}.json`)
|
||||
}
|
||||
|
||||
async function readCache(file) {
|
||||
if (!existsSync(file)) return null
|
||||
try {
|
||||
const cached = JSON.parse(await fs.readFile(file, 'utf8'))
|
||||
return cached?.graph?.nodes && cached?.graph?.links ? cached : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function writeCache(file, value) {
|
||||
await fs.mkdir(path.dirname(file), { recursive: true })
|
||||
await fs.writeFile(file, `${JSON.stringify({
|
||||
version: CACHE_VERSION,
|
||||
backend: BACKEND,
|
||||
model: MODEL,
|
||||
excerpt_chars: EXCERPT_CHARS,
|
||||
max_tokens: MAX_TOKENS,
|
||||
created_at: new Date().toISOString(),
|
||||
...value
|
||||
}, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
function run(command, args) {
|
||||
@@ -160,7 +208,10 @@ async function main() {
|
||||
selected: selected.length,
|
||||
start: START,
|
||||
batch_size: BATCH_SIZE,
|
||||
excerpt_chars: EXCERPT_CHARS
|
||||
excerpt_chars: EXCERPT_CHARS,
|
||||
max_tokens: MAX_TOKENS,
|
||||
cache_dir: CACHE_DIR,
|
||||
cache: USE_CACHE
|
||||
}
|
||||
if (DRY_RUN) {
|
||||
console.log(JSON.stringify({ ok: true, dry_run: true, ...plan }, null, 2))
|
||||
@@ -181,7 +232,9 @@ async function main() {
|
||||
batch.results.push({
|
||||
file: extracted.rel,
|
||||
nodes: extracted.graph.nodes.length,
|
||||
edges: extracted.graph.links.length
|
||||
edges: extracted.graph.links.length,
|
||||
cached: extracted.cached,
|
||||
cache: extracted.cache
|
||||
})
|
||||
}
|
||||
await writeGraph(GRAPH, base)
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const STATE = process.env.MNEMAZINE_STATE || path.join(ROOT, '.mnemazine/state')
|
||||
const REFRESH = path.join(ROOT, 'scripts/mnemazine-refresh-graphify.mjs')
|
||||
const SWARM = path.join(ROOT, 'scripts/mnemazine-semantic-swarm.mjs')
|
||||
const MERGE = path.join(ROOT, 'scripts/mnemazine-merge-semantic-shards.mjs')
|
||||
const SELF = fileURLToPath(import.meta.url)
|
||||
const argv = process.argv.slice(2)
|
||||
const TASK_TIMEOUT_MS = Number(process.env.MNEMAZINE_SEMANTIC_TASK_TIMEOUT_SECONDS || '7200') * 1000
|
||||
const CLUSTER_TIMEOUT_MS = Number(process.env.MNEMAZINE_SEMANTIC_CLUSTER_TIMEOUT_SECONDS || '900') * 1000
|
||||
const DEFAULT_STALE_HOURS = Number(process.env.MNEMAZINE_SEMANTIC_MONITOR_STALE_HOURS || '3')
|
||||
|
||||
function hasFlag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
function taskFile(stateDir = STATE) {
|
||||
return path.join(stateDir, 'semantic-graph-task.json')
|
||||
}
|
||||
|
||||
function logFile(stateDir = STATE) {
|
||||
return path.join(stateDir, 'semantic-graph-task.log')
|
||||
}
|
||||
|
||||
async function ensureState(stateDir = STATE) {
|
||||
await fs.mkdir(stateDir, { recursive: true })
|
||||
}
|
||||
|
||||
async function readJson(file, fallback = null) {
|
||||
try { return JSON.parse(await fs.readFile(file, 'utf8')) } catch { return fallback }
|
||||
}
|
||||
|
||||
async function writeTaskState(state, stateDir = STATE) {
|
||||
await ensureState(stateDir)
|
||||
await fs.writeFile(taskFile(stateDir), `${JSON.stringify(state, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
|
||||
function pidRunning(pid) {
|
||||
if (!Number.isFinite(Number(pid)) || Number(pid) <= 0) return false
|
||||
try {
|
||||
process.kill(Number(pid), 0)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async function taskStatus(stateDir = STATE) {
|
||||
const state = await readJson(taskFile(stateDir), { status: 'never-run' })
|
||||
const running = state.status === 'running' && pidRunning(state.pid)
|
||||
const progressFile = state.progress_file || (state.shards_dir ? path.join(state.shards_dir, 'progress.json') : '')
|
||||
const progress = progressFile ? await readJson(progressFile, null) : null
|
||||
return {
|
||||
...state,
|
||||
running,
|
||||
progress,
|
||||
state_file: taskFile(stateDir),
|
||||
log_file: logFile(stateDir)
|
||||
}
|
||||
}
|
||||
|
||||
function formatSeconds(value) {
|
||||
if (value === null || value === undefined || value === '') return 'n/a'
|
||||
const seconds = Number(value)
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return 'n/a'
|
||||
const rounded = Math.round(seconds)
|
||||
if (rounded < 60) return `${rounded}s`
|
||||
const minutes = Math.round(rounded / 60)
|
||||
if (minutes < 60) return `${minutes}m`
|
||||
const hours = Math.floor(minutes / 60)
|
||||
const rest = String(minutes % 60).padStart(2, '0')
|
||||
return `${hours}h ${rest}m`
|
||||
}
|
||||
|
||||
function listValue(items) {
|
||||
if (!Array.isArray(items) || items.length === 0) return 'none'
|
||||
return items.map(item => {
|
||||
if (typeof item === 'string') return item
|
||||
return item?.file || item?.path || item?.shard || item?.id || JSON.stringify(item)
|
||||
}).join(', ')
|
||||
}
|
||||
|
||||
function taskElapsedSeconds(status) {
|
||||
const start = Date.parse(status.started_at || '')
|
||||
const end = status.running ? Date.now() : Date.parse(status.finished_at || '')
|
||||
if (Number.isFinite(start) && Number.isFinite(end) && end >= start) return (end - start) / 1000
|
||||
const progressElapsed = Number(status.progress?.elapsed_seconds)
|
||||
return Number.isFinite(progressElapsed) && progressElapsed >= 0 ? progressElapsed : null
|
||||
}
|
||||
|
||||
function ageHoursFromIso(value) {
|
||||
const start = Date.parse(value || '')
|
||||
if (!Number.isFinite(start)) return null
|
||||
return Math.max(0, (Date.now() - start) / 3600000)
|
||||
}
|
||||
|
||||
function prettyStatus(status) {
|
||||
const progress = status.progress
|
||||
const lines = [
|
||||
`Semantic: ${status.status || 'unknown'} | ${status.strategy || 'unknown'} | ${progress?.phase || (status.running ? 'running' : 'idle')}`
|
||||
]
|
||||
lines.push(`Task: running ${status.running ? 'yes' : 'no'} | PID ${status.pid || 'n/a'} | elapsed ${formatSeconds(taskElapsedSeconds(status))}`)
|
||||
if (progress) {
|
||||
const failed = Array.isArray(progress.failed_jobs) ? progress.failed_jobs : []
|
||||
const completed = progress.completed_jobs ?? 0
|
||||
const total = progress.total_jobs ?? 0
|
||||
const remaining = progress.remaining_jobs ?? Math.max(0, Number(total) - Number(completed))
|
||||
const skipped = progress.skipped_completed_jobs ?? progress.skipped_jobs ?? 0
|
||||
lines.push(`Jobs: ${completed}/${total} done | remaining ${remaining} | skipped ${skipped} | active ${listValue(progress.active_jobs)} | failed ${failed.length} | ETA ${formatSeconds(progress.eta_seconds)}`)
|
||||
if (failed.length > 0) lines.push(`First fail: ${listValue(failed.slice(0, 1))}`)
|
||||
} else {
|
||||
lines.push('Jobs: progress unavailable')
|
||||
}
|
||||
lines.push(`Vault: ${status.vault || 'unknown'}`)
|
||||
lines.push(`Progress: ${status.progress_file || 'n/a'}`)
|
||||
lines.push(`Log: ${status.log_file || 'n/a'}`)
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function stripTaskArgs(args, options = {}) {
|
||||
const flags = new Set(['--start', '--status', '--monitor', '--worker', '--foreground', '--selftest', '--pretty', '--dry-run'])
|
||||
if (!options.keepFresh) flags.add('--fresh')
|
||||
flags.add('--resume')
|
||||
const valueOptions = new Set(['--mode', '--strategy', '--stale-hours'])
|
||||
const out = []
|
||||
for (let i = 0; i < args.length; i += 1) {
|
||||
const item = args[i]
|
||||
if (flags.has(item)) continue
|
||||
if (valueOptions.has(item)) {
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
if ([...valueOptions].some(name => item.startsWith(`${name}=`))) continue
|
||||
if (item === '--json') continue
|
||||
out.push(item)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function needsUpdateMarker(vault) {
|
||||
const file = path.join(vault, 'graphify-out', 'needs_update')
|
||||
if (!existsSync(file)) return null
|
||||
const stat = await fs.stat(file).catch(() => null)
|
||||
return {
|
||||
file,
|
||||
exists: true,
|
||||
content: await fs.readFile(file, 'utf8').catch(() => ''),
|
||||
age_hours: stat ? Math.max(0, (Date.now() - stat.mtimeMs) / 3600000) : null
|
||||
}
|
||||
}
|
||||
|
||||
function monitorReason(status, marker, staleHours) {
|
||||
const elapsedHours = ageHoursFromIso(status.started_at)
|
||||
if (status.running) {
|
||||
return elapsedHours !== null && elapsedHours >= staleHours
|
||||
? { action: 'wait', reason: 'running-stale-live-pid', elapsed_hours: elapsedHours }
|
||||
: { action: 'wait', reason: 'running', elapsed_hours: elapsedHours }
|
||||
}
|
||||
if (status.status === 'running') return { action: 'start', reason: 'running-dead-pid', elapsed_hours: elapsedHours }
|
||||
if (['pending', 'failed'].includes(String(status.status || ''))) return { action: 'start', reason: status.status, elapsed_hours: elapsedHours }
|
||||
if (marker?.exists && Number(marker.age_hours) >= staleHours) return { action: 'start', reason: 'needs-update-stale', marker_age_hours: marker.age_hours }
|
||||
return { action: 'none', reason: marker?.exists ? 'needs-update-not-stale' : 'clean', marker_age_hours: marker?.age_hours ?? null }
|
||||
}
|
||||
|
||||
function progressDone(progress) {
|
||||
if (!progress) return false
|
||||
if (progress.phase === 'done') return true
|
||||
const total = Number(progress.total_jobs)
|
||||
const completed = Number(progress.completed_jobs)
|
||||
const failed = Array.isArray(progress.failed_jobs) ? progress.failed_jobs.length : 0
|
||||
return Number.isFinite(total) && total >= 0 && completed >= total && failed === 0
|
||||
}
|
||||
|
||||
async function resumeCandidate(vault, stateDir = STATE) {
|
||||
const previous = await taskStatus(stateDir)
|
||||
if (previous.running) return null
|
||||
if (!['running', 'pending', 'failed'].includes(String(previous.status || ''))) return null
|
||||
if (previous.vault && path.resolve(previous.vault) !== path.resolve(vault)) return null
|
||||
if (!previous.shards_dir || !existsSync(previous.shards_dir)) return null
|
||||
if (progressDone(previous.progress)) return null
|
||||
return previous
|
||||
}
|
||||
|
||||
function hasOption(args, name) {
|
||||
return args.includes(`--${name}`) || args.some(item => item.startsWith(`--${name}=`))
|
||||
}
|
||||
|
||||
function parseJsonOutput(text) {
|
||||
const raw = String(text || '').trim()
|
||||
const start = raw.indexOf('{')
|
||||
const end = raw.lastIndexOf('}')
|
||||
if (start === -1 || end < start) return null
|
||||
try { return JSON.parse(raw.slice(start, end + 1)) } catch { return null }
|
||||
}
|
||||
|
||||
function runRefresh(args, timeoutMs = TASK_TIMEOUT_MS) {
|
||||
return runCommand(process.execPath, [REFRESH, ...args], timeoutMs)
|
||||
}
|
||||
|
||||
function runCommand(command, args, timeoutMs = TASK_TIMEOUT_MS) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: ROOT,
|
||||
env: process.env,
|
||||
stdio: ['ignore', 'pipe', 'pipe']
|
||||
})
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
let timedOut = false
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true
|
||||
child.kill('SIGTERM')
|
||||
setTimeout(() => child.kill('SIGKILL'), 5000).unref()
|
||||
}, timeoutMs)
|
||||
child.stdout.on('data', chunk => { stdout += String(chunk) })
|
||||
child.stderr.on('data', chunk => { stderr += String(chunk) })
|
||||
child.on('close', code => {
|
||||
clearTimeout(timer)
|
||||
resolve({ code: code ?? 1, stdout, stderr, timedOut })
|
||||
})
|
||||
child.on('error', error => {
|
||||
clearTimeout(timer)
|
||||
resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}`, timedOut })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function addDefault(args, name, value) {
|
||||
if (!hasOption(args, name)) args.push(`--${name}`, String(value))
|
||||
}
|
||||
|
||||
async function runSwarm(vault, passthrough) {
|
||||
const graph = path.join(vault, 'graphify-out', 'graph.json')
|
||||
const needsUpdate = path.join(vault, 'graphify-out', 'needs_update')
|
||||
const dryRun = passthrough.includes('--dry-run')
|
||||
const swarmArgs = ['--vault', vault, '--graph', graph, ...passthrough]
|
||||
addDefault(swarmArgs, 'chunk-size', process.env.MNEMAZINE_SEMANTIC_SWARM_CHUNK_SIZE || '40')
|
||||
addDefault(swarmArgs, 'batch-size', process.env.MNEMAZINE_SEMANTIC_SWARM_BATCH_SIZE || '1')
|
||||
addDefault(swarmArgs, 'excerpt-chars', process.env.MNEMAZINE_SEMANTIC_EXCERPT_CHARS || '600')
|
||||
addDefault(swarmArgs, 'max-tokens', process.env.MNEMAZINE_SEMANTIC_MAX_TOKENS || '360')
|
||||
addDefault(swarmArgs, 'concurrency', process.env.MNEMAZINE_SEMANTIC_SWARM_CONCURRENCY || '2')
|
||||
|
||||
const swarm = await runCommand(process.execPath, [SWARM, ...swarmArgs])
|
||||
const parsedSwarm = parseJsonOutput(swarm.stdout)
|
||||
const steps = { swarm: { ok: swarm.code === 0 && parsedSwarm?.ok !== false, code: swarm.code, timedOut: swarm.timedOut, parsed: parsedSwarm } }
|
||||
if (dryRun || !steps.swarm.ok) {
|
||||
return {
|
||||
code: dryRun && steps.swarm.ok ? 2 : (swarm.code || 1),
|
||||
timedOut: swarm.timedOut,
|
||||
stdout: JSON.stringify({ ok: steps.swarm.ok, mode: 'swarm', dry_run: dryRun, semantic_pending_after: true, steps }, null, 2),
|
||||
stderr: swarm.stderr
|
||||
}
|
||||
}
|
||||
|
||||
const merge = await runCommand(process.execPath, [
|
||||
MERGE,
|
||||
'--vault', vault,
|
||||
'--graph', graph,
|
||||
'--shards-dir', parsedSwarm.shards_dir,
|
||||
'--manifest', parsedSwarm.manifest
|
||||
])
|
||||
const parsedMerge = parseJsonOutput(merge.stdout)
|
||||
steps.merge = { ok: merge.code === 0 && parsedMerge?.ok !== false, code: merge.code, timedOut: merge.timedOut, parsed: parsedMerge }
|
||||
|
||||
const cluster = steps.merge.ok
|
||||
? await runCommand('graphify', ['cluster-only', vault, '--graph', graph, '--no-viz'], CLUSTER_TIMEOUT_MS)
|
||||
: { code: 1, timedOut: false, stdout: '', stderr: 'merge failed; cluster skipped' }
|
||||
steps.cluster = { ok: cluster.code === 0 && !cluster.timedOut, code: cluster.code, timedOut: cluster.timedOut, stdout_tail: String(cluster.stdout || '').trim().split('\n').slice(-5).join('\n'), stderr_tail: String(cluster.stderr || '').trim().split('\n').slice(-5).join('\n') }
|
||||
|
||||
const ok = steps.swarm.ok && steps.merge.ok && steps.cluster.ok
|
||||
if (ok) await fs.rm(needsUpdate, { force: true }).catch(() => {})
|
||||
return {
|
||||
code: ok ? 0 : 2,
|
||||
timedOut: Boolean(swarm.timedOut || merge.timedOut || cluster.timedOut),
|
||||
stdout: JSON.stringify({ ok, mode: 'swarm', vault, graph, semantic_pending_after: !ok, steps }, null, 2),
|
||||
stderr: [swarm.stderr, merge.stderr, cluster.stderr].filter(Boolean).join('\n')
|
||||
}
|
||||
}
|
||||
|
||||
async function runWorker() {
|
||||
const fresh = hasFlag('fresh') || hasFlag('no-resume')
|
||||
const passthrough = stripTaskArgs(argv)
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const strategy = arg('strategy', process.env.MNEMAZINE_SEMANTIC_TASK_STRATEGY || 'swarm')
|
||||
const startedAt = new Date().toISOString()
|
||||
let shardsDir = arg('shards-dir', '')
|
||||
let resumedFrom = null
|
||||
if (strategy !== 'full' && !shardsDir && !fresh) {
|
||||
resumedFrom = await resumeCandidate(vault)
|
||||
if (resumedFrom) {
|
||||
shardsDir = resumedFrom.shards_dir
|
||||
passthrough.push('--shards-dir', shardsDir)
|
||||
}
|
||||
}
|
||||
if (strategy !== 'full' && !shardsDir) {
|
||||
shardsDir = process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR
|
||||
? path.join(process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR, startedAt.replace(/[:.]/g, '-'))
|
||||
: path.join(vault, '.mnemazine/semantic-shards', startedAt.replace(/[:.]/g, '-'))
|
||||
passthrough.push('--shards-dir', shardsDir)
|
||||
}
|
||||
const progressFile = strategy !== 'full' && shardsDir ? path.join(shardsDir, 'progress.json') : null
|
||||
const refreshArgs = ['--vault', vault, '--mode', 'semantic', '--json']
|
||||
if (!hasOption(passthrough, 'timeout-seconds') && process.env.MNEMAZINE_SEMANTIC_REFRESH_TIMEOUT_SECONDS) refreshArgs.push('--timeout-seconds', process.env.MNEMAZINE_SEMANTIC_REFRESH_TIMEOUT_SECONDS)
|
||||
refreshArgs.push(...passthrough)
|
||||
await writeTaskState({
|
||||
status: 'running',
|
||||
pid: process.pid,
|
||||
started_at: startedAt,
|
||||
vault,
|
||||
strategy,
|
||||
fresh,
|
||||
resume_from: resumedFrom ? {
|
||||
status: resumedFrom.status,
|
||||
started_at: resumedFrom.started_at || null,
|
||||
shards_dir: resumedFrom.shards_dir,
|
||||
progress_file: resumedFrom.progress_file || null
|
||||
} : null,
|
||||
shards_dir: shardsDir || null,
|
||||
progress_file: progressFile,
|
||||
command: strategy === 'full'
|
||||
? `node scripts/mnemazine-refresh-graphify.mjs ${refreshArgs.join(' ')}`
|
||||
: `node scripts/mnemazine-semantic-swarm.mjs --vault ${vault}`,
|
||||
log_file: logFile()
|
||||
})
|
||||
const result = strategy === 'full'
|
||||
? await runRefresh(refreshArgs)
|
||||
: await runSwarm(vault, passthrough)
|
||||
const parsed = parseJsonOutput(result.stdout)
|
||||
const status = result.code === 0 && !result.timedOut && parsed?.ok !== false
|
||||
? 'succeeded'
|
||||
: result.code === 2 || parsed?.semantic_pending_after
|
||||
? 'pending'
|
||||
: 'failed'
|
||||
await fs.writeFile(logFile(), [
|
||||
`# Semantic Graph Task ${startedAt}`,
|
||||
'',
|
||||
`status=${status}`,
|
||||
`exit_code=${result.code}`,
|
||||
`timed_out=${result.timedOut}`,
|
||||
'',
|
||||
'## stdout',
|
||||
result.stdout.trim(),
|
||||
'',
|
||||
'## stderr',
|
||||
result.stderr.trim(),
|
||||
''
|
||||
].join('\n'), 'utf8')
|
||||
await writeTaskState({
|
||||
status,
|
||||
pid: process.pid,
|
||||
running: false,
|
||||
strategy,
|
||||
fresh,
|
||||
resume_from: resumedFrom ? {
|
||||
status: resumedFrom.status,
|
||||
started_at: resumedFrom.started_at || null,
|
||||
shards_dir: resumedFrom.shards_dir,
|
||||
progress_file: resumedFrom.progress_file || null
|
||||
} : null,
|
||||
shards_dir: parsed?.steps?.swarm?.parsed?.shards_dir || shardsDir || null,
|
||||
progress_file: parsed?.steps?.swarm?.parsed?.progress || progressFile,
|
||||
started_at: startedAt,
|
||||
finished_at: new Date().toISOString(),
|
||||
vault,
|
||||
exit_code: result.code,
|
||||
timed_out: result.timedOut,
|
||||
semantic_pending_after: Boolean(parsed?.semantic_pending_after),
|
||||
semantic_status: parsed?.mode || parsed?.semantic_refresh?.status || parsed?.semantic_refresh?.selected?.status || null,
|
||||
chosen_model: parsed?.semantic_refresh?.chosen_model || null,
|
||||
state_file: taskFile(),
|
||||
log_file: logFile()
|
||||
})
|
||||
process.exit(status === 'failed' ? 1 : 0)
|
||||
}
|
||||
|
||||
async function startTask() {
|
||||
const current = await taskStatus()
|
||||
if (current.running) {
|
||||
console.log(JSON.stringify({ ok: true, started: false, reason: 'already running', task: current }, null, 2))
|
||||
return
|
||||
}
|
||||
console.log(JSON.stringify(await spawnTask(resolveVault({ cli: arg('vault') })), null, 2))
|
||||
}
|
||||
|
||||
async function spawnTask(vault) {
|
||||
await ensureState()
|
||||
const child = spawn(process.execPath, [SELF, '--worker', ...stripTaskArgs(argv, { keepFresh: true })], {
|
||||
cwd: ROOT,
|
||||
env: process.env,
|
||||
detached: true,
|
||||
stdio: 'ignore'
|
||||
})
|
||||
child.unref()
|
||||
const state = {
|
||||
status: 'running',
|
||||
pid: child.pid,
|
||||
running: true,
|
||||
started_at: new Date().toISOString(),
|
||||
vault,
|
||||
state_file: taskFile(),
|
||||
log_file: logFile(),
|
||||
status_command: 'npm run graph:semantic:status'
|
||||
}
|
||||
await writeTaskState(state)
|
||||
return { ok: true, started: true, task: state }
|
||||
}
|
||||
|
||||
async function monitorTask() {
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const staleHoursRaw = Number(arg('stale-hours', String(DEFAULT_STALE_HOURS)))
|
||||
const staleHours = Number.isFinite(staleHoursRaw) && staleHoursRaw > 0 ? staleHoursRaw : 3
|
||||
const status = await taskStatus()
|
||||
const marker = await needsUpdateMarker(vault)
|
||||
const decision = monitorReason(status, marker, staleHours)
|
||||
let start = null
|
||||
if (decision.action === 'start' && !hasFlag('dry-run')) {
|
||||
const current = await taskStatus()
|
||||
if (current.running) {
|
||||
start = { ok: true, started: false, reason: 'already running', task: current }
|
||||
} else {
|
||||
start = await spawnTask(vault)
|
||||
}
|
||||
}
|
||||
const output = {
|
||||
ok: decision.action !== 'wait' || decision.reason === 'running',
|
||||
monitor: true,
|
||||
dry_run: hasFlag('dry-run'),
|
||||
stale_hours: staleHours,
|
||||
vault,
|
||||
marker,
|
||||
status,
|
||||
decision,
|
||||
start
|
||||
}
|
||||
if (hasFlag('pretty')) {
|
||||
console.log(`Semantic monitor: ${decision.action} (${decision.reason})`)
|
||||
console.log(`Vault: ${vault}`)
|
||||
console.log(`Task: ${status.status || 'unknown'} | running ${status.running ? 'yes' : 'no'} | PID ${status.pid || 'n/a'}`)
|
||||
if (marker?.exists) console.log(`Marker: ${marker.file} | age ${formatSeconds((marker.age_hours || 0) * 3600)}`)
|
||||
if (start?.started) console.log(`Started: PID ${start.task.pid}`)
|
||||
} else {
|
||||
console.log(JSON.stringify(output, null, 2))
|
||||
}
|
||||
if (!output.ok) process.exit(2)
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-semantic-task-'))
|
||||
await writeTaskState({ status: 'running', pid: 999999, started_at: '2099-01-01T00:00:00.000Z' }, temp)
|
||||
const status = await taskStatus(temp)
|
||||
if (status.running) throw new Error('selftest failed: dead pid reported running')
|
||||
if (!status.state_file.endsWith('semantic-graph-task.json')) throw new Error('selftest failed: state file mismatch')
|
||||
const resumeTemp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-semantic-resume-'))
|
||||
const resumeVault = path.join(resumeTemp, 'vault')
|
||||
const resumeShards = path.join(resumeVault, '.mnemazine/semantic-shards/old')
|
||||
await fs.mkdir(resumeShards, { recursive: true })
|
||||
await fs.writeFile(path.join(resumeShards, 'progress.json'), `${JSON.stringify({ phase: 'running', total_jobs: 2, completed_jobs: 1, failed_jobs: [] })}\n`, 'utf8')
|
||||
await writeTaskState({ status: 'pending', vault: resumeVault, shards_dir: resumeShards, progress_file: path.join(resumeShards, 'progress.json') }, resumeTemp)
|
||||
const candidate = await resumeCandidate(resumeVault, resumeTemp)
|
||||
if (candidate?.shards_dir !== resumeShards) throw new Error('selftest failed: resume candidate not selected')
|
||||
const pretty = prettyStatus({
|
||||
status: 'succeeded',
|
||||
strategy: 'swarm',
|
||||
running: false,
|
||||
pid: 12345,
|
||||
started_at: '2026-01-01T00:00:00.000Z',
|
||||
finished_at: '2026-01-01T00:01:05.000Z',
|
||||
vault: '/tmp/vault',
|
||||
progress_file: '/tmp/progress.json',
|
||||
log_file: '/tmp/log',
|
||||
progress: {
|
||||
phase: 'done',
|
||||
total_jobs: 2,
|
||||
completed_jobs: 1,
|
||||
remaining_jobs: 1,
|
||||
skipped_completed_jobs: 1,
|
||||
active_jobs: [],
|
||||
failed_jobs: [],
|
||||
eta_seconds: null
|
||||
}
|
||||
})
|
||||
if (!pretty.includes('ETA n/a')) throw new Error('selftest failed: null ETA should render as n/a')
|
||||
if (!pretty.includes('remaining 1')) throw new Error('selftest failed: remaining jobs not rendered')
|
||||
if (!pretty.includes('skipped 1')) throw new Error('selftest failed: skipped jobs not rendered')
|
||||
if (pretty.includes('ETA 0s')) throw new Error('selftest failed: null ETA rendered as 0s')
|
||||
if (!pretty.includes('PID 12345')) throw new Error('selftest failed: PID not rendered')
|
||||
if (!pretty.includes('elapsed 1m')) throw new Error('selftest failed: elapsed time not rendered')
|
||||
if (!prettyStatus({ status: 'never-run', strategy: 'swarm' }).includes('Jobs: progress unavailable')) {
|
||||
throw new Error('selftest failed: missing progress fallback not rendered')
|
||||
}
|
||||
const pendingDecision = monitorReason({ status: 'pending', running: false, started_at: new Date().toISOString() }, null, 3)
|
||||
if (pendingDecision.action !== 'start') throw new Error('selftest failed: pending monitor should start')
|
||||
const staleLiveDecision = monitorReason({ status: 'running', running: true, started_at: new Date(Date.now() - 4 * 3600000).toISOString() }, null, 3)
|
||||
if (staleLiveDecision.action !== 'wait' || staleLiveDecision.reason !== 'running-stale-live-pid') throw new Error('selftest failed: stale live pid should not start duplicate task')
|
||||
const markerDecision = monitorReason({ status: 'succeeded', running: false }, { exists: true, age_hours: 4 }, 3)
|
||||
if (markerDecision.action !== 'start') throw new Error('selftest failed: stale marker should start')
|
||||
await fs.rm(temp, { recursive: true, force: true })
|
||||
await fs.rm(resumeTemp, { recursive: true, force: true })
|
||||
console.log(JSON.stringify({ ok: true }, null, 2))
|
||||
}
|
||||
|
||||
if (hasFlag('selftest')) await selftest()
|
||||
else if (hasFlag('worker') || hasFlag('foreground')) await runWorker()
|
||||
else if (hasFlag('status')) {
|
||||
const status = await taskStatus()
|
||||
console.log(hasFlag('pretty') ? prettyStatus(status) : JSON.stringify(status, null, 2))
|
||||
}
|
||||
else if (hasFlag('monitor')) await monitorTask()
|
||||
else await startTask()
|
||||
@@ -5,6 +5,7 @@ import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { graphStats, mergeGraphObjects, readGraph, writeGraph } from './mnemazine-graph-utils.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const ROOT = path.resolve(process.cwd())
|
||||
@@ -19,7 +20,7 @@ function hasFlag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
const VAULT = path.resolve(arg('vault', process.env.MNEMAZINE_VAULT || path.join(process.env.HOME || '.', 'Мозг')))
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out')
|
||||
const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json')
|
||||
const BACKEND = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || 'openai')
|
||||
@@ -54,15 +55,19 @@ async function keychain(service) {
|
||||
return result.stdout.trim()
|
||||
}
|
||||
|
||||
// Graph-backend credential map as DATA (env vars + keychain service per backend),
|
||||
// not a per-provider code branch. New backend = one row here.
|
||||
// ponytail: graph-backend axis, separate from the CLI-connector registry.
|
||||
const BACKEND_CREDENTIALS = {
|
||||
openai: { env: ['OPENAI_API_KEY'], keychain: 'mnemazine/openai_api_key' },
|
||||
kimi: { env: ['KIMI_API_KEY', 'MOONSHOT_API_KEY'], keychain: 'mnemazine/moonshot_api_key' }
|
||||
}
|
||||
|
||||
async function apiEnv() {
|
||||
if (BACKEND === 'openai') {
|
||||
return { OPENAI_API_KEY: process.env.OPENAI_API_KEY || await keychain('mnemazine/openai_api_key') }
|
||||
}
|
||||
if (BACKEND === 'kimi') {
|
||||
const key = process.env.KIMI_API_KEY || process.env.MOONSHOT_API_KEY || await keychain('mnemazine/moonshot_api_key')
|
||||
return { KIMI_API_KEY: key, MOONSHOT_API_KEY: key }
|
||||
}
|
||||
return {}
|
||||
const spec = BACKEND_CREDENTIALS[BACKEND]
|
||||
if (!spec) return {}
|
||||
const key = spec.env.map(name => process.env[name]).find(Boolean) || await keychain(spec.keychain)
|
||||
return Object.fromEntries(spec.env.map(name => [name, key]))
|
||||
}
|
||||
|
||||
async function walkMarkdown(dir) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { spawn } from 'node:child_process'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
@@ -35,7 +36,7 @@ async function countVaultFiles(vault) {
|
||||
|
||||
function runWorker(job) {
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(process.execPath, [
|
||||
const args = [
|
||||
'scripts/mnemazine-semantic-batches.mjs',
|
||||
'--vault', job.vault,
|
||||
'--graph', job.graph,
|
||||
@@ -45,7 +46,12 @@ function runWorker(job) {
|
||||
'--start', String(job.start),
|
||||
'--limit', String(job.limit),
|
||||
'--no-cluster'
|
||||
], { cwd: ROOT, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
]
|
||||
if (job.backend) args.push('--backend', job.backend)
|
||||
if (job.model) args.push('--model', job.model)
|
||||
if (job.cacheDir) args.push('--cache-dir', job.cacheDir)
|
||||
if (!job.cache) args.push('--no-cache')
|
||||
const child = spawn(process.execPath, args, { cwd: ROOT, env: process.env, stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
const chunks = []
|
||||
const errors = []
|
||||
child.stdout.on('data', chunk => chunks.push(chunk))
|
||||
@@ -69,9 +75,12 @@ function runWorker(job) {
|
||||
async function main() {
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const graph = path.resolve(arg('graph', path.join(vault, 'graphify-out/graph.json')))
|
||||
const shardsDir = path.resolve(arg('shards-dir', path.join(vault, `.mnemazine/semantic-shards/${RUN_ID}`)))
|
||||
const shardsDir = path.resolve(arg('shards-dir', process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR ? path.join(process.env.MNEMAZINE_SEMANTIC_SHARDS_DIR, RUN_ID) : path.join(vault, `.mnemazine/semantic-shards/${RUN_ID}`)))
|
||||
const logsDir = path.resolve(arg('logs-dir', path.join(shardsDir, 'logs')))
|
||||
const cacheDir = path.resolve(arg('cache-dir', process.env.MNEMAZINE_SEMANTIC_CACHE_DIR || path.join(vault, '.mnemazine/semantic-cache')))
|
||||
const manifestPath = path.join(shardsDir, 'manifest.json')
|
||||
const progressPath = path.join(shardsDir, 'progress.json')
|
||||
const startedAt = new Date().toISOString()
|
||||
const total = await countVaultFiles(vault)
|
||||
const start = Math.max(0, Number(arg('start', '0')))
|
||||
const limit = Number(arg('limit', String(Math.max(0, total - start))))
|
||||
@@ -79,12 +88,18 @@ async function main() {
|
||||
const batchSize = Math.max(1, Number(arg('batch-size', '1')))
|
||||
const excerptChars = Math.max(300, Number(arg('excerpt-chars', '600')))
|
||||
const maxTokens = Math.max(120, Number(arg('max-tokens', '360')))
|
||||
const backend = arg('backend', process.env.MNEMAZINE_GRAPHIFY_BACKEND || '')
|
||||
const model = arg('model', process.env.MNEMAZINE_GRAPHIFY_MODEL || '')
|
||||
const concurrency = Math.max(1, Number(arg('concurrency', String(Math.min(8, Math.max(1, os.cpus().length - 2))))))
|
||||
const dryRun = flag('dry-run')
|
||||
const resume = !flag('no-resume')
|
||||
const cache = !flag('no-cache')
|
||||
await fs.mkdir(shardsDir, { recursive: true })
|
||||
await fs.mkdir(logsDir, { recursive: true })
|
||||
|
||||
const end = Math.min(total, start + limit)
|
||||
const selected = Math.max(0, end - start)
|
||||
const hadManifest = existsSync(manifestPath)
|
||||
const jobs = []
|
||||
for (let i = start; i < end; i += chunkSize) {
|
||||
const size = Math.min(chunkSize, end - i)
|
||||
@@ -95,16 +110,22 @@ async function main() {
|
||||
graph,
|
||||
shardGraph: path.join(shardsDir, `${name}.json`),
|
||||
log: path.join(logsDir, `${name}.log`),
|
||||
done: path.join(shardsDir, `${name}.done.json`),
|
||||
start: i,
|
||||
limit: size,
|
||||
batchSize,
|
||||
excerptChars,
|
||||
maxTokens
|
||||
maxTokens,
|
||||
backend,
|
||||
model,
|
||||
cacheDir,
|
||||
cache,
|
||||
signature: JSON.stringify({ start: i, limit: size, batchSize, excerptChars, maxTokens, backend, model, cache })
|
||||
})
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
console.log(JSON.stringify({ ok: true, dry_run: true, vault, graph, shards_dir: shardsDir, manifest: manifestPath, total, selected: limit, start, chunk_size: chunkSize, batch_size: batchSize, excerpt_chars: excerptChars, max_tokens: maxTokens, concurrency, jobs: jobs.map(j => ({ name: j.name, start: j.start, limit: j.limit, graph: j.shardGraph })) }, null, 2))
|
||||
console.log(JSON.stringify({ ok: true, dry_run: true, vault, graph, shards_dir: shardsDir, manifest: manifestPath, progress: progressPath, cache_dir: cacheDir, cache, resume, total, selected, start, chunk_size: chunkSize, batch_size: batchSize, excerpt_chars: excerptChars, max_tokens: maxTokens, backend: backend || null, model: model || null, concurrency, jobs: jobs.map(j => ({ name: j.name, start: j.start, limit: j.limit, graph: j.shardGraph, done: j.done })) }, null, 2))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -113,26 +134,95 @@ async function main() {
|
||||
graph,
|
||||
shards_dir: shardsDir,
|
||||
total,
|
||||
selected: limit,
|
||||
selected,
|
||||
start,
|
||||
chunk_size: chunkSize,
|
||||
batch_size: batchSize,
|
||||
excerpt_chars: excerptChars,
|
||||
max_tokens: maxTokens,
|
||||
backend: backend || null,
|
||||
model: model || null,
|
||||
cache_dir: cacheDir,
|
||||
cache,
|
||||
resume,
|
||||
resumed: resume && hadManifest,
|
||||
concurrency,
|
||||
jobs: jobs.map(job => ({ name: job.name, start: job.start, limit: job.limit, graph: job.shardGraph, log: job.log }))
|
||||
progress: progressPath,
|
||||
jobs: jobs.map(job => ({ name: job.name, start: job.start, limit: job.limit, graph: job.shardGraph, log: job.log, done: job.done, signature: job.signature }))
|
||||
}, null, 2)}\n`, 'utf8')
|
||||
|
||||
let next = 0
|
||||
const done = []
|
||||
const skipped = []
|
||||
const active = new Map()
|
||||
async function completedJob(job) {
|
||||
if (!resume || !await fs.access(job.done).then(() => true).catch(() => false)) return false
|
||||
try {
|
||||
const marker = JSON.parse(await fs.readFile(job.done, 'utf8'))
|
||||
return marker.signature === job.signature && await fs.access(job.shardGraph).then(() => true).catch(() => false)
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
async function writeProgress(phase = 'running') {
|
||||
const completed = done.length
|
||||
const failed = done.filter(j => j.code !== 0)
|
||||
const remaining = Math.max(0, jobs.length - completed)
|
||||
const elapsed = Math.max(0, Math.round((Date.now() - Date.parse(startedAt)) / 1000))
|
||||
const eta = completed > 0 && completed < jobs.length
|
||||
? Math.round((elapsed / completed) * (jobs.length - completed))
|
||||
: null
|
||||
await fs.writeFile(progressPath, `${JSON.stringify({
|
||||
ok: failed.length === 0,
|
||||
phase,
|
||||
vault,
|
||||
graph,
|
||||
shards_dir: shardsDir,
|
||||
manifest: manifestPath,
|
||||
started_at: startedAt,
|
||||
updated_at: new Date().toISOString(),
|
||||
elapsed_seconds: elapsed,
|
||||
eta_seconds: eta,
|
||||
total_jobs: jobs.length,
|
||||
completed_jobs: completed,
|
||||
remaining_jobs: remaining,
|
||||
skipped_jobs: skipped.length,
|
||||
skipped_completed_jobs: skipped.length,
|
||||
resumed: Boolean(resume && (hadManifest || skipped.length > 0)),
|
||||
active_jobs: [...active.values()].map(j => ({ name: j.name, start: j.start, limit: j.limit })),
|
||||
failed_jobs: failed.map(j => ({ name: j.name, code: j.code, log: j.log }))
|
||||
}, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
await writeProgress(jobs.length ? 'running' : 'done')
|
||||
|
||||
async function worker(slot) {
|
||||
while (next < jobs.length) {
|
||||
const job = jobs[next++]
|
||||
if (await completedJob(job)) {
|
||||
skipped.push(job)
|
||||
done.push({ ...job, code: 0, skipped: true })
|
||||
process.stderr.write(`[swarm:${slot}] skip ${job.name} (resume)\n`)
|
||||
await writeProgress('running')
|
||||
continue
|
||||
}
|
||||
await fs.writeFile(job.shardGraph, '{"nodes":[],"links":[]}\n', 'utf8')
|
||||
active.set(job.name, job)
|
||||
process.stderr.write(`[swarm:${slot}] start ${job.name}\n`)
|
||||
await writeProgress('running')
|
||||
const result = await runWorker({ ...job, graph: job.shardGraph })
|
||||
active.delete(job.name)
|
||||
done.push(result)
|
||||
if (result.code === 0) {
|
||||
await fs.writeFile(job.done, `${JSON.stringify({
|
||||
name: job.name,
|
||||
signature: job.signature,
|
||||
graph: job.shardGraph,
|
||||
log: job.log,
|
||||
finished_at: new Date().toISOString()
|
||||
}, null, 2)}\n`, 'utf8')
|
||||
}
|
||||
process.stderr.write(`[swarm:${slot}] done ${job.name} code=${result.code}\n`)
|
||||
await writeProgress('running')
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(concurrency, jobs.length) }, (_, i) => worker(i + 1)))
|
||||
@@ -144,17 +234,26 @@ async function main() {
|
||||
graph,
|
||||
shards_dir: shardsDir,
|
||||
manifest: manifestPath,
|
||||
progress: progressPath,
|
||||
total,
|
||||
selected: limit,
|
||||
selected,
|
||||
start,
|
||||
chunk_size: chunkSize,
|
||||
batch_size: batchSize,
|
||||
excerpt_chars: excerptChars,
|
||||
max_tokens: maxTokens,
|
||||
backend: backend || null,
|
||||
model: model || null,
|
||||
cache_dir: cacheDir,
|
||||
cache,
|
||||
resume,
|
||||
resumed: Boolean(resume && (hadManifest || skipped.length > 0)),
|
||||
concurrency,
|
||||
completed: done.length,
|
||||
skipped: skipped.length,
|
||||
failed: failed.map(j => ({ name: j.name, start: j.start, limit: j.limit, log: j.log }))
|
||||
}, null, 2))
|
||||
await writeProgress(failed.length ? 'failed' : 'done')
|
||||
if (failed.length) process.exit(1)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
#!/usr/bin/env node
|
||||
// Одна правда (план П11, метод-правило 8). Ловит СОДЕРЖАТЕЛЬНЫЙ дубль, а не различие хешей.
|
||||
//
|
||||
// - CLAUDE.md/AGENTS.md: одна обязана быть указателем (симлинк или ≤5 строк, называющие
|
||||
// другую), другая — каноном. Требование черновика «sha256(A)!=sha256(B)→1» ПЕРЕВЁРНУТО:
|
||||
// оно закрепляло дубль. П05 сделал указателем CLAUDE.md (канон — AGENTS.md); прибор
|
||||
// распознаёт указатель в любую сторону. Оба указателя / канон схлопнулся / нет указателя → 1.
|
||||
// - enum SPEC_TYPES (mnemazine-note-spec.mjs) сходится с таблицей docs/NOTE-SPEC.md и с любой
|
||||
// второй литеральной копией; расхождение → 1.
|
||||
// - knowledge-note, встреченный в приёмке или человеческом гейте при отсутствии в SPEC_TYPES → 1.
|
||||
// - две одноимённые функции strictKnowledgeReady с разным телом → 1.
|
||||
//
|
||||
// Коды: 0 — одна правда; 1 — дубль/расхождение; 2 — ноль сравнённых пар.
|
||||
|
||||
import { existsSync, readFileSync, lstatSync, readlinkSync, readdirSync } from 'node:fs'
|
||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { SPEC_TYPES } from './mnemazine-note-spec.mjs'
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const RUNNERS_WITH_FILE_ARG = new Set(['node', 'bash', 'sh', 'python', 'python3'])
|
||||
const REPO_FILE_PREFIXES = ['scripts/', 'tests/', 'workflows/', 'skills/']
|
||||
const PACKAGE_SCRIPT_FILE_EXCEPTIONS = [
|
||||
// { target: 'имя-цели', path: 'generated/file', reason: 'почему файл не отслеживается' }
|
||||
]
|
||||
|
||||
function readSafe(p) { try { return readFileSync(p, 'utf8') } catch { return '' } }
|
||||
|
||||
// Указатель: симлинк (цель — по readlink) либо ≤5 непустых строк, называющие .md-файл.
|
||||
function pointerTarget(absPath, text) {
|
||||
try { if (lstatSync(absPath).isSymbolicLink()) return path.basename(readlinkSync(absPath)) } catch {}
|
||||
const nonEmpty = String(text).split(/\r?\n/).filter(l => l.trim())
|
||||
if (nonEmpty.length <= 5) {
|
||||
const m = String(text).match(/([A-Za-z0-9._-]+\.md)/)
|
||||
return m ? m[1] : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// {ok, reason}. ok=true когда ровно одна — указатель на другую, вторая — канон.
|
||||
function evaluatePair(claudePath, agentsPath) {
|
||||
const cText = readSafe(claudePath)
|
||||
const aText = readSafe(agentsPath)
|
||||
if (!cText && !aText) return { present: false }
|
||||
const cTarget = pointerTarget(claudePath, cText)
|
||||
const aTarget = pointerTarget(agentsPath, aText)
|
||||
const cIsPtr = cTarget !== null
|
||||
const aIsPtr = aTarget !== null
|
||||
if (cIsPtr && !aIsPtr && cTarget === path.basename(agentsPath)) return { present: true, ok: true }
|
||||
if (aIsPtr && !cIsPtr && aTarget === path.basename(claudePath)) return { present: true, ok: true }
|
||||
return {
|
||||
present: true,
|
||||
ok: false,
|
||||
reason: `нет валидного указателя CLAUDE.md↔AGENTS.md: одна должна быть указателем (≤5 строк/симлинк на другую), другая — каноном (ptr C→${cTarget}, ptr A→${aTarget})`
|
||||
}
|
||||
}
|
||||
|
||||
function parseNoteSpecTypes() {
|
||||
const p = path.join(ROOT, 'docs', 'NOTE-SPEC.md')
|
||||
if (!existsSync(p)) return null
|
||||
const types = []
|
||||
for (const line of readFileSync(p, 'utf8').split(/\r?\n/)) {
|
||||
const m = line.match(/^\|\s*`([a-z][a-z-]*)`\s*\|/)
|
||||
if (m) types.push(m[1])
|
||||
}
|
||||
return types.length ? new Set(types) : null
|
||||
}
|
||||
|
||||
function setsEqual(a, b) {
|
||||
if (a.size !== b.size) return false
|
||||
for (const x of a) if (!b.has(x)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
function scriptFiles() {
|
||||
return readdirSync(path.join(ROOT, 'scripts'))
|
||||
.filter(f => f.endsWith('.mjs'))
|
||||
.map(f => path.join('scripts', f))
|
||||
}
|
||||
|
||||
function secondEnumLiteralMismatch() {
|
||||
const failures = []
|
||||
for (const rel of scriptFiles()) {
|
||||
if (rel.endsWith('mnemazine-note-spec.mjs')) continue
|
||||
const text = readFileSync(path.join(ROOT, rel), 'utf8')
|
||||
const m = text.match(/SPEC_TYPES\s*=\s*new Set\(\[([^\]]*)\]/)
|
||||
if (!m) continue
|
||||
const members = new Set(m[1].split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean))
|
||||
if (!setsEqual(members, SPEC_TYPES)) failures.push(`вторая литеральная копия SPEC_TYPES в ${rel} расходится с mnemazine-note-spec.mjs`)
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
function knowledgeNoteLeak() {
|
||||
const failures = []
|
||||
if (SPEC_TYPES.has('knowledge-note')) return failures
|
||||
for (const rel of ['scripts/mnemazine-release-check.mjs', 'scripts/mnemazine-human-layer-gate.mjs']) {
|
||||
const p = path.join(ROOT, rel)
|
||||
if (existsSync(p) && readFileSync(p, 'utf8').includes('knowledge-note')) {
|
||||
failures.push(`тип knowledge-note защищается в ${rel}, но отсутствует в SPEC_TYPES`)
|
||||
}
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
function extractFunctionBody(text, startIdx) {
|
||||
const open = text.indexOf('{', startIdx)
|
||||
if (open === -1) return ''
|
||||
let depth = 0
|
||||
for (let i = open; i < text.length; i++) {
|
||||
if (text[i] === '{') depth++
|
||||
else if (text[i] === '}') { depth--; if (depth === 0) return text.slice(open + 1, i) }
|
||||
}
|
||||
return text.slice(open + 1)
|
||||
}
|
||||
|
||||
function strictKnowledgeReadyDivergence() {
|
||||
const defs = []
|
||||
for (const rel of scriptFiles()) {
|
||||
const text = readFileSync(path.join(ROOT, rel), 'utf8')
|
||||
const m = text.match(/(?:export\s+)?function\s+strictKnowledgeReady\b|const\s+strictKnowledgeReady\s*=/)
|
||||
if (m) defs.push({ rel, body: extractFunctionBody(text, m.index).replace(/\s+/g, ' ').trim() })
|
||||
}
|
||||
if (defs.length <= 1) return []
|
||||
const distinct = new Set(defs.map(d => d.body))
|
||||
if (distinct.size > 1) return [`strictKnowledgeReady определена в ${defs.length} местах с разным телом: ${defs.map(d => d.rel).join(', ')}`]
|
||||
return []
|
||||
}
|
||||
|
||||
function shTokens(command) {
|
||||
const tokens = []
|
||||
const re = /"([^"\\]*(?:\\.[^"\\]*)*)"|'([^']*)'|[^\s]+/g
|
||||
for (const m of String(command).matchAll(re)) tokens.push(m[1] ?? m[2] ?? m[0])
|
||||
return tokens
|
||||
}
|
||||
|
||||
function normalizeRepoPath(token) {
|
||||
let rel = String(token).replace(/^\.\/+/, '')
|
||||
if (!rel || rel.startsWith('-') || path.isAbsolute(rel) || /[*?[\]{}$`]/.test(rel)) return null
|
||||
rel = path.posix.normalize(rel)
|
||||
if (rel === '.' || rel.startsWith('../') || rel.includes('/../')) return null
|
||||
return rel
|
||||
}
|
||||
|
||||
function looksLikeRepoFileArg(token) {
|
||||
const rel = normalizeRepoPath(token)
|
||||
if (!rel) return null
|
||||
if (REPO_FILE_PREFIXES.some(prefix => rel.startsWith(prefix))) return rel
|
||||
if (!rel.includes('/') && /\.(?:sh|mjs|js|cjs|py)$/.test(rel)) return rel
|
||||
return null
|
||||
}
|
||||
|
||||
function packageScriptFileRefs(scripts) {
|
||||
const refs = []
|
||||
for (const [target, command] of Object.entries(scripts || {})) {
|
||||
const tokens = shTokens(command)
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const runner = path.basename(tokens[i])
|
||||
if (!RUNNERS_WITH_FILE_ARG.has(runner)) continue
|
||||
for (let j = i + 1; j < tokens.length; j++) {
|
||||
const token = tokens[j]
|
||||
if (/^(?:&&|\|\||;|\|)$/.test(token)) break
|
||||
if (token.startsWith('-')) continue
|
||||
const rel = looksLikeRepoFileArg(token)
|
||||
if (rel) refs.push({ target, path: rel })
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return refs
|
||||
}
|
||||
|
||||
function packageScriptExceptionSet() {
|
||||
const failures = []
|
||||
const allowed = new Set()
|
||||
for (const e of PACKAGE_SCRIPT_FILE_EXCEPTIONS) {
|
||||
if (!e?.target || !e?.path || !e?.reason) {
|
||||
failures.push('PACKAGE_SCRIPT_FILE_EXCEPTIONS: каждая строка обязана иметь target, path, reason')
|
||||
continue
|
||||
}
|
||||
allowed.add(`${e.target}\0${normalizeRepoPath(e.path)}`)
|
||||
}
|
||||
return { failures, allowed }
|
||||
}
|
||||
|
||||
function packageScriptTrackedPathFailures(scripts, tracked, fileExists = rel => existsSync(path.join(ROOT, rel))) {
|
||||
const { failures, allowed } = packageScriptExceptionSet()
|
||||
for (const ref of packageScriptFileRefs(scripts)) {
|
||||
if (allowed.has(`${ref.target}\0${ref.path}`)) continue
|
||||
if (!tracked.has(ref.path)) failures.push(`package.json:${ref.target} → ${ref.path}: файл не в git ls-files`)
|
||||
else if (!fileExists(ref.path)) failures.push(`package.json:${ref.target} → ${ref.path}: файл отслеживается, но отсутствует на диске`)
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
function gitTrackedFiles() {
|
||||
return new Set(execFileSync('git', ['ls-files', '-z'], { cwd: ROOT, encoding: 'utf8' }).split('\0').filter(Boolean))
|
||||
}
|
||||
|
||||
function packageScriptTrackedPathCheck() {
|
||||
const p = path.join(ROOT, 'package.json')
|
||||
if (!existsSync(p)) return ['package.json отсутствует']
|
||||
const pkg = JSON.parse(readFileSync(p, 'utf8'))
|
||||
return packageScriptTrackedPathFailures(pkg.scripts || {}, gitTrackedFiles())
|
||||
}
|
||||
|
||||
function evaluate() {
|
||||
const failures = []
|
||||
let pairs = 0 // число сравнённых категорий (не число провалов)
|
||||
|
||||
const pair = evaluatePair(path.join(ROOT, 'CLAUDE.md'), path.join(ROOT, 'AGENTS.md'))
|
||||
if (pair.present) { pairs++; if (!pair.ok) failures.push(pair.reason) }
|
||||
|
||||
const docTypes = parseNoteSpecTypes()
|
||||
if (docTypes) { pairs++; if (!setsEqual(docTypes, SPEC_TYPES)) failures.push(`SPEC_TYPES ${[...SPEC_TYPES].sort().join(',')} != таблица NOTE-SPEC ${[...docTypes].sort().join(',')}`) }
|
||||
|
||||
pairs++; failures.push(...secondEnumLiteralMismatch())
|
||||
pairs++; failures.push(...knowledgeNoteLeak())
|
||||
pairs++; failures.push(...strictKnowledgeReadyDivergence())
|
||||
pairs++; failures.push(...packageScriptTrackedPathCheck())
|
||||
|
||||
if (pairs === 0) return { code: 2, failures: ['ноль сравнённых пар'] }
|
||||
return { code: failures.length ? 1 : 0, failures, pairs }
|
||||
}
|
||||
|
||||
function selftest() {
|
||||
const tmp = mkdtempSync(path.join(os.tmpdir(), 'single-truth-selftest-'))
|
||||
try {
|
||||
const body = '# Canon\n\n' + Array.from({ length: 10 }, (_, i) => `Rule line ${i} with real content.`).join('\n') + '\n'
|
||||
writeFileSync(path.join(tmp, 'CLAUDE.md'), body, 'utf8')
|
||||
writeFileSync(path.join(tmp, 'AGENTS.md'), body, 'utf8')
|
||||
const pair = evaluatePair(path.join(tmp, 'CLAUDE.md'), path.join(tmp, 'AGENTS.md'))
|
||||
if (pair.ok) { console.error('selftest FAILED: два одинаковых канона прошли зелёным'); return 1 }
|
||||
const failures = packageScriptTrackedPathFailures({
|
||||
'graph:clean': 'python3 scripts/graphify_clean.py',
|
||||
'combo': 'node scripts/ok.mjs && bash install.sh',
|
||||
'delegated': 'npm run release-check'
|
||||
}, new Set(['scripts/ok.mjs', 'install.sh']), rel => rel !== 'scripts/graphify_clean.py')
|
||||
if (!failures.some(f => f.includes('graph:clean') && f.includes('scripts/graphify_clean.py'))) {
|
||||
console.error('selftest FAILED: неотслеживаемая цель package.json не покраснела')
|
||||
return 1
|
||||
}
|
||||
if (failures.some(f => f.includes('combo') || f.includes('delegated'))) {
|
||||
console.error('selftest FAILED: валидная или npm-делегированная цель покраснела')
|
||||
return 1
|
||||
}
|
||||
console.log('selftest ok: содержательный дубль CLAUDE/AGENTS краснит')
|
||||
console.log('selftest ok: package.json file targets должны быть tracked')
|
||||
return 0
|
||||
} finally {
|
||||
rmSync(tmp, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function main() {
|
||||
const argv = process.argv.slice(2)
|
||||
if (argv.includes('--selftest')) process.exit(selftest())
|
||||
const r = evaluate()
|
||||
if (r.failures?.length) {
|
||||
console.error('ПРОВАЛЫ:')
|
||||
for (const f of r.failures) console.error(` - ${f}`)
|
||||
} else {
|
||||
console.log(`одна правда: сравнено пар ${r.pairs}, расхождений нет`)
|
||||
}
|
||||
process.exit(r.code)
|
||||
}
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env node
|
||||
// Потолок провалов спеки (план П16, шаг 8): .mnemazine/state/spec-ceiling.json
|
||||
// переписывается ТОЛЬКО ВНИЗ и ТОЛЬКО ЭТИМ КОДОМ. Рост провалов — отказ (exit 1),
|
||||
// ручная правка файла задетектится сверкой sha256 гейта и checked.
|
||||
//
|
||||
// node scripts/mnemazine-spec-ceiling.mjs --update прогнать гейт и опустить потолок, если провалов стало меньше
|
||||
// node scripts/mnemazine-spec-ceiling.mjs --check сверить: текущие провалы не выше потолка (exit 0/1)
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import path from 'node:path'
|
||||
import crypto from 'node:crypto'
|
||||
import { resolveVault, ROOT } from './mnemazine-paths.mjs'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const UPDATE = argv.includes('--update')
|
||||
const CHECK = argv.includes('--check')
|
||||
if (!UPDATE && !CHECK) {
|
||||
console.error('нужен --update или --check')
|
||||
process.exit(2)
|
||||
}
|
||||
function arg(name) {
|
||||
const flag = `--${name}`
|
||||
const index = argv.findIndex(a => a === flag || a.startsWith(`${flag}=`))
|
||||
if (index === -1) return ''
|
||||
return argv[index].includes('=') ? argv[index].slice(flag.length + 1) : argv[index + 1] || ''
|
||||
}
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const CEILING_PATH = arg('ceiling') ? path.resolve(arg('ceiling')) : path.join(ROOT, '.mnemazine', 'state', 'spec-ceiling.json')
|
||||
const GATE = path.join(ROOT, 'scripts', 'mnemazine-vault-quality-gate.mjs')
|
||||
|
||||
async function runGate() {
|
||||
// JSON уходит в stderr при провалах; код 1 при провалах — ожидаем.
|
||||
// Через pipe гейт режет свой JSON: console.error в pipe асинхронен, а process.exit(1)
|
||||
// сразу за ним обрывает поток (замерено: ровно 48898 байт). В файл stderr синхронен —
|
||||
// поэтому пишем во временный файл редиректом, а не читаем pipe.
|
||||
const tmp = path.join(ROOT, '.mnemazine', 'state', '.spec-ceiling-gate.json')
|
||||
execFileSync('bash', ['-c', `node "$1" --spec --json --max-failures=0 > "$2" 2>&1 || true`, '_', GATE, tmp], {
|
||||
env: { ...process.env, MNEMAZINE_VAULT: VAULT, LC_ALL: 'C' },
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
const out = await fs.readFile(tmp, 'utf8')
|
||||
const start = out.indexOf('{')
|
||||
if (start === -1) throw new Error(`гейт не вернул JSON: ${out.slice(0, 200)}`)
|
||||
return JSON.parse(out.slice(start))
|
||||
}
|
||||
|
||||
const report = await runGate()
|
||||
const failures = report.failures.length
|
||||
const checked = report.checked
|
||||
let ceiling = null
|
||||
try { ceiling = JSON.parse(await fs.readFile(CEILING_PATH, 'utf8')) } catch { /* первый съём */ }
|
||||
|
||||
if (CHECK) {
|
||||
if (!ceiling) {
|
||||
console.error('потолок не снят — сравнивать не с чем')
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`сейчас ${failures} провалов, потолок ${ceiling.ceiling}`)
|
||||
process.exit(failures <= ceiling.ceiling ? 0 : 1)
|
||||
}
|
||||
|
||||
const sha256 = crypto.createHash('sha256').update(await fs.readFile(GATE)).digest('hex')
|
||||
if (ceiling && failures >= ceiling.ceiling) {
|
||||
console.error(`ОТКАЗ: провалов ${failures} не меньше потолка ${ceiling.ceiling} — потолок НЕ переписан (только вниз)`)
|
||||
process.exit(1)
|
||||
}
|
||||
const next = { vault: VAULT, checked, ceiling: failures, recorded_at: new Date().toISOString(), sha256_of_gate: sha256 }
|
||||
await fs.mkdir(path.dirname(CEILING_PATH), { recursive: true })
|
||||
await fs.writeFile(CEILING_PATH, JSON.stringify(next, null, 2) + '\n')
|
||||
console.log(`потолок опущен: ${ceiling ? ceiling.ceiling : '—'} → ${failures} (checked ${checked})`)
|
||||
@@ -1,9 +1,10 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { promises as fs, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import crypto from 'node:crypto'
|
||||
import { llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
|
||||
import { activeProvider, llmAvailable, llmJson, fenceUntrusted, providerCostTier } from './mnemazine-llm.mjs'
|
||||
import { verifyLocal, verifyDeep, isPublicHttpUrl } from './mnemazine-verify.mjs'
|
||||
import { SPEC_VERIFIED } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
@@ -24,12 +25,22 @@ const MIN_CLUSTER_CHARS = Number(arg('min-cluster-chars', '80'))
|
||||
// and never needs codex. Flag also honoured via MNEMAZINE_DEEP=1.
|
||||
const DEEP = argv.includes('--deep') || argv.includes('--atomize') || process.env.MNEMAZINE_DEEP === '1'
|
||||
const MAX_ATOMS = Number(arg('max-atoms', process.env.MNEMAZINE_MAX_ATOMS || '20'))
|
||||
// Long material (video transcripts, books) was silently cut to the first 4000
|
||||
// chars per record, so atoms only ever covered the intro. Knobs, defaults kept.
|
||||
const MAX_RECORD_CHARS = Number(process.env.MNEMAZINE_MAX_RECORD_CHARS || '4000')
|
||||
const MAX_MATERIAL_CHARS = Number(process.env.MNEMAZINE_MAX_MATERIAL_CHARS || '24000')
|
||||
// Enrichment is on within --deep unless explicitly disabled (it needs the network).
|
||||
const ENRICH = DEEP && process.env.MNEMAZINE_ENRICH !== '0' && !argv.includes('--no-enrich')
|
||||
const ENRICH_TIMEOUT_MS = Number(process.env.MNEMAZINE_ENRICH_TIMEOUT_MS || '60000')
|
||||
// Enrichment web calls can be slow; default to the generous ceiling for any
|
||||
// provider (env overrides). No branch on a CLI name — a longer timeout never
|
||||
// harms a faster CLI.
|
||||
const ENRICH_TIMEOUT_MS = Number(process.env.MNEMAZINE_ENRICH_TIMEOUT_MS || '420000')
|
||||
const STRICT_ENRICH = DEEP && process.env.MNEMAZINE_STRICT_ENRICH !== '0' && !argv.includes('--allow-raw-atomize')
|
||||
const MIN_ADDED_FACTS = Number(process.env.MNEMAZINE_MIN_ADDED_FACTS || '2')
|
||||
const CLUSTER_CHUNK_SIZE = Number(arg('cluster-chunk-size', process.env.MNEMAZINE_CLUSTER_CHUNK_SIZE || '25'))
|
||||
const ATOMIZER_PROVIDER = process.env.MNEMAZINE_ATOMIZER_LLM || process.env.MNEMAZINE_LLM || undefined
|
||||
const VERIFIER_PROVIDER = process.env.MNEMAZINE_VERIFIER_LLM || process.env.MNEMAZINE_LLM || undefined
|
||||
const RESOLVED_ATOMIZER_PROVIDER = activeProvider({ provider: ATOMIZER_PROVIDER })
|
||||
const SOURCE_REF_FILTER = new Set(String(process.env.MNEMAZINE_SYNTH_SOURCE_REFS || '')
|
||||
.split(',')
|
||||
.map(s => s.trim())
|
||||
@@ -51,6 +62,9 @@ const sourceHints = [
|
||||
{ re: /terraform|pulumi|infrastructure|iac/i, name: 'Terraform docs', url: 'https://developer.hashicorp.com/terraform/docs' },
|
||||
{ re: /bff|backend for frontend/i, name: 'Backends for Frontends pattern', url: 'https://learn.microsoft.com/en-us/azure/architecture/patterns/backends-for-frontends' },
|
||||
{ re: /worktree|git stash/i, name: 'git worktree docs', url: 'https://git-scm.com/docs/git-worktree' },
|
||||
{ re: /стартап|фаундер|основател|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber|клиент/i, name: "Paul Graham Do Things That Don't Scale", url: 'https://www.paulgraham.com/ds.html' },
|
||||
{ re: /стартап|фаундер|основател|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber|клиент/i, name: 'Sam Altman Startup Playbook', url: 'https://playbook.samaltman.com/' },
|
||||
{ re: /стартап|фаундер|основател|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber|клиент/i, name: 'Y Combinator Startup Playbook', url: 'https://www.ycombinator.com/blog/startup-playbook/' },
|
||||
{ re: /moneyprinter|short-form|reels|tiktok|youtube shorts/i, name: 'MoneyPrinterTurbo', url: 'https://github.com/harry0703/MoneyPrinterTurbo' }
|
||||
]
|
||||
|
||||
@@ -61,6 +75,7 @@ const clusterRules = [
|
||||
{ id: 'engineering-ops', title: 'Engineering operations and reproducible delivery', re: /observability|terraform|pulumi|worktree|staging|environment|deploy|bff|backend/i },
|
||||
{ id: 'design-frontend', title: 'Design systems and frontend quality', re: /design|frontend|ui|component|playwright|browser|layout|wcag/i },
|
||||
{ id: 'tool-radar', title: 'Open-source tool radar and selection', re: /github\.com|open source|langflow|dify|open-webui|openhands|crawl4ai|coolify|papermark|twenty|crowdsec/i },
|
||||
{ id: 'startup-strategy', title: 'Startup strategy and founder-led growth', re: /стартап|фаундер|основател|корпораци|гигант|голодн|узк(?:ая|ой|ую|ом)\s+ниш|mvp|партизан|голиаф|airbnb|uber/i },
|
||||
{ id: 'content-growth', title: 'Content experiments and growth loops', re: /ad |ads|hook|cta|offer|short-form|reels|tiktok|youtube|content|moneyprinter/i },
|
||||
{ id: 'research-workflow', title: 'Research workflow and source verification', re: /research|source|citation|academic|verify|evidence/i }
|
||||
]
|
||||
@@ -102,6 +117,12 @@ const topicTemplates = {
|
||||
how: '- Score tools by fit, maturity, license, API, self-hosting, and operational burden.\n- Tie tools to concrete projects.\n- Re-check source repositories before adopting.',
|
||||
next: 'Сделать schema для tool-radar и заполнять её из извлечённых GitHub-ссылок.'
|
||||
},
|
||||
'startup-strategy': {
|
||||
what: 'Startup strategy is the operating pattern for small teams beating larger incumbents: narrow focus, fast customer feedback, founder-led trust, and manual work before scale.',
|
||||
why: 'The captured carousel is useful only if it becomes a reusable decision rule, not motivational noise.',
|
||||
how: '- Pick a narrow ignored segment.\n- Talk to customers directly.\n- Ship small changes faster than incumbents can route approvals.\n- Treat manual founder service as learning, not as permanent process.',
|
||||
next: 'Привязать startup strategy к ближайшему проекту: ниша, скорость, founder-led trust, ручной сервис.'
|
||||
},
|
||||
'content-growth': {
|
||||
what: 'Content growth loops treat ads, hooks, CTAs, short-form scripts, and publishing as experiments with feedback.',
|
||||
why: 'One generated video or ad is not learning. Learning appears when variants, metric, result, and next control are stored.',
|
||||
@@ -159,6 +180,12 @@ const topicTemplatesRu = {
|
||||
how: ['Оценивать fit, maturity, license, API, self-hosting и operational burden.', 'Связывать инструмент с конкретным проектом.', 'Перед adoption перепроверять primary source.'],
|
||||
next: 'Сделать schema для tool-radar и заполнять её из GitHub links.'
|
||||
},
|
||||
'startup-strategy': {
|
||||
what: 'Startup strategy - это набор ходов, где маленькая команда обходит крупного игрока не бюджетом, а узкой нишей, скоростью, прямым контактом с клиентом и founder-led доверием.',
|
||||
why: 'Такие карточки легко превращаются в мотивационный шум. Польза появляется, когда из них выходит конкретное правило для проекта: кого выбрать, что урезать, как быстро проверить и где основатель должен говорить лично.',
|
||||
how: ['Выбрать один узкий сегмент, который крупный игрок игнорирует.', 'Не копировать весь продукт корпорации, а закрыть одну боль лучше.', 'Собирать обратную связь напрямую от клиентов.', 'Выкатывать маленькие изменения быстрее корпоративного цикла согласований.', 'Ручной сервис основателя использовать как обучение, а не как вечный процесс.'],
|
||||
next: 'Привязать startup strategy к ближайшему проекту: ниша, скорость, founder-led trust, ручной сервис.'
|
||||
},
|
||||
'content-growth': {
|
||||
what: 'Контентные петли роста рассматривают ads, hooks, CTA, scripts и публикации как эксперименты с обратной связью.',
|
||||
why: 'Один ролик или объявление ещё не обучение. Обучение появляется, когда есть variant, metric, result и next control.',
|
||||
@@ -254,6 +281,7 @@ function clusterTitleRu(id) {
|
||||
'engineering-ops': 'Инженерные операции и воспроизводимая доставка',
|
||||
'design-frontend': 'Дизайн-системы и качество фронтенда',
|
||||
'tool-radar': 'Радар инструментов и выбор open-source',
|
||||
'startup-strategy': 'Стратегия стартапа и founder-led рост',
|
||||
'content-growth': 'Контентные эксперименты и петли роста',
|
||||
'research-workflow': 'Исследовательский workflow и проверка источников',
|
||||
misc: 'Прочие сигналы знаний'
|
||||
@@ -305,22 +333,54 @@ async function fetchText(url, limit = 40000) {
|
||||
}
|
||||
}
|
||||
|
||||
function looksLikeCode(text) {
|
||||
// JS-heavy pages (YouTube et al) leak `(function() {window.ytplayer={};` and
|
||||
// `ytcfg.set({"KEY":...})` into "external facts". Prose has no braces/arrows
|
||||
// and is mostly letters and spaces.
|
||||
const value = String(text || '')
|
||||
if (/[{}]|=>|\);|\w+\.\w+\(|^\(function/.test(value)) return true
|
||||
const letters = (value.match(/[\p{L}\s.,;:!?()'"-]/gu) || []).length
|
||||
return letters / Math.max(1, value.length) < 0.85
|
||||
}
|
||||
|
||||
function readmePoints(readme, max = 6) {
|
||||
const points = []
|
||||
for (const line of stripHtmlText(readme).split('\n')) {
|
||||
const clean = compact(line.replace(/^#+\s*/, '').replace(/^[-*]\s+/, ''), 220)
|
||||
if (clean.length < 32) continue
|
||||
if (/^[,.;:]/.test(clean) || /^https?:\/\//i.test(clean)) continue
|
||||
if (/^(install|usage|license|contributing|table of contents|badges?)$/i.test(clean)) continue
|
||||
if (/^!\[|^<img|^\[!?\[|^window\.|^document\.|^function\s/i.test(line.trim())) continue
|
||||
if (/\b(src|href|alt|title)=["'][^"']*["']/i.test(clean)) continue
|
||||
if (/https?:\/\/\S+\.(?:svg|png|jpe?g|gif|webp)(?:\?\S*)?$/i.test(clean)) continue
|
||||
if (/<[a-z][\s\S]*>/i.test(clean)) continue
|
||||
if (looksLikeCode(clean)) continue
|
||||
points.push(clean)
|
||||
if (points.length >= max) break
|
||||
}
|
||||
return points
|
||||
}
|
||||
|
||||
function latinCount(text) {
|
||||
return (String(text || '').match(/[A-Za-z]/g) || []).length
|
||||
}
|
||||
|
||||
function cyrillicCount(text) {
|
||||
return (String(text || '').match(/[А-Яа-яЁё]/g) || []).length
|
||||
}
|
||||
|
||||
function russianSourceSignal(text, fallback = 'проверяемый сигнал первоисточника') {
|
||||
const clean = compact(text, 180)
|
||||
if (!clean) return fallback
|
||||
const low = clean.toLowerCase()
|
||||
if (/critical vulnerab|vulnerab/.test(low)) return 'заявленный security-риск marketplace skills'
|
||||
if (/secure|validated|hardened|confidence/.test(low)) return 'позиционирование как проверенный каталог skills'
|
||||
if (/registry|library|catalog/.test(low)) return 'каталог skills и reusable capabilities'
|
||||
if (/agent|skill|claude|cursor|copilot|antigravity/.test(low)) return 'поддержка skills для AI coding agents и IDE'
|
||||
if (latinCount(clean) > Math.max(40, cyrillicCount(clean) * 2)) return fallback
|
||||
return clean
|
||||
}
|
||||
|
||||
function htmlDescription(html) {
|
||||
const raw = String(html || '')
|
||||
const hit = raw.match(/<meta\s+name="description"\s+content="([^"]+)"/i) ||
|
||||
@@ -390,14 +450,16 @@ async function enrichClusterFromGithub(cluster, sources) {
|
||||
const readme = rawReadme.text
|
||||
const release = await fetchJson(`https://api.github.com/repos/${repoRef.owner}/${repoRef.repo}/releases/latest`)
|
||||
const points = readmePoints(readme)
|
||||
const description = russianSourceSignal(api.description, 'англоязычное описание GitHub; точная формулировка сохранена в primary source')
|
||||
const pointSignals = points.map(point => russianSourceSignal(point, 'README-сигнал требует ручной сверки')).filter(Boolean)
|
||||
const license = api.license?.spdx_id || api.license?.name || 'лицензия неизвестна'
|
||||
const pushed = api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'
|
||||
const releaseLine = release?.tag_name ? `${release.tag_name} (${String(release.published_at || '').slice(0, 10) || 'дата неизвестна'})` : 'GitHub API не вернул latest release'
|
||||
const addedFacts = [
|
||||
`${api.full_name}: ${api.description || 'официальный GitHub-репозиторий'}.`,
|
||||
`${api.full_name}: ${description}.`,
|
||||
`Метаданные GitHub: ${api.stargazers_count} звёзд, ${api.forks_count} форков, ${api.open_issues_count} открытых issues, лицензия ${license}, основной язык ${api.language || 'unknown'}.`,
|
||||
`Свежесть репозитория: основная ветка ${api.default_branch || 'unknown'}, последний push ${pushed}, последний release ${releaseLine}.`,
|
||||
...points.slice(0, 5).map(point => `Сигнал README: ${point}`)
|
||||
...pointSignals.slice(0, 5).map(point => `Сигнал README: ${point}.`)
|
||||
]
|
||||
const addedSources = [
|
||||
api.html_url,
|
||||
@@ -406,10 +468,10 @@ async function enrichClusterFromGithub(cluster, sources) {
|
||||
].filter(Boolean)
|
||||
const enriched = [
|
||||
`Расширение по официальному GitHub для ${api.full_name}.`,
|
||||
`Описание: ${api.description || 'GitHub не дал описание.'}`,
|
||||
`Описание: ${description}.`,
|
||||
`Метаданные: ${api.stargazers_count} звёзд, ${api.forks_count} форков, ${api.open_issues_count} открытых issues, ${license}, язык ${api.language || 'unknown'}, последний push ${pushed}.`,
|
||||
`Последний release: ${releaseLine}.`,
|
||||
points.length ? `Из README извлечены стабильные сигналы:\n${points.map(point => `- ${point}`).join('\n')}` : 'README не дал устойчивых feature-пунктов без ручной проверки.',
|
||||
pointSignals.length ? `Из README извлечены рабочие сигналы:\n${pointSignals.map(point => `- ${point}`).join('\n')}` : 'README не дал устойчивых feature-пунктов без ручной проверки.',
|
||||
`Локальные source refs: ${cluster.records.map(r => r.source_ref).join(', ')}.`
|
||||
].join('\n\n')
|
||||
return { enriched, addedSources, addedFacts, github: { api, readmeUrl, release, points } }
|
||||
@@ -450,13 +512,15 @@ function atomsFromGithub(part, sources) {
|
||||
const api = github.api
|
||||
const repo = api.full_name
|
||||
const sourceUrls = [api.html_url, github.readmeUrl, github.release?.html_url].filter(Boolean)
|
||||
const points = github.points || []
|
||||
const points = (github.points || []).map(point => russianSourceSignal(point, 'README-сигнал требует ручной сверки')).filter(Boolean)
|
||||
const license = api.license?.spdx_id || api.license?.name || 'unknown license'
|
||||
const releaseLine = github.release?.tag_name || 'no latest release returned'
|
||||
const description = russianSourceSignal(api.description, 'англоязычное описание GitHub; точная формулировка в primary source')
|
||||
return [
|
||||
{
|
||||
title: `${repo}: проверенная карточка инструмента`,
|
||||
what: `${repo} - официальный GitHub-репозиторий инструмента из inbox. GitHub показывает: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, лицензия ${license}, основной язык ${api.language || 'unknown'}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}.`,
|
||||
source_refs: part.records.map(record => record.source_ref).filter(Boolean),
|
||||
what: `${repo} - официальный GitHub-репозиторий инструмента из inbox. Описание: ${description}. GitHub показывает: ${api.stargazers_count} stars, ${api.forks_count} forks, ${api.open_issues_count} open issues, лицензия ${license}, основной язык ${api.language || 'unknown'}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}.`,
|
||||
why: 'Это превращает скриншот или карточку со звёздами в проверяемую запись: есть primary source, дата свежести, лицензия и базовый риск.',
|
||||
how: ['Сначала смотреть метаданные: лицензия, свежесть, stars, forks, issues.', 'Перед установкой открыть README и issues, скриншот считать только подсказкой.', 'Решение фиксировать отдельно: установить сейчас, протестировать позже или забыть.'],
|
||||
sources: sourceUrls,
|
||||
@@ -464,7 +528,8 @@ function atomsFromGithub(part, sources) {
|
||||
},
|
||||
{
|
||||
title: `${repo}: что реально обещает README`,
|
||||
what: points.length ? points.slice(0, 4).join(' ') : `${repo} имеет официальный README, но Mnemazine не нашла в нём устойчивые продуктовые тезисы без ручной проверки.`,
|
||||
source_refs: part.records.map(record => record.source_ref).filter(Boolean),
|
||||
what: points.length ? `README даёт проверяемые сигналы: ${points.slice(0, 4).join('; ')}.` : `${repo} имеет официальный README, но Mnemazine не нашла в нём устойчивые продуктовые тезисы без ручной проверки.`,
|
||||
why: 'README ближе к рабочей правде, чем подпись на скриншоте. Он показывает, что авторы реально поддерживают и документируют.',
|
||||
how: points.slice(0, 5).map(point => `Проверить по README: ${point}`),
|
||||
sources: sourceUrls,
|
||||
@@ -472,6 +537,7 @@ function atomsFromGithub(part, sources) {
|
||||
},
|
||||
{
|
||||
title: `${repo}: риск эксплуатации и поддержки`,
|
||||
source_refs: part.records.map(record => record.source_ref).filter(Boolean),
|
||||
what: `Поверхность риска: ${api.open_issues_count} open issues, последний release ${releaseLine}, последний push ${api.pushed_at ? api.pushed_at.slice(0, 10) : 'unknown'}, лицензия ${license}.`,
|
||||
why: 'Популярный репозиторий всё равно может быть плохой зависимостью, если релизы, лицензия или issue-профиль не подходят под workflow.',
|
||||
how: ['Проверить issues на security, потерю данных и ошибки установки.', 'Сначала гонять в одноразовом workspace, не добавлять сразу в глобальные правила агента.', 'Если это станет Skill/MCP/plugin, записать source ledger и usage ledger.'],
|
||||
@@ -480,6 +546,7 @@ function atomsFromGithub(part, sources) {
|
||||
},
|
||||
{
|
||||
title: `${repo}: решение для Mnemazine`,
|
||||
source_refs: part.records.map(record => record.source_ref).filter(Boolean),
|
||||
what: `Этот атом связывает локальный захват с primary GitHub evidence по ${repo}. Это не команда установить, а кандидат на разбор.`,
|
||||
why: 'Полезная память - не "увидел репозиторий", а решение: что инструмент делает, подходит ли он, какой риск остаётся и что делать дальше.',
|
||||
how: ['Хранить репозиторий как кандидата в рабочие возможности, не как инструкцию к установке.', 'Если принять, зеркалировать docs/skill metadata и логировать usage.', 'Если отклонить, записать причину, чтобы репозиторий не возвращался шумом.'],
|
||||
@@ -497,6 +564,7 @@ function atomsFromSources(part, sources) {
|
||||
return [
|
||||
{
|
||||
title: `${clusterTitleRu(part.id)}: проверенный рабочий паттерн`,
|
||||
source_refs: part.records.map(record => record.source_ref).filter(Boolean),
|
||||
what: `${template.what} Источники добавили проверяемые опорные факты: ${facts.slice(0, 2).join(' ')}`,
|
||||
why: template.why,
|
||||
how: [...how, ...facts.slice(2, 4).map(fact => `Проверить по источнику: ${fact}`)].slice(0, 5),
|
||||
@@ -535,6 +603,7 @@ function topicSignals(cluster, sources) {
|
||||
'engineering-ops': ['Повторяются инженерные сигналы: воспроизводимые окружения, IaC, worktrees, observability, release checks и secret injection.', sourceLine],
|
||||
'design-frontend': ['Повторяются UI-сигналы: DESIGN.md, taste rules, frontend structure, Playwright/browser checks и WCAG constraints.', sourceLine],
|
||||
'tool-radar': ['Повторяются tool-radar сигналы: GitHub repos, self-hosting, AI tools и open-source alternatives.', sourceLine],
|
||||
'startup-strategy': ['Повторяются startup-сигналы: узкая ниша, скорость внедрения, прямой контакт с клиентом, founder-led доверие и ручной сервис до scale.', sourceLine],
|
||||
'content-growth': ['Повторяются growth-сигналы: ad variants, hooks, CTA, short-form generation, metrics и winner/loser loops.', sourceLine],
|
||||
'research-workflow': ['Повторяются research-сигналы: сбор источников, проверка claims, evidence, drafting и revision.', sourceLine],
|
||||
misc: ['Слабые misc-сигналы отделены от сильных knowledge atoms.', sourceLine]
|
||||
@@ -589,10 +658,12 @@ function makeNote(cluster) {
|
||||
: 'Публичного источника в extraction не было; это локальный memory atom, а не внешне подтверждённый claim.'
|
||||
return `---
|
||||
title: "${title.replace(/"/g, '\\"')}"
|
||||
type: "knowledge-note"
|
||||
type: "synthesis"
|
||||
subject: world
|
||||
source_type: "synthesis-cluster"
|
||||
source: "session:${SESSION}/${cluster.id}"
|
||||
source_ref: "session:${SESSION}/${cluster.id}"
|
||||
verified: false
|
||||
verified: ${specVerified(localVerdict.status)}
|
||||
verification_status: "${localVerdict.status}"
|
||||
verification: "${sourceStatus}"
|
||||
status: "draft"
|
||||
@@ -628,7 +699,12 @@ ${sourceRefs.length > 30 ? `- ... ещё ${sourceRefs.length - 30} source refs
|
||||
Публичные источники:
|
||||
${sourceLines.join('\n')}
|
||||
|
||||
## Проверка
|
||||
## 🎯 Как это поможет мне
|
||||
|
||||
- ${template.next}
|
||||
- Тема: ${clusterTitleRu(cluster.id)} — черновик собран, но требует проверки перед применением.
|
||||
|
||||
## Достоверность
|
||||
|
||||
- **Автоматический fact-check не запускался.** Это unverified synthesis cluster (\`status: draft\`). URL из extraction или topic hints - указатели, не подтверждение конкретного claim.
|
||||
- Повышать до \`status: final\` только после проверки человеком или verify gate по primary sources.
|
||||
@@ -638,7 +714,7 @@ ${sourceLines.join('\n')}
|
||||
## Связанные заметки
|
||||
|
||||
- [[Mnemazine Protocol]]
|
||||
- [[${clusterTitle(cluster.id)}]]
|
||||
- [[${clusterTitleRu(cluster.id)}]]
|
||||
|
||||
## Следующее действие
|
||||
|
||||
@@ -656,35 +732,56 @@ const ATOM_SCHEMA = {
|
||||
items: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['title', 'what', 'why', 'how', 'next', 'sources'],
|
||||
required: ['title', 'what', 'why', 'how', 'next', 'sources', 'source_refs'],
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
what: { type: 'string' },
|
||||
why: { type: 'string' },
|
||||
how: { type: 'array', items: { type: 'string' } },
|
||||
next: { type: 'string' },
|
||||
sources: { type: 'array', items: { type: 'string' } }
|
||||
sources: { type: 'array', items: { type: 'string' } },
|
||||
source_refs: { type: 'array', items: { type: 'string' } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Owner projects come from the vault (99 Система/_ПРОЕКТЫ.md), never hardcoded —
|
||||
// the spec gate rejects a "как это поможет мне" block that names no real project.
|
||||
let OWNER_PROJECTS = null
|
||||
function ownerProjects() {
|
||||
if (OWNER_PROJECTS) return OWNER_PROJECTS
|
||||
try {
|
||||
const text = readFileSync(path.join(VAULT, '99 Система', '_ПРОЕКТЫ.md'), 'utf8')
|
||||
OWNER_PROJECTS = [...text.matchAll(/^##\s+(.+?)\s*$/gm)].map(m => m[1]).filter(Boolean)
|
||||
} catch { OWNER_PROJECTS = [] }
|
||||
return OWNER_PROJECTS
|
||||
}
|
||||
|
||||
function atomPrompt(cluster, sources, materialOverride) {
|
||||
// When enrichment ran, atomize the EXPANDED knowledge; else the raw capture.
|
||||
const text = materialOverride
|
||||
? String(materialOverride).slice(0, 28000)
|
||||
: cluster.records.map(r => compact(r.text, 4000)).join('\n---\n').slice(0, 24000)
|
||||
? String(materialOverride).slice(0, Math.max(28000, MAX_MATERIAL_CHARS))
|
||||
: cluster.records.map(r => `SOURCE_REF: ${r.source_ref}\n${compact(r.text, MAX_RECORD_CHARS)}`).join('\n---\n').slice(0, MAX_MATERIAL_CHARS)
|
||||
const urls = sources.map(s => s.url).join(', ') || 'none detected'
|
||||
return `You are Mnemazine's atomization agent. Split the enriched research material below into FOCUSED, atomic knowledge notes — one idea per atom, up to ${MAX_ATOMS}. Do NOT merge unrelated ideas; do NOT invent facts not present in the material. Each atom: a precise title, a one-paragraph "what", a one-paragraph "why it matters", 2-5 concrete "how to use" bullets, one "next action", and the subset of source URLs that support it (from: ${urls}; [] only if truly local/private).
|
||||
const refs = cluster.records.map(r => r.source_ref).filter(Boolean).join(', ')
|
||||
return `You are Mnemazine's atomization agent. Split the enriched research material below into FOCUSED, atomic knowledge notes — one idea per atom, up to ${MAX_ATOMS}. Do NOT merge unrelated ideas; do NOT invent facts not present in the material. Each atom: a precise title, a one-paragraph "what", a one-paragraph "why it matters", 2-5 concrete "how to use" bullets, one "next action", the subset of source URLs that support it (from: ${urls}; [] only if truly local/private), and the subset of local source_refs that support this exact atom (from: ${refs}; never include an unrelated source_ref just because it is in the same cluster).
|
||||
|
||||
Пиши значения JSON на русском языке. Return ONLY JSON matching the schema.
|
||||
|
||||
Заголовок атома (title) — живой русский без канцелярита: запрещены «является/являются», «данный», «осуществляет», «представляет собой». Пиши «X — Y», а не «X является Y»: заголовок уходит в имя файла и в ссылки, канцелярит оттуда расползается по всей базе.
|
||||
|
||||
Поле "next" (следующее действие) обязано НАЧИНАТЬСЯ с имени проекта владельца, которому этот атом полезен, — дословно одним из списка: ${ownerProjects().join(' · ') || 'Саморазвитие/инструментарий'}. Если ни один проект по теме не подходит, пиши «Саморазвитие/инструментарий». Формат: «<Проект>: <одно конкретное действие>». Проект не выдумывать и не переименовывать.
|
||||
|
||||
${fenceUntrusted('MATERIAL', text)}`
|
||||
}
|
||||
|
||||
async function atomizeCluster(cluster, sources, materialOverride) {
|
||||
const result = await llmJson(atomPrompt(cluster, sources, materialOverride), ATOM_SCHEMA)
|
||||
const result = await llmJson(atomPrompt(cluster, sources, materialOverride), ATOM_SCHEMA, {
|
||||
provider: ATOMIZER_PROVIDER,
|
||||
label: `atomize:${cluster.id}`
|
||||
})
|
||||
const atoms = Array.isArray(result?.atoms) ? result.atoms : []
|
||||
return atoms.filter(a => a && a.title && a.what).slice(0, MAX_ATOMS)
|
||||
}
|
||||
@@ -717,10 +814,12 @@ ${fenceUntrusted('MATERIAL', text)}`
|
||||
}
|
||||
|
||||
async function enrichCluster(cluster, sources) {
|
||||
const text = cluster.records.map(r => compact(r.text, 6000)).join('\n---\n').slice(0, 24000)
|
||||
const text = cluster.records.map(r => compact(r.text, Math.max(6000, MAX_RECORD_CHARS))).join('\n---\n').slice(0, MAX_MATERIAL_CHARS)
|
||||
const res = await llmJson(enrichPrompt(text, sources), ENRICH_SCHEMA, {
|
||||
tools: ['WebSearch', 'WebFetch', 'mcp__firecrawl', 'mcp__tavily'],
|
||||
timeoutMs: ENRICH_TIMEOUT_MS
|
||||
provider: VERIFIER_PROVIDER,
|
||||
tools: ['WebSearch', 'WebFetch'],
|
||||
timeoutMs: ENRICH_TIMEOUT_MS,
|
||||
label: `enrich:${cluster.id}`
|
||||
})
|
||||
const enriched = typeof res?.enriched === 'string' ? res.enriched.trim() : ''
|
||||
const addedSources = Array.isArray(res?.sources) ? res.sources.filter(isPublicHttpUrl) : []
|
||||
@@ -735,9 +834,60 @@ function atomFingerprint(atom, clusterId = '') {
|
||||
return crypto.createHash('sha1').update(key).digest('hex').slice(0, 10)
|
||||
}
|
||||
|
||||
function words(value) {
|
||||
return String(value || '')
|
||||
.toLowerCase()
|
||||
.split(/[^a-zа-яё0-9]+/i)
|
||||
.filter(word => word.length >= 4)
|
||||
}
|
||||
|
||||
function localSourceRefsForAtom(cluster, atom) {
|
||||
const valid = new Set(cluster.records.map(record => record.source_ref).filter(Boolean))
|
||||
const explicit = Array.isArray(atom.source_refs)
|
||||
? atom.source_refs.filter(ref => valid.has(ref))
|
||||
: []
|
||||
if (explicit.length) return [...new Set(explicit)]
|
||||
|
||||
const atomText = `${atom.title || ''}\n${atom.what || ''}\n${(atom.sources || []).join('\n')}`.toLowerCase()
|
||||
const tokens = new Set(words(atomText))
|
||||
const scored = cluster.records
|
||||
.map(record => {
|
||||
const text = String(record.text || '').toLowerCase()
|
||||
let score = 0
|
||||
for (const source of atom.sources || []) {
|
||||
const url = String(source || '').toLowerCase()
|
||||
if (url && text.includes(url.replace(/^https?:\/\//, '').replace(/^www\./, ''))) score += 8
|
||||
try {
|
||||
const parsed = new URL(url)
|
||||
const pathBits = parsed.pathname.split('/').filter(Boolean).slice(0, 2).join('/')
|
||||
if (pathBits && text.includes(pathBits.toLowerCase())) score += 6
|
||||
if (parsed.hostname && text.includes(parsed.hostname.replace(/^www\./, ''))) score += 3
|
||||
} catch {}
|
||||
}
|
||||
for (const token of tokens) if (text.includes(token)) score += 1
|
||||
return { ref: record.source_ref, score }
|
||||
})
|
||||
.filter(item => item.ref && item.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
const best = scored[0]?.score || 0
|
||||
return scored.filter(item => item.score === best).map(item => item.ref)
|
||||
}
|
||||
|
||||
// NOTE-SPEC enum is the single truth for `verified:` (SPEC_VERIFIED). Deep verify
|
||||
// speaks verified|assumed|unknown, so map it here instead of writing a boolean the
|
||||
// spec gate rejects.
|
||||
function specVerified(status) {
|
||||
const map = { verified: SPEC_VERIFIED[0], assumed: SPEC_VERIFIED[2], unknown: SPEC_VERIFIED[5] }
|
||||
return map[status] || SPEC_VERIFIED[5]
|
||||
}
|
||||
|
||||
function makeAtomNote(cluster, atom, verdict) {
|
||||
const how = (atom.how || []).filter(Boolean).map(h => `- ${compact(h, 240)}`).join('\n') || '- Проверить и применить в контексте.'
|
||||
const sourceRefs = cluster.records.map(record => `- ${record.source_ref}`).join('\n')
|
||||
const localRefs = localSourceRefsForAtom(cluster, atom)
|
||||
const sourceRefs = (localRefs.length ? localRefs : cluster.records.map(record => record.source_ref))
|
||||
.filter(Boolean)
|
||||
.map(ref => `- ${ref}`)
|
||||
.join('\n')
|
||||
const addedFacts = (cluster.enrichment?.addedFacts || []).map(f => `- ${compact(f, 300)}`).join('\n') || '- Внешние факты не записаны.'
|
||||
const srcs = (atom.sources || []).filter(isPublicHttpUrl)
|
||||
const sourceLines = srcs.length
|
||||
@@ -748,10 +898,12 @@ function makeAtomNote(cluster, atom, verdict) {
|
||||
const isVerified = v.status === 'verified'
|
||||
return `---
|
||||
title: "${String(atom.title).replace(/"/g, '\\"').slice(0, 120)}"
|
||||
type: "knowledge-note"
|
||||
type: "synthesis"
|
||||
subject: world
|
||||
source_type: "synthesis-atom"
|
||||
source: "session:${SESSION}/${cluster.id}#${fp}"
|
||||
source_ref: "session:${SESSION}/${cluster.id}#${fp}"
|
||||
verified: ${isVerified}
|
||||
verified: ${specVerified(v.status)}
|
||||
verification_status: "${v.status}"
|
||||
verification: "llm-atomized; ${String(v.note || 'sources unverified').replace(/"/g, "'")}"
|
||||
status: "${isVerified ? 'final' : 'draft'}"
|
||||
@@ -787,7 +939,12 @@ ${sourceLines}
|
||||
Факты, добавленные до атомизации:
|
||||
${addedFacts}
|
||||
|
||||
## Проверка
|
||||
## 🎯 Как это поможет мне
|
||||
|
||||
- ${compact(atom.next, 240) || 'Применить в ближайшей задаче по теме кластера.'}
|
||||
- Тема: ${clusterTitleRu(cluster.id)} — смотреть сюда, когда всплывёт этот вопрос.
|
||||
|
||||
## Достоверность
|
||||
|
||||
- Статус проверки: **${v.status}**${v.note ? ` (${v.note})` : ''}.
|
||||
${isVerified
|
||||
@@ -807,6 +964,25 @@ ${isVerified
|
||||
}
|
||||
|
||||
await fs.mkdir(path.join(VAULT, '01 Concepts'), { recursive: true })
|
||||
// One runnable check for the source-scrape junk filter: real prose survives,
|
||||
// leaked page JS does not. Run: node scripts/mnemazine-synthesize.mjs --selftest
|
||||
if (argv.includes('--selftest')) {
|
||||
const junk = [
|
||||
'(function() {window.ytplayer={};',
|
||||
'ytcfg.set({"CLIENT_CANARY_STATE":"none","DEVICE":"ceng\\u003dUSER_DEFINED"});',
|
||||
'document.querySelector("#player").play();'
|
||||
]
|
||||
const prose = [
|
||||
'Obsidian хранит заметки как обычные markdown-файлы в локальной папке без облака.',
|
||||
'Wikilinks connect notes into a graph you can open and inspect from the sidebar.'
|
||||
]
|
||||
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}`)
|
||||
if (readmePoints(junk.concat(prose).join('\n'), 6).length !== prose.length) throw new Error('selftest: readmePoints kept the wrong lines')
|
||||
console.log(JSON.stringify({ ok: true, selftest: 'source-scrape junk filter' }))
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const records = await listRecords()
|
||||
const clusters = new Map()
|
||||
for (const record of records) {
|
||||
@@ -847,8 +1023,19 @@ async function processPart(part, parts, index) {
|
||||
let material
|
||||
if (ENRICH) {
|
||||
try {
|
||||
const deterministic = await enrichClusterFromGithub(part, sources) || await enrichClusterFromSources(part, sources)
|
||||
const { enriched, addedSources, addedFacts } = deterministic || await enrichCluster(part, sources)
|
||||
// GitHub API/README is a real primary source, so it stays first. The
|
||||
// generic page-scrape path builds a canned topic template and skips the
|
||||
// LLM atomizer, so it only runs when the LLM enricher gave nothing.
|
||||
let deterministic = await enrichClusterFromGithub(part, sources)
|
||||
let llmEnriched = null
|
||||
if (!deterministic) {
|
||||
llmEnriched = await enrichCluster(part, sources).catch(() => null)
|
||||
if (!llmEnriched?.enriched || (llmEnriched.addedFacts || []).length < MIN_ADDED_FACTS) {
|
||||
deterministic = await enrichClusterFromSources(part, sources)
|
||||
if (deterministic) llmEnriched = null
|
||||
}
|
||||
}
|
||||
const { enriched, addedSources, addedFacts } = deterministic || llmEnriched || { enriched: '', addedSources: [], addedFacts: [] }
|
||||
if (enriched && enriched.length > 200) {
|
||||
material = enriched
|
||||
for (const u of addedSources) if (!sources.some(s => s.url === u)) sources.push({ name: hostOf(u) || 'Source', url: u })
|
||||
@@ -875,15 +1062,25 @@ async function processPart(part, parts, index) {
|
||||
: await atomizeCluster(part, sources, material)
|
||||
let wroteAtom = false
|
||||
const allowedSourceUrls = new Set(sources.map(source => source.url).filter(isPublicHttpUrl))
|
||||
// Atom verdicts are independent read-only calls, so they are collected in
|
||||
// parallel (same verifyDeep args — call quality is unchanged). File writes
|
||||
// and counters stay serial. Cap via MNEMAZINE_VERIFY_CONCURRENCY.
|
||||
const pendingAtoms = []
|
||||
for (const atom of atoms) {
|
||||
atom.sources = (atom.sources || []).filter(url => allowedSourceUrls.has(url))
|
||||
const out = path.join(VAULT, '01 Concepts', `synthesis-${slugify(atom.title)}-${atomFingerprint(atom, part.id)}.md`)
|
||||
if (await fs.access(out).then(() => true).catch(() => false)) { skipped += 1; continue }
|
||||
const verdict = part.enrichment?.deterministic
|
||||
? { status: 'verified', checked: atom.sources || [], evidence: part.enrichment.kind === 'github' ? 'Fetched GitHub API/README/release for primary-source enrichment.' : 'Fetched public source pages from configured source hints.', note: `deterministic ${part.enrichment.kind} source check` }
|
||||
pendingAtoms.push({ atom, out, verdict: null })
|
||||
}
|
||||
const VERIFY_CONCURRENCY = Math.max(1, Number(process.env.MNEMAZINE_VERIFY_CONCURRENCY || '8'))
|
||||
await mapLimit(pendingAtoms, VERIFY_CONCURRENCY, async (entry) => {
|
||||
entry.verdict = part.enrichment?.deterministic
|
||||
? { status: 'verified', checked: entry.atom.sources || [], evidence: part.enrichment.kind === 'github' ? 'Fetched GitHub API/README/release for primary-source enrichment.' : 'Fetched public source pages from configured source hints.', note: `deterministic ${part.enrichment.kind} source check` }
|
||||
: DEEP
|
||||
? await verifyDeep(`${atom.what}\n${atom.why}`, atom.sources)
|
||||
: verifyLocal(atom.sources)
|
||||
? await verifyDeep(`${entry.atom.what}\n${entry.atom.why}`, entry.atom.sources, { provider: VERIFIER_PROVIDER, label: `verify:${part.id}` })
|
||||
: verifyLocal(entry.atom.sources)
|
||||
})
|
||||
for (const { atom, out, verdict } of pendingAtoms) {
|
||||
if (STRICT_ENRICH && verdict.status !== 'verified') {
|
||||
console.error(`[synthesize] strict verification rejected atom "${atom.title}": ${verdict.status}`)
|
||||
continue
|
||||
@@ -893,8 +1090,16 @@ async function processPart(part, parts, index) {
|
||||
wroteAtom = true
|
||||
}
|
||||
if (wroteAtom) return // atomized this cluster — skip the template note
|
||||
if (STRICT_ENRICH) throw new Error(`strict verification failed for cluster ${part.id}: no verified atoms`)
|
||||
console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`)
|
||||
// Strict verify rejected every atom. Writing nothing leaves the source
|
||||
// "unvisited": the next run re-atomizes it, gets fresh fingerprints and
|
||||
// re-verifies from scratch — the loop that burned 1755 verify calls on one
|
||||
// source. Fall through to the honest draft note instead (its own verdict
|
||||
// fields stay unverified), so the source has an artifact and stops recurring.
|
||||
if (STRICT_ENRICH) {
|
||||
console.error(`[synthesize] strict verification rejected all atoms for cluster ${part.id}; writing honest draft note instead of looping`)
|
||||
} else {
|
||||
console.error(`[synthesize] atomize produced no atoms for cluster ${part.id}; using template note`)
|
||||
}
|
||||
} catch (err) {
|
||||
if (STRICT_ENRICH) throw err
|
||||
console.error(`[synthesize] atomize failed for cluster ${part.id}: ${err.message}; using template note`)
|
||||
@@ -922,7 +1127,10 @@ for (const cluster of clusters.values()) {
|
||||
}
|
||||
// Swarm only helps when each task spawns an agent (deep); local template writes
|
||||
// stay serial. Cap concurrency so we are cheap+fast, not a fork bomb.
|
||||
const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || '4'))
|
||||
// Premium-tier CLIs are rate-limited/expensive → run atomization serial; cheaper
|
||||
// tiers parallelize. Read from the registry (cost_tier), never a name list.
|
||||
const DEFAULT_CONCURRENCY = providerCostTier(RESOLVED_ATOMIZER_PROVIDER) === 'premium' ? '1' : '4'
|
||||
const CONCURRENCY = Number(arg('concurrency', process.env.MNEMAZINE_CONCURRENCY || DEFAULT_CONCURRENCY))
|
||||
await mapLimit(tasks, useAtomize ? CONCURRENCY : 1, async ({ part, parts, index }) => {
|
||||
// Outer guard: a part must never break the swarm, even on an unexpected throw.
|
||||
try { await processPart(part, parts, index) }
|
||||
|
||||
@@ -6,10 +6,16 @@
|
||||
set -euo pipefail
|
||||
|
||||
REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
||||
ENV_DRAFT_ONLY="${MNEMAZINE_DRAFT_ONLY:-}"
|
||||
ENV_REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-}"
|
||||
ENV_REMOTE_REPORTS="${MNEMAZINE_REMOTE_REPORTS:-}"
|
||||
# Live host/key/paths live in a gitignored config, never hardcoded here.
|
||||
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
|
||||
# Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored.
|
||||
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
|
||||
[ -n "$ENV_DRAFT_ONLY" ] && export MNEMAZINE_DRAFT_ONLY="$ENV_DRAFT_ONLY"
|
||||
[ -n "$ENV_REMOTE_INBOX" ] && export MNEMAZINE_REMOTE_INBOX="$ENV_REMOTE_INBOX"
|
||||
[ -n "$ENV_REMOTE_REPORTS" ] && export MNEMAZINE_REMOTE_REPORTS="$ENV_REMOTE_REPORTS"
|
||||
VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
|
||||
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
|
||||
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-mnemazine/inbox}"
|
||||
@@ -17,13 +23,83 @@ REMOTE_REPORTS="${MNEMAZINE_REMOTE_REPORTS:-mnemazine/reports}"
|
||||
SSH_BIN="${MNEMAZINE_SSH_BIN:-ssh}"
|
||||
SYNC_BIN="${MNEMAZINE_TELEGRAM_SYNC_BIN:-$REPO/scripts/mnemazine-telegram-sync.sh}"
|
||||
|
||||
print_remote_paths() {
|
||||
reports_count="$(find "$REPO/reports" -type f 2>/dev/null | wc -l | tr -d ' ')"
|
||||
capability_report="$REPO/reports/2026-06-15-capability-link-suggestions.md"
|
||||
capability_size="unknown"
|
||||
[ -f "$capability_report" ] && capability_size="$(wc -c < "$capability_report" | tr -d ' ')"
|
||||
cat <<EOF
|
||||
Remote path review (host omitted)
|
||||
|
||||
| Remote path | Action | Code |
|
||||
|---|---|---|
|
||||
| ${REMOTE_INBOX%/}/ | read into local staging; no remote mutation | scripts/mnemazine-telegram-sync.sh:46 |
|
||||
| ${REMOTE_INBOX%/}/.search-queue | read and truncate | scripts/mnemazine-telegram-poll.sh:52 |
|
||||
| ${REMOTE_INBOX%/}/.run-now | read and delete; write retry back after failure | scripts/mnemazine-telegram-poll.sh:66,94 |
|
||||
| ${REMOTE_INBOX%/}/.last-run | overwrite with UTC timestamp | scripts/mnemazine-telegram-poll.sh:90 |
|
||||
| ${REMOTE_INBOX%/}/<pulled batch files> | delete only after successful local protocol run | scripts/mnemazine-telegram-sync.sh:65 |
|
||||
| ${REMOTE_REPORTS%/}/ | upload local reports/ only after the data-class gate allows a staged export | scripts/mnemazine-telegram-poll.sh:130 |
|
||||
| mnemazine/inbox, mnemazine/bot | create directories | setup.sh:178 |
|
||||
| mnemazine/bot/mnemazine-telegram-bot.mjs | overwrite bot script | setup.sh:179 |
|
||||
| mnemazine/bot/.env | write bot token under umask 177 | setup.sh:183 |
|
||||
| pm2 process mnemazine-bot | start/restart and save process | setup.sh:185 |
|
||||
|
||||
WARNING: reports/ upload was 88 files on 2026-08-22; current local count is ${reports_count}. It includes 2026-06-15-capability-link-suggestions.md (${capability_size} bytes) and live vault audit files. Bulk upload is disabled; reports can leave only through the P24 data-class gate.
|
||||
|
||||
Owner step after review:
|
||||
add MNEMAZINE_REMOTE_MUTATION=1 to $REPO/.mnemazine/config.env
|
||||
EOF
|
||||
}
|
||||
|
||||
record_blocked() {
|
||||
reason="$1"
|
||||
mkdir -p "$REPO/.mnemazine/state"
|
||||
set +e
|
||||
node - "$REPO/.mnemazine/state/telegram-blocked.json" "$reason" <<'NODE'
|
||||
const fs = require('node:fs')
|
||||
const [file, reason] = process.argv.slice(2)
|
||||
const now = new Date().toISOString()
|
||||
let prev = {}
|
||||
try { prev = JSON.parse(fs.readFileSync(file, 'utf8')) } catch {}
|
||||
const changed = prev.reason !== reason
|
||||
const lastPrinted = Date.parse(prev.last_printed_at || '')
|
||||
const shouldPrint = changed || !Number.isFinite(lastPrinted) || Date.now() - lastPrinted >= 86400000
|
||||
const next = {
|
||||
reason,
|
||||
first_seen: changed || !prev.first_seen ? now : prev.first_seen,
|
||||
last_seen: now,
|
||||
count: changed ? 1 : Number(prev.count || 0) + 1,
|
||||
last_printed_at: shouldPrint ? now : prev.last_printed_at
|
||||
}
|
||||
fs.writeFileSync(file, JSON.stringify(next, null, 2) + '\n')
|
||||
process.exit(shouldPrint ? 0 : 3)
|
||||
NODE
|
||||
rc="$?"
|
||||
set -e
|
||||
case "$rc" in
|
||||
0) return 0 ;;
|
||||
3) return 1 ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
--print-remote-paths) print_remote_paths; exit 0 ;;
|
||||
"") ;;
|
||||
*) echo "Usage: $0 [--print-remote-paths]" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
# ponytail: fail fast if still on the placeholder — beats a confusing ssh error.
|
||||
if [ "$VPS" = "deploy@YOUR_VPS_HOST" ]; then
|
||||
echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2
|
||||
if record_blocked "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env"; then
|
||||
echo "Set MNEMAZINE_VPS (and MNEMAZINE_VPS_KEY) in $REPO/.mnemazine/config.env" >&2
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
if [ "${MNEMAZINE_REMOTE_MUTATION:-0}" != "1" ]; then
|
||||
echo "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports." >&2
|
||||
if record_blocked "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports."; then
|
||||
echo "Set MNEMAZINE_REMOTE_MUTATION=1 after reviewing VPS paths; poll mutates remote flags/reports." >&2
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
ATTEMPT_MARKER="$REPO/.mnemazine/.last-daily-attempt"
|
||||
@@ -57,8 +133,21 @@ if [ -n "$queue" ]; then
|
||||
[ -z "$topic" ] && continue
|
||||
MNEMAZINE_DEEP=1 npm run --silent search -- --topic "$topic" || echo "search failed: $topic" >&2
|
||||
done <<< "$topics"
|
||||
# Push reports back so the mini app can read them (reverse channel Mac->VPS).
|
||||
[ -d "$REPO/reports" ] && rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/" 2>/dev/null || true
|
||||
# Заливка reports наружу — только через классовый барьер П24: партия
|
||||
# описывается манифестом, манифест проходит machine-class-gate, ненулевой код
|
||||
# ОСТАНАВЛИВАЕТ отправку. rsync ниже ОБЯЗАН стоять после вызова гейта — это
|
||||
# требование проверяет release-check machine-class-gate (грепом по этому файлу).
|
||||
if [ "${MNEMAZINE_PUSH_REPORTS:-0}" = "1" ]; then
|
||||
REPORTS_MANIFEST="$REPO/.mnemazine/state/reports-export-manifest.txt"
|
||||
mkdir -p "$REPO/.mnemazine/state"
|
||||
find "$REPO/reports" -type f -name '*.md' > "$REPORTS_MANIFEST"
|
||||
if node "$REPO/scripts/mnemazine-machine-class-gate.mjs" --batch "$REPORTS_MANIFEST" --target vps; then
|
||||
rsync -az -e "$SSH" "$REPO/reports/" "$VPS:$REMOTE_REPORTS/"
|
||||
else
|
||||
echo "reports export заблокирован гейтом класса данных П24 (pd/personal или неопределимый класс в партии)." >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
run=0; manual=0; daily=0
|
||||
|
||||
@@ -6,16 +6,23 @@
|
||||
set -euo pipefail
|
||||
|
||||
REPO="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
||||
ENV_REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-}"
|
||||
# Live host/key/paths live in a gitignored config, never hardcoded here.
|
||||
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
|
||||
# Non-secret personal overrides (e.g. MNEMAZINE_INBOX), gitignored.
|
||||
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
|
||||
[ -n "$ENV_REMOTE_INBOX" ] && export MNEMAZINE_REMOTE_INBOX="$ENV_REMOTE_INBOX"
|
||||
VPS="${MNEMAZINE_VPS:-deploy@YOUR_VPS_HOST}"
|
||||
KEY="${MNEMAZINE_VPS_KEY:-$HOME/.ssh/id_rsa}"
|
||||
REMOTE_INBOX="${MNEMAZINE_REMOTE_INBOX:-mnemazine/inbox/}"
|
||||
REMOTE_INBOX="${REMOTE_INBOX%/}/"
|
||||
# Inbox honours MNEMAZINE_INBOX (from config.env); defaults to repo-local inbox.
|
||||
LOCAL_INBOX="${MNEMAZINE_INBOX:-$REPO/inbox}"
|
||||
# Inbox must be explicit: otherwise Telegram traffic splits into a repo-local
|
||||
# inbox that the desktop protocol does not use.
|
||||
if [ -z "${MNEMAZINE_INBOX:-}" ]; then
|
||||
echo "Set MNEMAZINE_INBOX in $REPO/.mnemazine/config.env; sync refuses to use $REPO/inbox silently." >&2
|
||||
exit 1
|
||||
fi
|
||||
LOCAL_INBOX="$MNEMAZINE_INBOX"
|
||||
LOCAL_INBOX="${LOCAL_INBOX%/}/"
|
||||
STAGING="${LOCAL_INBOX}.staging/"
|
||||
# Export so the protocol runner reads the same inbox.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { SPEC_TYPES } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
@@ -63,6 +64,11 @@ function titleOf(text, file) {
|
||||
path.basename(file, '.md')
|
||||
}
|
||||
|
||||
function frontmatterType(text) {
|
||||
const match = String(text || '').match(/^type:\s*["']?([^"'\n#]+)["']?\s*(?:#.*)?$/m)
|
||||
return match ? match[1].trim() : ''
|
||||
}
|
||||
|
||||
async function walk(dir) {
|
||||
const out = []
|
||||
async function visit(folder) {
|
||||
@@ -158,7 +164,7 @@ async function collectTools() {
|
||||
const stat = await fs.stat(file)
|
||||
if (SINCE_MS && stat.mtimeMs < SINCE_MS) continue
|
||||
const text = await fs.readFile(file, 'utf8').catch(() => '')
|
||||
if (!/type:\s*"knowledge-note"/.test(text)) continue
|
||||
if (!SPEC_TYPES.has(frontmatterType(text))) continue
|
||||
if (!/github\.com\//i.test(text)) continue
|
||||
if (!/verified:\s*true/.test(text)) continue
|
||||
const repos = reposFrom(text)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared terminal UI helpers for install.sh and setup.sh. Sourced, never run.
|
||||
# Bilingual: MNEMAZINE_LANG is ru|en, chosen once from the locale. A public
|
||||
# repo defaults to English so the first question a stranger sees is in English.
|
||||
|
||||
# Locale → language, one case. Explicit MNEMAZINE_LANG wins; otherwise ru_* → ru.
|
||||
case "${MNEMAZINE_LANG:-}" in
|
||||
ru|en) : ;;
|
||||
*)
|
||||
case "${LC_ALL:-}${LANG:-}" in
|
||||
ru_*|ru|*ru_RU*|*ru.*) MNEMAZINE_LANG=ru ;;
|
||||
*) MNEMAZINE_LANG=en ;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
export MNEMAZINE_LANG
|
||||
|
||||
# L "<ru>" "<en>": echo the string for the active language (no trailing newline).
|
||||
L() { if [ "$MNEMAZINE_LANG" = ru ]; then printf '%s' "$1"; else printf '%s' "$2"; fi; }
|
||||
|
||||
b() { printf '\033[1m%s\033[0m\n' "$*"; }
|
||||
ok() { printf ' \033[32m✓\033[0m %s\n' "$*"; }
|
||||
no() { printf ' \033[31m✗\033[0m %s\n' "$*"; }
|
||||
note() { printf ' • %s\n' "$*"; }
|
||||
warn() { printf ' \033[33m[!]\033[0m %s\n' "$*"; }
|
||||
# stage "<n/total>" "<title>" — numbered with a denominator so progress is legible.
|
||||
stage() { printf '\n\033[1m\033[36m── %s %s ──\033[0m %s\n' "$(L 'Этап' 'Stage')" "$1" "$2"; }
|
||||
miss() { printf '\n \033[33m%s\033[0m %s\n' "$1" "${2:-}"; }
|
||||
halt() { printf '\n\033[1m%s\033[0m\n' "$(L 'Установи это и запусти снова — продолжим со следующего этапа.' 'Install this, run again — we continue from the next stage.')"; exit 1; }
|
||||
@@ -4,12 +4,34 @@ set -euo pipefail
|
||||
ROOT="${MNEMAZINE_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
|
||||
cd "$ROOT"
|
||||
|
||||
git pull --ff-only
|
||||
echo "Update touches code only. Your data stays put — inbox/, vault/, reports/"
|
||||
echo "are gitignored and never pulled or rebuilt."
|
||||
|
||||
# git pull can fail on a local edit; say what to do instead of dying silently.
|
||||
if ! git pull --ff-only; then
|
||||
echo "git pull --ff-only failed (local edits, or history diverged)." >&2
|
||||
echo "Your data is untouched. Inspect with: git status" >&2
|
||||
echo "Then: git stash (or commit) your changes, run this again, and reapply." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# install.sh now exits with its status. Code 2 = skeleton rebuilt, some optional
|
||||
# capability degraded (deps intentionally skipped on update) — normal, not a stop.
|
||||
# Code 1 = real failure — stop and surface it.
|
||||
set +e
|
||||
MNEMAZINE_FROM_SETUP=1 MNEMAZINE_SKIP_DEPS=1 bash install.sh
|
||||
rc=$?
|
||||
set -e
|
||||
case "$rc" in
|
||||
0) : ;;
|
||||
2) echo "Some optional capabilities are degraded (deps skipped on update) — that is expected." ;;
|
||||
*) echo "install.sh failed (code $rc) — update not finished." >&2; exit "$rc" ;;
|
||||
esac
|
||||
|
||||
npm run audit:local
|
||||
|
||||
echo "Mnemazine updated."
|
||||
echo "Sign of life: npm run doctor"
|
||||
echo "Preflight before live run: npm run preflight:live"
|
||||
echo "Run from chat: Mnemazine"
|
||||
echo "Run from terminal: mnemazine"
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
function flag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const MAX_FAILURES = Number(arg('max-failures', '50'))
|
||||
const WIKI_SCOPE = arg('wiki-scope', flag('strict-wiki') ? 'all' : 'critical')
|
||||
const STRICT_WIKI = flag('strict-wiki')
|
||||
|
||||
const rawAllowed = new Set([
|
||||
'99 Система/Лог обработки.md',
|
||||
'99 Система/Протокол_Мнемозина.md',
|
||||
'Лог обработки.md'
|
||||
])
|
||||
|
||||
const wikiTargetIgnore = new Set(['...', '…', 'note', 'Название'])
|
||||
|
||||
const rawRules = [
|
||||
['raw-media-name', /\b(?:temp[_-]?image|tmpImage|IMG_\d+)(?:\.(?:WEBP|PNG|JPE?G|HEIC|TIFF|MOV|MP4))?\b/gi],
|
||||
['draft-marker', /\b(?:intake-draft|draft-local)\b/gi],
|
||||
['raw-ocr', /\braw\s+ocr\b|сыр[оы]й\s+ocr|Локальное извлечение/gi],
|
||||
['external-sandbox-ref', /\b(?:attached_file:\/\/|sandbox:\/mnt\/data\/|oai_citation|turn\d+(?:search|fetch|view)\d+)\b/gi],
|
||||
['chatgpt-tracking-ref', /[?&]utm_source=chatgpt\.com\b/gi],
|
||||
['english-section-shell', /^##\s+(What This Is|Why It Matters|How To Use It|Source|Verification|Related Notes|Reuse)\b/gm]
|
||||
]
|
||||
|
||||
function norm(value) {
|
||||
return String(value || '')
|
||||
.replace(/\\+$/g, '')
|
||||
.replace(/\.md$/i, '')
|
||||
.replace(/[—–]/g, '-')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function stripDate(value) {
|
||||
return norm(value)
|
||||
.replace(/^\d{4}-\d{2}-\d{2}\s*[-—–]\s*/, '')
|
||||
.replace(/-\d+$/, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function pathRel(file) {
|
||||
return path.relative(VAULT, file).replace(/\\/g, '/')
|
||||
}
|
||||
|
||||
function addFailure(failures, rule, file, details) {
|
||||
if (failures.length >= MAX_FAILURES) return
|
||||
failures.push({ rule, file, details })
|
||||
}
|
||||
|
||||
function addIndex(index, key, file) {
|
||||
const normalized = norm(key)
|
||||
if (!normalized) return
|
||||
if (!index.has(normalized)) index.set(normalized, new Set())
|
||||
index.get(normalized).add(file)
|
||||
}
|
||||
|
||||
function frontmatterValue(text, key) {
|
||||
const match = text.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))
|
||||
if (!match) return ''
|
||||
return match[1].trim().replace(/^['"]|['"]$/g, '')
|
||||
}
|
||||
|
||||
function frontmatterAliases(text) {
|
||||
const out = []
|
||||
const inline = text.match(/^aliases:\s*\[([^\]]+)\]/m)
|
||||
if (inline) {
|
||||
out.push(...inline[1].split(',').map(item => item.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean))
|
||||
}
|
||||
const block = text.match(/^aliases:\s*\n((?:\s+-\s+.+\n?)+)/m)
|
||||
if (block) {
|
||||
out.push(...block[1].split('\n')
|
||||
.map(line => line.replace(/^\s+-\s+/, '').trim().replace(/^['"]|['"]$/g, ''))
|
||||
.filter(Boolean))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function strictWikiFile(rel) {
|
||||
return [
|
||||
'_МАСТЕР-ИНДЕКС.md',
|
||||
'10 Карта возможностей.md',
|
||||
'AGENTS.md',
|
||||
'CLAUDE.md',
|
||||
'99 Система/Протокол_Мнемозина.md',
|
||||
'99 Система/Agent_Handoff_Graph.md'
|
||||
].includes(rel) || rel.startsWith('08 AI и Инструменты/Capabilities/_СПОСОБНОСТИ')
|
||||
}
|
||||
|
||||
async function collectVault() {
|
||||
const files = []
|
||||
const dirs = new Set([''])
|
||||
const nestedGraphify = []
|
||||
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (['.git', '.obsidian', '.mnemazine'].includes(item.name)) continue
|
||||
const file = path.join(dir, item.name)
|
||||
const rel = pathRel(file)
|
||||
if (item.isDirectory()) {
|
||||
if (item.name.startsWith('graphify-out')) {
|
||||
if (path.dirname(rel) !== '.') nestedGraphify.push(rel)
|
||||
continue
|
||||
}
|
||||
dirs.add(rel)
|
||||
await walk(file)
|
||||
} else if (item.isFile() && item.name.endsWith('.md')) {
|
||||
files.push(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await walk(VAULT)
|
||||
return { files, dirs, nestedGraphify }
|
||||
}
|
||||
|
||||
function rawMarkerFailures(files) {
|
||||
const failures = []
|
||||
for (const file of files) {
|
||||
const rel = pathRel(file)
|
||||
const basename = path.basename(file)
|
||||
if (/Users [^/ ]+|\/Users\/[^/]+|Проекты mnemazine|личный vault 0\d/.test(basename)) {
|
||||
addFailure(failures, 'private-path-filename', rel, [basename])
|
||||
}
|
||||
if (rawAllowed.has(rel)) continue
|
||||
const text = existsSync(file) ? String(readFileSync(file, 'utf8')) : ''
|
||||
const haystack = `${basename}\n${text}`
|
||||
for (const [rule, re] of rawRules) {
|
||||
const matches = [...haystack.matchAll(re)].slice(0, 5).map(match => match[0])
|
||||
if (matches.length) addFailure(failures, rule, rel, matches)
|
||||
}
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
function buildWikiIndex(files, dirs) {
|
||||
const index = new Map()
|
||||
for (const file of files) {
|
||||
const rel = pathRel(file)
|
||||
const withoutExt = rel.replace(/\.md$/, '')
|
||||
const basename = path.basename(withoutExt)
|
||||
const text = existsSync(file) ? String(readFileSync(file, 'utf8')) : ''
|
||||
for (const key of [
|
||||
rel,
|
||||
withoutExt,
|
||||
basename,
|
||||
stripDate(basename),
|
||||
frontmatterValue(text, 'title'),
|
||||
...frontmatterAliases(text)
|
||||
]) {
|
||||
addIndex(index, key, rel)
|
||||
}
|
||||
}
|
||||
return { index, dirs }
|
||||
}
|
||||
|
||||
function wikiTargetExists(target, wiki) {
|
||||
let clean = String(target || '').split('|')[0].split('#')[0].split('^')[0].trim()
|
||||
clean = clean.replace(/\\+$/g, '').trim()
|
||||
if (!clean || clean.startsWith('#') || /^https?:\/\//i.test(clean)) return true
|
||||
if (wikiTargetIgnore.has(clean)) return true
|
||||
|
||||
const normalized = norm(clean)
|
||||
if (!normalized) return true
|
||||
if (wiki.dirs.has(normalized) || wiki.index.has(normalized)) return true
|
||||
const basename = path.basename(normalized)
|
||||
return wiki.index.has(basename) || wiki.index.has(stripDate(basename))
|
||||
}
|
||||
|
||||
function linkScanText(text) {
|
||||
return String(text || '')
|
||||
.replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
|
||||
.replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
|
||||
}
|
||||
|
||||
function wikiFailures(files, wiki) {
|
||||
const failures = []
|
||||
const warnings = []
|
||||
const linkRe = /\[\[([^\]\n]+)\]\]/g
|
||||
for (const file of files) {
|
||||
const rel = pathRel(file)
|
||||
if (WIKI_SCOPE === 'none') continue
|
||||
if (WIKI_SCOPE === 'critical' && !strictWikiFile(rel)) continue
|
||||
const text = existsSync(file) ? linkScanText(readFileSync(file, 'utf8')) : ''
|
||||
let match
|
||||
while ((match = linkRe.exec(text))) {
|
||||
const target = match[1].split('|')[0].trim()
|
||||
if (wikiTargetExists(target, wiki)) continue
|
||||
const item = { rule: 'broken-wiki-link', file: rel, details: [target] }
|
||||
if (STRICT_WIKI || WIKI_SCOPE === 'critical') {
|
||||
if (failures.length < MAX_FAILURES) failures.push(item)
|
||||
} else if (warnings.length < MAX_FAILURES) {
|
||||
warnings.push(item)
|
||||
}
|
||||
}
|
||||
}
|
||||
return { failures, warnings }
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const failures = []
|
||||
const warnings = []
|
||||
const { files, dirs, nestedGraphify } = await collectVault()
|
||||
|
||||
for (const rel of nestedGraphify) addFailure(failures, 'nested-graphify-runtime', rel, ['move graphify runtime out of note folders'])
|
||||
for (const failure of rawMarkerFailures(files)) addFailure(failures, failure.rule, failure.file, failure.details)
|
||||
|
||||
const wiki = wikiFailures(files, buildWikiIndex(files, dirs))
|
||||
for (const failure of wiki.failures) addFailure(failures, failure.rule, failure.file, failure.details)
|
||||
warnings.push(...wiki.warnings)
|
||||
|
||||
const result = {
|
||||
ok: failures.length === 0,
|
||||
vault: VAULT,
|
||||
checked: {
|
||||
markdown_files: files.length,
|
||||
nested_graphify_dirs: nestedGraphify.length,
|
||||
wiki_scope: WIKI_SCOPE,
|
||||
strict_wiki: STRICT_WIKI
|
||||
},
|
||||
failures,
|
||||
warnings
|
||||
}
|
||||
|
||||
console.log(JSON.stringify(result, null, 2))
|
||||
if (!result.ok) process.exit(1)
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
console.error(error.message || error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1,362 @@
|
||||
#!/usr/bin/env node
|
||||
// mnemazine-vault-hygiene-check.mjs — прибор П15 «Гигиена vault».
|
||||
//
|
||||
// Три режима:
|
||||
// --snapshot --out <file> слепок vault: basename всех .md, sha256 каждого,
|
||||
// вес по каталогам, wikilink-вхождения внутри/вне
|
||||
// graphify-каталогов, число путей в git status.
|
||||
// --compare [before] множество basename before-слепка == ЖИВОМУ диску:
|
||||
// свежий срез vault снимается самим --compare в момент
|
||||
// запуска, отдельный after-слепок не нужен (можно вывести
|
||||
// побочно через --after-out <file>). Без позиционного
|
||||
// аргумента before берётся из .mnemazine/state/vault-
|
||||
// hygiene-before.json. Нет before-слепка → exit 2
|
||||
// (fail-closed: сверка без базиса — это не «зелёный»).
|
||||
// Расхождение → exit 1 с именами пропавших/появившихся
|
||||
// файлов. Допустимые новые basename читаются из манифеста
|
||||
// .mnemazine/state/vault-hygiene-allowed-new.json — объявление
|
||||
// живёт в ДАННЫХ, а не во флаге вызова.
|
||||
// --converge сходимость замерщиков битых wikilink: число от
|
||||
// mnemazine-kb-lint.mjs --json --limit=500 против
|
||||
// независимого грубого обхода ниже. Расхождение → exit 1.
|
||||
//
|
||||
// Грубый обход сознательно НЕ исключает graphify-out* — именно этим два замерщика
|
||||
// расходились до П15 (один считал внутри graphify, другой снаружи). После выноса
|
||||
// мёртвых бэкапов оба обязаны давать одно число; вернувшийся бэкап снова их разводит,
|
||||
// и --converge обязан упасть (враждебная проба 3 плана П15).
|
||||
//
|
||||
// Все обходы — под LC_ALL=C: BSD uniq/sort под en_US.UTF-8 схлопывает разные
|
||||
// кириллические имена (инвариант 4 мастер-плана).
|
||||
|
||||
import fs from 'node:fs/promises'
|
||||
import { existsSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import crypto from 'node:crypto'
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { resolveVault as resolveVaultPath } from './mnemazine-paths.mjs'
|
||||
|
||||
process.env.LC_ALL = 'C'
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
function arg(name, fallback = '') {
|
||||
const i = argv.indexOf(`--${name}`)
|
||||
if (i !== -1 && argv[i + 1] && !argv[i + 1].startsWith('--')) return argv[i + 1]
|
||||
const eq = argv.find(a => a.startsWith(`--${name}=`))
|
||||
return eq ? eq.slice(name.length + 3) : fallback
|
||||
}
|
||||
const flag = name => argv.includes(`--${name}`)
|
||||
|
||||
const nfc = value => String(value || '').normalize('NFC')
|
||||
|
||||
function resolveVault() {
|
||||
return resolveVaultPath({ cli: arg('vault'), requireExists: false })
|
||||
}
|
||||
|
||||
const KB_LINT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'mnemazine-kb-lint.mjs')
|
||||
|
||||
const ALLOWED_NEW_MANIFEST = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)), '..', '.mnemazine', 'state', 'vault-hygiene-allowed-new.json'
|
||||
)
|
||||
|
||||
// Манифест допустимых появлений — единственный канал объявления новых basename.
|
||||
// Отсутствующий файл = пустой манифест; битый JSON = exit 1 (молчаливого пропуска нет).
|
||||
async function readAllowedNew() {
|
||||
if (!existsSync(ALLOWED_NEW_MANIFEST)) return []
|
||||
let doc
|
||||
try {
|
||||
doc = JSON.parse(await fs.readFile(ALLOWED_NEW_MANIFEST, 'utf8'))
|
||||
} catch (err) {
|
||||
console.error(`FAIL: манифест допустимых появлений — битый JSON: ${ALLOWED_NEW_MANIFEST} (${err.message})`)
|
||||
process.exit(1)
|
||||
}
|
||||
const list = Array.isArray(doc?.allowed) ? doc.allowed : []
|
||||
return list
|
||||
.map(entry => ({ basename: nfc(entry?.basename), reason: String(entry?.reason || ''), added: String(entry?.added || '') }))
|
||||
.filter(entry => entry.basename)
|
||||
}
|
||||
|
||||
async function writeAllowedNew(entries) {
|
||||
const doc = {
|
||||
description: 'Манифест допустимых появлений прибора П15 (mnemazine-vault-hygiene-check.mjs --compare). Новый basename в vault считается законным только если он объявлен здесь, с причиной. Любой необъявленный — exit 1 с именем. Флаг --allow-new лишь ДОБАВЛЯЕТ запись в этот файл, обхода сверки нет.',
|
||||
allowed: entries
|
||||
}
|
||||
await fs.mkdir(path.dirname(ALLOWED_NEW_MANIFEST), { recursive: true })
|
||||
await fs.writeFile(ALLOWED_NEW_MANIFEST, JSON.stringify(doc, null, 2) + '\n', 'utf8')
|
||||
}
|
||||
|
||||
const SKIP_DIRS = new Set(['.git', '.obsidian', '.mnemazine'])
|
||||
|
||||
// --- Обход vault -------------------------------------------------------------
|
||||
// graphify: 'none' — повторяет исключения kb-lint (все graphify-out*, 99 Система/_lint).
|
||||
// graphify: 'extra' — грубый обход для --converge: видит любые graphify-out* КРОМЕ
|
||||
// рабочего graphify-out (его GRAPH_REPORT.md линкует метки кластеров,
|
||||
// а не ноты). Вернувшийся из архива бэкап грубый обход увидит — и
|
||||
// замерщики разойдутся, чего требует враждебная проба 3 плана П15.
|
||||
// graphify: 'all' — слепок: видит вообще всё.
|
||||
async function walkVault(vault, { graphify = 'none' } = {}) {
|
||||
const md = []
|
||||
const dirs = new Set()
|
||||
const fileKeys = new Set()
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const abs = path.join(dir, item.name)
|
||||
const rel = nfc(path.relative(vault, abs).replace(/\\/g, '/'))
|
||||
if (item.isDirectory()) {
|
||||
if (SKIP_DIRS.has(item.name)) continue
|
||||
if (item.name.startsWith('graphify-out') && graphify !== 'all' && !(graphify === 'extra' && item.name !== 'graphify-out')) continue
|
||||
if (rel === '99 Система/_lint') continue
|
||||
dirs.add(rel)
|
||||
await walk(abs)
|
||||
} else if (item.isFile()) {
|
||||
fileKeys.add(rel)
|
||||
fileKeys.add(nfc(item.name))
|
||||
fileKeys.add(nfc(item.name).replace(/\.md$/i, ''))
|
||||
if (item.name.endsWith('.md')) md.push({ abs, rel })
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(vault)
|
||||
return { md, dirs, fileKeys }
|
||||
}
|
||||
|
||||
// Код-блоки гасятся пробелами — позиции не едут (та же дисциплина, что в kb-lint).
|
||||
function scanText(text) {
|
||||
return text
|
||||
.replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
|
||||
.replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
|
||||
}
|
||||
|
||||
function linkTarget(raw) {
|
||||
return nfc(raw.split('|')[0].split('#')[0].split('^')[0].trim().replace(/\\+$/, ''))
|
||||
}
|
||||
|
||||
// --- Независимый грубый замер битых wikilink ---------------------------------
|
||||
// Отдельная реализация (не импорт kb-lint): разрешение цели через плоское
|
||||
// множество ключей. Семантика совпадает с kb-lint, код — свой.
|
||||
async function roughBrokenCount(vault) {
|
||||
const wiki = await walkVault(vault, { graphify: 'extra' })
|
||||
const resolvable = new Set()
|
||||
for (const key of wiki.dirs) resolvable.add(key)
|
||||
for (const key of wiki.fileKeys) resolvable.add(key)
|
||||
for (const file of wiki.md) {
|
||||
const base = nfc(path.basename(file.rel))
|
||||
resolvable.add(file.rel.replace(/\.md$/i, ''))
|
||||
resolvable.add(base)
|
||||
resolvable.add(base.replace(/\.md$/i, ''))
|
||||
}
|
||||
let broken = 0
|
||||
const brokenTargets = new Map()
|
||||
const linkRe = /\[\[([^\]\n]+)\]\]/g
|
||||
for (const file of wiki.md) {
|
||||
const text = scanText(await fs.readFile(file.abs, 'utf8'))
|
||||
let match
|
||||
while ((match = linkRe.exec(text))) {
|
||||
const target = linkTarget(match[1])
|
||||
if (!target || target.startsWith('#') || /^(https?|mailto):/i.test(target)) continue
|
||||
const base = nfc(path.basename(target))
|
||||
const keys = [target, target.replace(/\.md$/i, ''), base, base.replace(/\.md$/i, '')]
|
||||
if (keys.some(key => resolvable.has(key))) continue
|
||||
broken += 1
|
||||
brokenTargets.set(target, (brokenTargets.get(target) || 0) + 1)
|
||||
}
|
||||
}
|
||||
return { count: broken, targets: brokenTargets }
|
||||
}
|
||||
|
||||
// --- Слепок ------------------------------------------------------------------
|
||||
async function takeSnapshot(vault) {
|
||||
const wiki = await walkVault(vault, { graphify: 'all' })
|
||||
const files = []
|
||||
const weightByTop = new Map()
|
||||
let wikilinksInGraphify = 0
|
||||
let wikilinksOutGraphify = 0
|
||||
const linkRe = /\[\[([^\]\n]+)\]\]/g
|
||||
for (const file of wiki.md) {
|
||||
const buf = await fs.readFile(file.abs)
|
||||
const sha256 = crypto.createHash('sha256').update(buf).digest('hex')
|
||||
const text = buf.toString('utf8')
|
||||
const occurrences = (text.match(linkRe) || []).length
|
||||
const inGraphify = file.rel.split('/').some(part => part.startsWith('graphify-out'))
|
||||
if (inGraphify) wikilinksInGraphify += occurrences
|
||||
else wikilinksOutGraphify += occurrences
|
||||
files.push({ path: file.rel, basename: nfc(path.basename(file.rel)), sha256, bytes: buf.length })
|
||||
}
|
||||
// Вес по каталогам — все файлы, не только .md.
|
||||
async function weigh(dir) {
|
||||
let total = 0
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
const abs = path.join(dir, item.name)
|
||||
if (item.isDirectory()) total += await weigh(abs)
|
||||
else if (item.isFile()) total += (await fs.stat(abs).catch(() => ({ size: 0 }))).size
|
||||
}
|
||||
return total
|
||||
}
|
||||
for (const item of await fs.readdir(vault, { withFileTypes: true })) {
|
||||
const abs = path.join(vault, item.name)
|
||||
const bytes = item.isDirectory() ? await weigh(abs) : (await fs.stat(abs).catch(() => ({ size: 0 }))).size
|
||||
weightByTop.set(nfc(item.name), bytes)
|
||||
}
|
||||
const git = spawnSync('git', ['-C', vault, 'status', '--porcelain'], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' } })
|
||||
const gitStatusPaths = git.status === 0 ? git.stdout.split('\n').filter(Boolean).length : null
|
||||
const basenames = [...new Set(files.map(f => f.basename))].sort()
|
||||
const snap = {
|
||||
tool: 'mnemazine-vault-hygiene-check',
|
||||
created_at: new Date().toISOString(),
|
||||
vault,
|
||||
markdown_files: files.length,
|
||||
basenames,
|
||||
files: files.sort((a, b) => a.path < b.path ? -1 : 1),
|
||||
weight_bytes_by_top: Object.fromEntries([...weightByTop.entries()].sort()),
|
||||
wikilinks: { inside_graphify: wikilinksInGraphify, outside_graphify: wikilinksOutGraphify, total: wikilinksInGraphify + wikilinksOutGraphify },
|
||||
git_status_paths: gitStatusPaths
|
||||
}
|
||||
return snap
|
||||
}
|
||||
|
||||
async function snapshot(outPath) {
|
||||
const snap = await takeSnapshot(resolveVault())
|
||||
await fs.mkdir(path.dirname(path.resolve(outPath)), { recursive: true })
|
||||
await fs.writeFile(outPath, JSON.stringify(snap, null, 2) + '\n', 'utf8')
|
||||
console.log(`слепок записан: ${outPath}`)
|
||||
console.log(`markdown: ${snap.markdown_files}, basename уникальных: ${snap.basenames.length}, git status: ${snap.git_status_paths}`)
|
||||
console.log(`wikilinks: внутри graphify ${snap.wikilinks.inside_graphify}, вне ${snap.wikilinks.outside_graphify}`)
|
||||
}
|
||||
|
||||
// --- Сверка before-слепка с ЖИВЫМ диском -------------------------------------
|
||||
// --compare [before] сверяет before-слепок со свежим срезом vault, который
|
||||
// снимается самим --compare в момент запуска. До П15b сравнивались два
|
||||
// СОХРАНЁННЫХ JSON — гейт был слеп к подложке в живом vault, если after-слепок
|
||||
// не пересняли. Отдельный after-слепок больше не участвует в сверке; при нужде
|
||||
// живой срез можно вывести побочно через --after-out <file>.
|
||||
// Fail-closed: нет before-слепка (или он битый) → exit 2, сверка без базиса
|
||||
// не считается «зелёной».
|
||||
// Допустимые новые basename живут в манифесте .mnemazine/state/vault-hygiene-allowed-new.json
|
||||
// и читаются самим --compare, без флагов. --allow-new <a,b,c> [--reason <текст>] —
|
||||
// НЕ обход: он дописывает записи в манифест, после чего сверка идёт по манифесту.
|
||||
// Любая другая пропажа/появление → exit 1 с именем.
|
||||
async function compare(beforePath) {
|
||||
let before
|
||||
try {
|
||||
before = JSON.parse(await fs.readFile(beforePath, 'utf8'))
|
||||
} catch (err) {
|
||||
console.error(`compare FAIL: нет читаемого before-слепка: ${beforePath} (${err.message})`)
|
||||
process.exit(2)
|
||||
}
|
||||
if (!Array.isArray(before?.basenames)) {
|
||||
console.error(`compare FAIL: before-слепок без массива basenames: ${beforePath}`)
|
||||
process.exit(2)
|
||||
}
|
||||
const vault = resolveVault()
|
||||
if (!existsSync(vault)) {
|
||||
console.error(`compare FAIL: живой vault не существует: ${vault}`)
|
||||
process.exit(2)
|
||||
}
|
||||
const after = await takeSnapshot(vault)
|
||||
console.log(`живой срез снят с диска: ${vault} (${after.markdown_files} markdown, ${after.basenames.length} уникальных basename)`)
|
||||
const afterOut = arg('after-out', '')
|
||||
if (afterOut) {
|
||||
await fs.mkdir(path.dirname(path.resolve(afterOut)), { recursive: true })
|
||||
await fs.writeFile(afterOut, JSON.stringify(after, null, 2) + '\n', 'utf8')
|
||||
console.log(`живой срез записан побочно: ${afterOut}`)
|
||||
}
|
||||
let entries = await readAllowedNew()
|
||||
const cliNew = arg('allow-new', '').split(',').map(s => nfc(s.trim())).filter(Boolean)
|
||||
if (cliNew.length) {
|
||||
const reason = arg('reason', '').trim()
|
||||
if (!reason) { console.error('нужен --reason <причина> вместе с --allow-new: объявление без причины не пишется'); process.exit(2) }
|
||||
const have = new Set(entries.map(e => e.basename))
|
||||
const fresh = cliNew.filter(x => !have.has(x))
|
||||
entries = entries.concat(fresh.map(basename => ({ basename, reason, added: new Date().toISOString().slice(0, 10) })))
|
||||
if (fresh.length) await writeAllowedNew(entries)
|
||||
console.log(`манифест допустимых появлений дополнен (${fresh.length} новых): ${fresh.join(', ') || '—'}`)
|
||||
}
|
||||
const allowNew = new Set(entries.map(e => e.basename))
|
||||
const reasonByName = new Map(entries.map(e => [e.basename, e.reason]))
|
||||
const b = new Set(before.basenames)
|
||||
const a = new Set(after.basenames)
|
||||
const missing = [...b].filter(x => !a.has(x)).sort()
|
||||
const added = [...a].filter(x => !b.has(x)).sort()
|
||||
const undeclared = added.filter(x => !allowNew.has(x))
|
||||
const declared = added.filter(x => allowNew.has(x))
|
||||
for (const name of declared) console.log(`ожидаемая новая (манифест): ${name} — ${reasonByName.get(name) || 'без причины'}`)
|
||||
if (missing.length === 0 && undeclared.length === 0) {
|
||||
console.log(`compare OK: пропавших нет, появившихся сверх объявленных нет (${b.size} имён до)`)
|
||||
process.exit(0)
|
||||
}
|
||||
for (const name of missing) console.log(`ПРОПАЛА: ${name}`)
|
||||
for (const name of undeclared) console.log(`ПОЯВИЛАСЬ (не объявлена): ${name}`)
|
||||
console.error(`compare FAIL: пропало ${missing.length}, появилось необъявленных ${undeclared.length}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// --- Сходимость замерщиков ---------------------------------------------------
|
||||
async function converge() {
|
||||
const vault = resolveVault()
|
||||
const run = spawnSync(process.execPath, [KB_LINT, '--json', '--limit=500', '--vault', vault], {
|
||||
encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' }, maxBuffer: 64 * 1024 * 1024
|
||||
})
|
||||
// kb-lint возвращает 1 при critical-находках — это не ошибка запуска, JSON всё равно в stdout.
|
||||
const raw = String(run.stdout || '')
|
||||
const start = raw.indexOf('{')
|
||||
const end = raw.lastIndexOf('}')
|
||||
if (start === -1 || end < start) {
|
||||
console.error('converge FAIL: kb-lint не вернул JSON')
|
||||
console.error(run.stderr || '')
|
||||
process.exit(1)
|
||||
}
|
||||
const lint = JSON.parse(raw.slice(start, end + 1))
|
||||
const lintCount = lint?.checks?.broken_wikilinks?.count
|
||||
if (typeof lintCount !== 'number') {
|
||||
console.error('converge FAIL: в JSON kb-lint нет checks.broken_wikilinks.count')
|
||||
process.exit(1)
|
||||
}
|
||||
const rough = await roughBrokenCount(vault)
|
||||
console.log(`kb-lint: битых wikilink = ${lintCount}`)
|
||||
console.log(`грубый: битых wikilink = ${rough.count}`)
|
||||
if (lintCount === rough.count) {
|
||||
console.log('converge OK: замерщики сошлись')
|
||||
process.exit(0)
|
||||
}
|
||||
const lintTargets = new Map((lint.checks.broken_wikilinks.worst || []).map(item => [item.target, item.count]))
|
||||
console.error(`converge FAIL: расхождение ${Math.abs(lintCount - rough.count)}`)
|
||||
for (const [target, count] of [...rough.targets.entries()].sort((x, y) => y[1] - x[1]).slice(0, 20)) {
|
||||
console.error(` грубый-only/расход: ${target} ×${count} (kb-lint worst: ${lintTargets.get(target) ?? '—'})`)
|
||||
}
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// --- Точка входа -------------------------------------------------------------
|
||||
if (flag('snapshot')) {
|
||||
const out = arg('out', '')
|
||||
if (!out) { console.error('нужен --out <file>'); process.exit(2) }
|
||||
await snapshot(out)
|
||||
} else if (arg('compare') || argv[0] === '--compare') {
|
||||
const rest = []
|
||||
for (let i = argv.indexOf('--compare') + 1; i < argv.length; i++) {
|
||||
if (argv[i] === '--allow-new' || argv[i] === '--reason' || argv[i] === '--after-out' || argv[i] === '--vault') { i++; continue }
|
||||
if (argv[i].startsWith('--allow-new=') || argv[i].startsWith('--reason=') || argv[i].startsWith('--after-out=')) continue
|
||||
if (argv[i].startsWith('--')) continue
|
||||
rest.push(argv[i])
|
||||
}
|
||||
if (rest.length > 1) {
|
||||
console.error('лишний позиционный аргумент: --compare [before]. after-слепок больше не участвует в сверке — живой срез снимается с диска самим --compare; побочный вывод — --after-out <file>')
|
||||
process.exit(2)
|
||||
}
|
||||
const beforePath = rest[0] || path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '.mnemazine', 'state', 'vault-hygiene-before.json')
|
||||
await compare(beforePath)
|
||||
} else if (flag('converge')) {
|
||||
await converge()
|
||||
} else {
|
||||
console.log(`mnemazine-vault-hygiene-check.mjs — прибор П15
|
||||
--snapshot --out <file> слепок vault (basename, sha256, веса, wikilinks, git status)
|
||||
--compare [before] basename before-слепка против ЖИВОГО диска (срез снимается
|
||||
самим --compare; иначе exit 1 с именами). Без аргумента before —
|
||||
.mnemazine/state/vault-hygiene-before.json; нет слепка → exit 2;
|
||||
допустимые новые — из .mnemazine/state/vault-hygiene-allowed-new.json
|
||||
--after-out <file> (с --compare) записать живой срез побочным слепком
|
||||
--allow-new <a,b,c> --reason <текст> (с --compare) дописать basename в манифест, не обход
|
||||
--converge kb-lint против грубого обхода: одно число битых wikilink (иначе exit 1)
|
||||
--vault <path> переопределить vault (дефолт — нейтральный, см. mnemazine-paths.mjs)`)
|
||||
process.exit(2)
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { MIN_CYR_SHARE, SPEC_TYPES, SPEC_SUBJECTS, SPEC_DATA_CLASSES, SPEC_VERIFIED, SPEC_VERIFIED_NORM, TYPE_REQUIRED_FIELDS, normSpecValue } from './mnemazine-note-spec.mjs'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
@@ -13,10 +12,49 @@ function arg(name, fallback = '') {
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
if (argv.includes('--help')) {
|
||||
console.log(`mnemazine-vault-quality-gate.mjs — гейт качества нот корпуса.
|
||||
Без --spec: маркеры сырья + обязательные секции. С --spec: строгая проверка NOTE-SPEC.
|
||||
Только читает корпус, ничего не пишет.
|
||||
|
||||
Использование: node scripts/mnemazine-vault-quality-gate.mjs [флаги] [файлы...]
|
||||
--vault <путь> корпус (иначе MNEMAZINE_VAULT или repo-local vault)
|
||||
--spec режим NOTE-SPEC (frontmatter enum, блоки, слаги проектов)
|
||||
--json отчёт в JSON
|
||||
--require-dossier требовать полное досье секций (старый режим)
|
||||
--changed-since <время> проверять только ноты, изменённые после отметки
|
||||
--max-failures N остановиться после N провалов
|
||||
--allow-empty разрешить зелёный на пустом наборе (иначе 0 проверенных — exit 2)
|
||||
--help эта справка
|
||||
|
||||
Коды возврата: 0 — чисто; 1 — есть провалы; 2 — пустой набор без --allow-empty
|
||||
или нечитаемый _ПРОЕКТЫ.md в режиме --spec.`)
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const SPEC_MODE = argv.includes('--spec')
|
||||
const JSON_OUT = argv.includes('--json')
|
||||
const REQUIRE_DOSSIER = argv.includes('--require-dossier')
|
||||
const CHANGED_SINCE = arg('changed-since', '')
|
||||
const MAX_FAILURES = Number(arg('max-failures', process.env.MNEMAZINE_QUALITY_MAX_FAILURES || '0'))
|
||||
// fail-closed: ноль проверенных нот (пустой/нечитаемый vault, или changed-since
|
||||
// не совпал ни с одним файлом) — это НЕ «сдано 0/0 ✓», а exit 2. Только явный
|
||||
// --allow-empty разрешает зелёный на пустом наборе.
|
||||
const ALLOW_EMPTY = argv.includes('--allow-empty')
|
||||
|
||||
// Flags whose value is the NEXT argv item — without this list positional
|
||||
// file arguments are indistinguishable from flag values.
|
||||
const VALUE_FLAGS = new Set(['--vault', '--changed-since', '--max-failures'])
|
||||
const FILE_ARGS = []
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]
|
||||
if (a.startsWith('--')) {
|
||||
if (VALUE_FLAGS.has(a)) i += 1
|
||||
continue
|
||||
}
|
||||
FILE_ARGS.push(path.resolve(a))
|
||||
}
|
||||
|
||||
function sinceMs(value) {
|
||||
if (!value) return 0
|
||||
@@ -62,6 +100,254 @@ async function walk(dir) {
|
||||
return out
|
||||
}
|
||||
|
||||
function isServicePath(rel) {
|
||||
// «99 Система» — служебная секция живого корпуса владельца; «00 System» — её
|
||||
// близнец в свежесобранном (публичном) корпусе, куда install.sh кладёт
|
||||
// «Mnemazine Protocol.md». Оба — сервис, не знание: NOTE-SPEC их не судит (П22).
|
||||
return (
|
||||
rel.includes('/graphify-out/') ||
|
||||
rel.includes('/_legacy-index ') ||
|
||||
rel.includes('/_архив-дублей/') ||
|
||||
rel.includes('/Capabilities/_') ||
|
||||
/^99 Система\//.test(rel) ||
|
||||
/^00 System\//.test(rel) ||
|
||||
/(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
|
||||
['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
|
||||
)
|
||||
}
|
||||
|
||||
// ── NOTE-SPEC (docs/NOTE-SPEC.md проекта mnemazine) — режим --spec ──
|
||||
|
||||
// «не-проверялось» добавлено 2026-07-25 по решению владельца: 1235 старых нот пришли без поля verified
|
||||
// или со значением false, и ни одно из пяти прежних значений не описывает «никто не проверял» — впихнуть
|
||||
// их в «источник-не-найден» значило бы записать в корпус ложь ради зелёного гейта.
|
||||
// НОВАЯ нота это значение носить не должна: конвейер верифицирует материал до записи (стадия 3).
|
||||
// ё/е считаются одной буквой при сравнении: «подтверждён» и «подтвержден» —
|
||||
// одно слово, а слаги проектов в нотах пишут в обеих орфографиях.
|
||||
const norm = s => normSpecValue(s)
|
||||
|
||||
function unquote(v) {
|
||||
const m = v.match(/^"(.*)"$/s) || v.match(/^'(.*)'$/s)
|
||||
return m ? m[1] : v
|
||||
}
|
||||
|
||||
// Минимальный YAML-подмножество-парсер: только то, что реально встречается во
|
||||
// frontmatter нот (скаляры, инлайн- и блок-списки). Незнакомая форма = провал,
|
||||
// потому что гейт fail-closed. Дубль ключа — провал (дубль YAML-ключа уже был
|
||||
// измеренной дырой: вторая строка молча побеждает первую).
|
||||
function parseFrontmatter(text) {
|
||||
const lines = text.split('\n')
|
||||
if (!/^---\s*$/.test(lines[0] ?? '')) return { error: 'файл не начинается с ---', body: text }
|
||||
let close = -1
|
||||
for (let i = 1; i < lines.length; i++) {
|
||||
if (/^---\s*$/.test(lines[i])) { close = i; break }
|
||||
}
|
||||
if (close === -1) return { error: 'frontmatter не закрыт второй строкой ---', body: text }
|
||||
const body = lines.slice(close + 1).join('\n')
|
||||
const data = {}
|
||||
let listKey = null
|
||||
for (let i = 1; i < close; i++) {
|
||||
const line = lines[i].replace(/\r$/, '')
|
||||
if (!line.trim() || line.trim().startsWith('#')) continue
|
||||
const kv = line.match(/^([\w.-]+):(?:\s+(.*))?$/)
|
||||
if (kv) {
|
||||
const key = kv[1]
|
||||
if (Object.hasOwn(data, key)) return { error: `дубль ключа «${key}» во frontmatter`, body }
|
||||
const raw = (kv[2] ?? '').trim()
|
||||
if (!raw) {
|
||||
data[key] = []
|
||||
listKey = key
|
||||
} else if (/^\[.*\]$/.test(raw)) {
|
||||
data[key] = raw.slice(1, -1).split(',').map(s => unquote(s.trim())).filter(Boolean)
|
||||
listKey = null
|
||||
} else {
|
||||
data[key] = unquote(raw)
|
||||
listKey = null
|
||||
}
|
||||
continue
|
||||
}
|
||||
const item = line.match(/^\s*-\s+(.*)$/)
|
||||
if (item && listKey) {
|
||||
data[listKey].push(unquote(item[1].trim()))
|
||||
continue
|
||||
}
|
||||
if (/^\s/.test(line)) continue
|
||||
return { error: `непарсибельная строка frontmatter ${i + 1}: «${line.slice(0, 60)}»`, body }
|
||||
}
|
||||
return { data, body }
|
||||
}
|
||||
|
||||
const scalar = v => (Array.isArray(v) ? '' : String(v ?? '').trim())
|
||||
|
||||
function cyrillicShare(body) {
|
||||
const prose = body
|
||||
.replace(/```[\s\S]*?```/g, ' ')
|
||||
.replace(/`[^`\n]*`/g, ' ')
|
||||
.replace(/https?:\/\/\S+/g, ' ')
|
||||
const cyr = (prose.match(/[А-Яа-яЁё]/g) || []).length
|
||||
const lat = (prose.match(/[A-Za-z]/g) || []).length
|
||||
return { cyr, lat, share: cyr + lat ? cyr / (cyr + lat) : 0 }
|
||||
}
|
||||
|
||||
function sectionBody(body, headingRe) {
|
||||
const lines = body.split('\n')
|
||||
const start = lines.findIndex(l => headingRe.test(l))
|
||||
if (start === -1) return null
|
||||
const out = []
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
if (/^##\s/.test(lines[i])) break
|
||||
out.push(lines[i])
|
||||
}
|
||||
return out.join('\n')
|
||||
}
|
||||
|
||||
// Источник засчитывается ТОЛЬКО структурно (план П06 шаг 3): непустое значение
|
||||
// source: во frontmatter ИЛИ заголовок Source/Источник с непустым телом. Голая
|
||||
// подстрока source: в теле файла, в кодовом блоке или в цитате источником не считается.
|
||||
function hasStructuredSource(text) {
|
||||
const fm = parseFrontmatter(text)
|
||||
const fmSource = fm.data?.source
|
||||
const fmSourceOk = Array.isArray(fmSource) ? fmSource.some(s => String(s).trim()) : Boolean(scalar(fmSource))
|
||||
if (fmSourceOk) return true
|
||||
// (?:\s|$), не \b: JS \b — ASCII-only, после кириллицы («Источники») не срабатывает.
|
||||
const heading = sectionBody(fm.body ?? text, /^#{2,}\s+(Source|Sources|Источник|Источники)(?:\s|$)/i)
|
||||
return heading !== null && heading.trim().length > 0
|
||||
}
|
||||
|
||||
// Слаги проектов — только грепом ## заголовков _ПРОЕКТЫ.md, не хардкод.
|
||||
// Однословные имена проектов покрыты полным заголовком;
|
||||
// из многословных дополнительно берутся «кавычечные» имена и латинские токены
|
||||
// ≥5 символов — кириллические токены («Просто»,
|
||||
// «партнеры») дают ложные совпадения с обычной прозой, поэтому исключены.
|
||||
function projectSlugs(text) {
|
||||
const slugs = new Set()
|
||||
for (const [, h] of text.matchAll(/^##\s+(.+?)\s*$/gm)) {
|
||||
slugs.add(norm(h))
|
||||
for (const [, q] of h.matchAll(/«([^»]+)»/g)) slugs.add(norm(q))
|
||||
for (const t of h.split(/\s+/)) {
|
||||
const tok = t.replace(/[«»()"'.,:;]/g, '')
|
||||
if (tok.length >= 5 && /[A-Za-z]/.test(tok)) slugs.add(norm(tok))
|
||||
}
|
||||
}
|
||||
return [...slugs]
|
||||
}
|
||||
|
||||
function checkSpec(text, slugs, changedSince = false) {
|
||||
const reasons = []
|
||||
const fm = parseFrontmatter(text)
|
||||
if (fm.error) reasons.push(`frontmatter: ${fm.error}`)
|
||||
else {
|
||||
const data = fm.data
|
||||
const source = data.source
|
||||
const sourceOk = Array.isArray(source) ? source.some(s => String(s).trim()) : Boolean(scalar(source))
|
||||
if (!sourceOk) reasons.push('source: пуст или отсутствует')
|
||||
const type = scalar(data.type)
|
||||
if (!SPEC_TYPES.has(type)) reasons.push(`type: «${type || '—'}» вне enum спеки (${[...SPEC_TYPES].join(' | ')})`)
|
||||
const verifiedRaw = scalar(data.verified)
|
||||
if (!SPEC_VERIFIED_NORM.has(norm(verifiedRaw))) reasons.push(`verified: «${verifiedRaw || '—'}» вне enum спеки (${SPEC_VERIFIED.join(' | ')})`)
|
||||
for (const key of TYPE_REQUIRED_FIELDS[type] || []) {
|
||||
const v = data[key]
|
||||
const ok = Array.isArray(v) ? v.length > 0 : Boolean(scalar(v))
|
||||
if (!ok) reasons.push(`type: ${type} требует непустое поле ${key}`)
|
||||
}
|
||||
// subject (мастер §18): нота различает «факт о мире» и «факт обо мне».
|
||||
// (а) значение вне закрытого списка → провал ВСЕГДА;
|
||||
// (б) отсутствие поля → провал ТОЛЬКО в проходах с --changed-since (новая нота
|
||||
// обязана нести поле; старый корпус до переогранки П16 за отсутствие не карается);
|
||||
// (в) subject: self при source_type video|article|repo → self-нота с чужим источником (§18.4).
|
||||
const subject = scalar(data.subject)
|
||||
if (subject) {
|
||||
if (!SPEC_SUBJECTS.has(subject)) {
|
||||
reasons.push(`subject: «${subject}» вне закрытого списка (${[...SPEC_SUBJECTS].join(' | ')})`)
|
||||
} else if (subject === 'self') {
|
||||
const sourceType = scalar(data.source_type)
|
||||
if (['video', 'article', 'repo'].includes(sourceType)) reasons.push(`subject: self при source_type: ${sourceType} — self-нота с чужим источником (§18.4)`)
|
||||
}
|
||||
} else if (changedSince) {
|
||||
reasons.push('subject: отсутствует (обязателен для новой/изменённой ноты)')
|
||||
}
|
||||
|
||||
// data_class (§17.8, П24): необязательное; если есть — из закрытого списка
|
||||
// config/data-classes.json. Отсутствие дефектом НЕ считается — класс тогда
|
||||
// берут правила по разделу и наследование от источника (machine-class-gate).
|
||||
const dataClass = scalar(data.data_class)
|
||||
if (dataClass && SPEC_DATA_CLASSES && !SPEC_DATA_CLASSES.has(dataClass)) {
|
||||
reasons.push(`data_class: «${dataClass}» вне закрытого списка config/data-classes.json (${[...SPEC_DATA_CLASSES].join(' | ')})`)
|
||||
}
|
||||
}
|
||||
const body = fm.body
|
||||
const { cyr, lat, share } = cyrillicShare(body)
|
||||
if (share < MIN_CYR_SHARE) reasons.push(`кириллица ${(share * 100).toFixed(1)}% прозы (< 30%): ${cyr} кир. против ${lat} лат. букв`)
|
||||
const help = sectionBody(body, /^#{2,3}\s+(?:🎯\s*)?Как (?:это )?поможет мне\s*$/)
|
||||
if (help === null) reasons.push('нет блока «Как это поможет мне»')
|
||||
else {
|
||||
const normHelp = norm(help)
|
||||
if (!slugs.some(s => normHelp.includes(s))) reasons.push('блок «Как это поможет мне» не упоминает ни один проект из «99 Система/_ПРОЕКТЫ.md»')
|
||||
}
|
||||
const dost = sectionBody(body, /^##\s+Достоверность\s*$/)
|
||||
if (dost === null) reasons.push('нет блока «Достоверность»')
|
||||
else if (!dost.trim()) reasons.push('блок «Достоверность» пуст')
|
||||
return reasons
|
||||
}
|
||||
|
||||
if (SPEC_MODE) {
|
||||
const projectsFile = path.join(VAULT, '99 Система', '_ПРОЕКТЫ.md')
|
||||
// fail-closed: файла проектов нет или он нечитаем → exit 2, а не стек-трейс ENOENT
|
||||
// и код 1. Без списка слагов гейт не может судить блок «Как это поможет мне».
|
||||
let projectsText
|
||||
try {
|
||||
projectsText = await fs.readFile(projectsFile, 'utf8')
|
||||
} catch (error) {
|
||||
console.error(`Не прочитан ${projectsFile} (${error.code || error.message}) — режим --spec судить корпус не может`)
|
||||
process.exit(2)
|
||||
}
|
||||
const slugs = projectSlugs(projectsText)
|
||||
if (!slugs.length) {
|
||||
console.error(`Ни одного ## заголовка в ${projectsFile} — гейт не может судить блок «Как это поможет мне»`)
|
||||
process.exit(2)
|
||||
}
|
||||
let targets = FILE_ARGS
|
||||
if (!targets.length) {
|
||||
targets = []
|
||||
for (const file of await walk(VAULT)) {
|
||||
if (isServicePath(path.relative(VAULT, file))) continue
|
||||
if (CHANGED_SINCE_MS && (await fs.stat(file)).mtimeMs < CHANGED_SINCE_MS) continue
|
||||
targets.push(file)
|
||||
}
|
||||
}
|
||||
const failures = []
|
||||
let checked = 0
|
||||
for (const file of targets) {
|
||||
checked += 1
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
// Naming files explicitly means "check these fresh/touched notes", same
|
||||
// contract as --changed-since. Without this the subject rule (§18) stayed
|
||||
// silent in per-file mode and 64 notes shipped without `subject:`.
|
||||
const reasons = checkSpec(text, slugs, CHANGED_SINCE_MS > 0 || FILE_ARGS.length > 0)
|
||||
if (reasons.length) {
|
||||
failures.push({ file: path.relative(VAULT, file), reasons })
|
||||
if (MAX_FAILURES > 0 && failures.length >= MAX_FAILURES) break
|
||||
}
|
||||
}
|
||||
if (checked === 0 && !ALLOW_EMPTY) {
|
||||
console.error('vault пуст или нечитаем: 0 проверенных (--allow-empty чтобы разрешить)')
|
||||
process.exit(2)
|
||||
}
|
||||
const report = { ok: failures.length === 0, mode: 'spec', checked, failures }
|
||||
if (JSON_OUT) {
|
||||
;(failures.length ? console.error : console.log)(JSON.stringify(report, null, 2))
|
||||
} else {
|
||||
for (const f of failures) {
|
||||
console.error(`FAIL ${f.file}`)
|
||||
for (const r of f.reasons) console.error(` - ${r}`)
|
||||
}
|
||||
;(failures.length ? console.error : console.log)(`spec: проверено ${checked}, провалов ${failures.length}`)
|
||||
}
|
||||
process.exit(failures.length ? 1 : 0)
|
||||
}
|
||||
|
||||
// ── Старый режим (без --spec): маркеры сырья + обязательные секции ──
|
||||
|
||||
const files = await walk(VAULT)
|
||||
const failures = []
|
||||
let checked = 0
|
||||
@@ -69,22 +355,18 @@ for (const file of files) {
|
||||
const stat = await fs.stat(file)
|
||||
if (CHANGED_SINCE_MS && stat.mtimeMs < CHANGED_SINCE_MS) continue
|
||||
const rel = path.relative(VAULT, file)
|
||||
if (
|
||||
rel.includes('/graphify-out/') ||
|
||||
rel.includes('/_legacy-index ') ||
|
||||
rel.includes('/_архив-дублей/') ||
|
||||
rel.includes('/Capabilities/_') ||
|
||||
/^99 Система\//.test(rel) ||
|
||||
/(^|\/)_(Содержание|МАСТЕР-ИНДЕКС|ROUTING|ШАБЛОНЫ)\.md$/.test(rel) ||
|
||||
['AGENTS.md', 'CLAUDE.md', '_ROUTING.md', 'Лог обработки.md'].includes(rel)
|
||||
) continue
|
||||
if (isServicePath(rel)) continue
|
||||
checked += 1
|
||||
const text = await fs.readFile(file, 'utf8')
|
||||
if (/^##\s+Атомизировано(?:\s|$)/m.test(text)) continue
|
||||
// «## Атомизировано» больше НЕ освобождает ноту от суда (план П06 шаг 1):
|
||||
// сырьё (badMarkers), отсутствие источника и смыслового блока валят её как любую
|
||||
// другую. Единственное смягчение — при --require-dossier такая нота не обязана
|
||||
// нести шесть секций старого досье: это другой формат, а не индульгенция.
|
||||
const atomized = /^##\s+Атомизировано(?:\s|$)/m.test(text)
|
||||
const hit = badMarkers.find(re => re.test(text))
|
||||
const hasSource = /#{2,}\s+(Source|Sources|Источник|Источники|Источники и подтверждения)(?:\s|$)|source:/i.test(text)
|
||||
const hasMeaning = /#{2,}\s+(What This Is|Что это|Что это и зачем|Суть|Полное объяснение)(?:\s|$)/i.test(text)
|
||||
const missingDossier = REQUIRE_DOSSIER
|
||||
const hasSource = hasStructuredSource(text)
|
||||
const hasMeaning = /#{2,}\s+(What This Is|Что это|Что это и зачем|Суть|Полное объяснение|Короткий ответ|Короткий вывод|Кратко|Главное|Главный вывод)(?:\s|$)/i.test(text)
|
||||
const missingDossier = (REQUIRE_DOSSIER && !atomized)
|
||||
? [
|
||||
['Короткий ответ', /^##\s+Короткий ответ(?:\s|$)/m],
|
||||
['Полное объяснение', /^##\s+Полное объяснение(?:\s|$)/m],
|
||||
@@ -100,6 +382,11 @@ for (const file of files) {
|
||||
}
|
||||
}
|
||||
|
||||
if (checked === 0 && !ALLOW_EMPTY) {
|
||||
console.error('vault пуст или нечитаем: 0 проверенных (--allow-empty чтобы разрешить)')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
if (failures.length) {
|
||||
console.error(JSON.stringify({ ok: false, checked, total: files.length, scope: CHANGED_SINCE_MS ? { changed_since: new Date(CHANGED_SINCE_MS).toISOString() } : { changed_since: null }, failures }, null, 2))
|
||||
process.exit(1)
|
||||
|
||||
@@ -141,7 +141,7 @@ ${fenceUntrusted('CLAIM', String(claim).slice(0, 4000))}
|
||||
|
||||
SOURCES:
|
||||
${live.length ? live.join('\n') : '(none reachable)'}`
|
||||
const res = await llmJson(prompt, VERIFY_SCHEMA, { timeoutMs: options.llmTimeoutMs, provider: options.provider, tools: ['WebSearch', 'WebFetch'] })
|
||||
const res = await llmJson(prompt, VERIFY_SCHEMA, { timeoutMs: options.llmTimeoutMs, provider: options.provider, tools: ['WebSearch', 'WebFetch'], label: options.label || 'verify:claim' })
|
||||
let status = ['verified', 'assumed', 'unknown'].includes(res?.status) ? res.status : 'unknown'
|
||||
if (status === 'verified' && !live.length) status = 'unknown'
|
||||
const checked = Array.isArray(res?.checked) ? res.checked.filter(isPublicHttpUrl) : []
|
||||
|
||||
@@ -22,7 +22,8 @@ function arg(name, fallback = '') {
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
const VAULT = resolveVault({ cli: arg('vault') })
|
||||
const SELFTEST = argv.includes('--selftest')
|
||||
const VAULT = SELFTEST ? '' : resolveVault({ cli: arg('vault') })
|
||||
// Default state dir matches README:224 (~/Desktop/Mnemazine/.mnemazine/state),
|
||||
// the canonical pickup for the weekly-brief export. Override with MNEMAZINE_STATE
|
||||
// / --state-dir, or point --state straight at the downloaded file.
|
||||
@@ -110,7 +111,7 @@ function spawnRunner(root) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (argv.includes('--selftest')) return selftest()
|
||||
if (SELFTEST) return selftest()
|
||||
const state = JSON.parse(await fs.readFile(STATE_FILE, 'utf8').catch(() => '{}'))
|
||||
const result = { read: 0, work: 0, forget: 0, missing: 0, invalid: 0 }
|
||||
for (const [id, action] of Object.entries(state)) {
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
#!/usr/bin/env node
|
||||
import { promises as fs } from 'node:fs'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import os from 'node:os'
|
||||
import { resolveVault } from './mnemazine-paths.mjs'
|
||||
|
||||
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
|
||||
const argv = process.argv.slice(2)
|
||||
|
||||
function arg(name, fallback = '') {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
return hit.includes('=') ? hit.split('=').slice(1).join('=') : argv[argv.indexOf(hit) + 1] || fallback
|
||||
}
|
||||
|
||||
function flag(name) {
|
||||
return argv.includes(`--${name}`)
|
||||
}
|
||||
|
||||
function norm(value) {
|
||||
return String(value || '')
|
||||
.replace(/\\+$/g, '')
|
||||
.replace(/\.md$/i, '')
|
||||
.replace(/[—–]/g, '-')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function stripDate(value) {
|
||||
return norm(value)
|
||||
.replace(/^\d{4}-\d{2}-\d{2}\s*[-—–]\s*/, '')
|
||||
.replace(/-\d+$/, '')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function frontmatterValue(text, key) {
|
||||
const match = text.match(new RegExp(`^${key}:\\s*(.+)$`, 'm'))
|
||||
if (!match) return ''
|
||||
return match[1].trim().replace(/^['"]|['"]$/g, '')
|
||||
}
|
||||
|
||||
function frontmatterAliases(text) {
|
||||
const out = []
|
||||
const inline = text.match(/^aliases:\s*\[([^\]]+)\]/m)
|
||||
if (inline) out.push(...inline[1].split(',').map(item => item.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean))
|
||||
const block = text.match(/^aliases:\s*\n((?:\s+-\s+.+\n?)+)/m)
|
||||
if (block) {
|
||||
out.push(...block[1].split('\n')
|
||||
.map(line => line.replace(/^\s+-\s+/, '').trim().replace(/^['"]|['"]$/g, ''))
|
||||
.filter(Boolean))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function addIndex(index, key, file) {
|
||||
const normalized = norm(key)
|
||||
if (!normalized) return
|
||||
if (!index.has(normalized)) index.set(normalized, new Set())
|
||||
index.get(normalized).add(file)
|
||||
}
|
||||
|
||||
function targetParts(raw) {
|
||||
const display = String(raw || '').trim()
|
||||
const target = display.split('|')[0].split('#')[0].split('^')[0].trim()
|
||||
return { display, target, normalized: norm(target) }
|
||||
}
|
||||
|
||||
function linkScanText(text) {
|
||||
return String(text || '')
|
||||
.replace(/```[\s\S]*?```/g, block => block.replace(/[^\n]/g, ' '))
|
||||
.replace(/`[^`\n]*`/g, block => ' '.repeat(block.length))
|
||||
}
|
||||
|
||||
function sectionOf(file) {
|
||||
return file.includes('/') ? file.split('/')[0] : '(root)'
|
||||
}
|
||||
|
||||
function classifyTarget(target) {
|
||||
const clean = target.trim()
|
||||
if (!clean || ['...', '…', 'note', 'Название'].includes(clean)) return 'placeholder'
|
||||
if (/\\$/.test(clean)) return 'escaped-link'
|
||||
if (/\.(pdf|docx?|xlsx?|pptx?|png|jpe?g|webp|heic|mov|mp4|canvas)$/i.test(clean)) return 'file-or-asset'
|
||||
if (clean.includes('/')) return 'path-link'
|
||||
if (/^[A-ZА-ЯЁ0-9 _-]{2,}$/i.test(clean) && clean.length <= 40) return 'concept'
|
||||
return 'missing-note'
|
||||
}
|
||||
|
||||
function suggestedAction(kind) {
|
||||
if (kind === 'placeholder') return 'удалить placeholder или заменить на реальную заметку'
|
||||
if (kind === 'escaped-link') return 'убрать лишний escape/backslash или пересобрать индекс'
|
||||
if (kind === 'file-or-asset') return 'заменить wiki-link на обычный путь/markdown-link или создать заметку-обёртку'
|
||||
if (kind === 'path-link') return 'уточнить путь до существующей заметки или заменить на текстовую ссылку'
|
||||
if (kind === 'concept') return 'создать короткую понятиевую заметку или заменить на обычный текст'
|
||||
return 'найти новое имя заметки, создать мост или удалить ссылку'
|
||||
}
|
||||
|
||||
function yamlString(value) {
|
||||
return JSON.stringify(String(value || ''))
|
||||
}
|
||||
|
||||
function safeRelTarget(target) {
|
||||
const clean = targetParts(target).target
|
||||
if (!clean || clean.startsWith('/') || clean.split('/').some(part => part === '..')) return ''
|
||||
return `${clean.replace(/\.md$/i, '')}.md`
|
||||
}
|
||||
|
||||
function bridgeTitle(target) {
|
||||
return path.basename(targetParts(target).target).replace(/\.md$/i, '') || 'Wiki link bridge'
|
||||
}
|
||||
|
||||
function shouldPlainText(target, kind) {
|
||||
const clean = targetParts(target).target
|
||||
return kind === 'placeholder' ||
|
||||
kind === 'escaped-link' ||
|
||||
kind === 'file-or-asset' ||
|
||||
clean.startsWith('artifacts/') ||
|
||||
/(?:^|[\s"`])[$][A-Z_]+/.test(clean) ||
|
||||
/[<>=~]/.test(clean)
|
||||
}
|
||||
|
||||
function plainReplacement(target, kind) {
|
||||
const clean = targetParts(target).target.replace(/\\+$/g, '').trim()
|
||||
if (kind === 'placeholder') return clean === '…' ? '...' : clean
|
||||
if (kind === 'file-or-asset' || clean.startsWith('artifacts/')) return `\`${clean}\``
|
||||
if (/[<>=~]/.test(clean)) return `\`${clean}\``
|
||||
return clean
|
||||
}
|
||||
|
||||
function bridgeNote(target, kind) {
|
||||
const clean = targetParts(target).target.replace(/\\+$/g, '').trim()
|
||||
const title = bridgeTitle(clean)
|
||||
const isPath = clean.includes('/')
|
||||
const aliasLines = [...new Set([clean, title, stripDate(title)].filter(Boolean))]
|
||||
.map(alias => ` - ${yamlString(alias)}`)
|
||||
.join('\n')
|
||||
const noteKind = isPath ? 'точного пути' : kind === 'concept' ? 'понятия' : 'старой ссылки'
|
||||
return `---
|
||||
title: ${yamlString(title)}
|
||||
type: "knowledge-note"
|
||||
source_type: "wiki-link-bridge"
|
||||
source_ref: "wiki-link-cleanup:${new Date().toISOString().slice(0, 10)}"
|
||||
verified: false
|
||||
verification_status: "unknown"
|
||||
status: "bridge"
|
||||
aliases:
|
||||
${aliasLines}
|
||||
---
|
||||
|
||||
# ${title}
|
||||
|
||||
## Что это
|
||||
|
||||
Это мостовая заметка для ${noteKind} \`${clean}\`. Она нужна, чтобы старая wiki-ссылка в базе знаний вела в живой узел, а не оставалась битой.
|
||||
|
||||
## Зачем это нужно
|
||||
|
||||
В vault много исторических ссылок из digest, старых заметок и автоматических синтезов. Мост сохраняет навигацию и не выдаёт себя за новый проверенный источник.
|
||||
|
||||
## Как использовать
|
||||
|
||||
- Если тема стала рабочей, заменить этот мост полноценной заметкой.
|
||||
- Если ссылка была только техническим хвостом digest, оставить мост как совместимость.
|
||||
- Если рядом найдена лучшая целевая заметка, перенести alias туда и удалить этот мост.
|
||||
|
||||
## Источники
|
||||
|
||||
- Внутренний отчёт Mnemazine: \`npm run wiki:links\`.
|
||||
- Тип цели: \`${kind}\`.
|
||||
- Исходная цель: \`${clean}\`.
|
||||
|
||||
## Проверка
|
||||
|
||||
Статус: навигационный мост, внешняя факт-проверка не требуется. Содержательные утверждения надо брать из связанных заметок, не из этого файла.
|
||||
|
||||
## Связанные заметки
|
||||
|
||||
- Протокол Мнемозина.
|
||||
|
||||
## Следующее действие
|
||||
|
||||
При ближайшей ручной чистке заменить мост на полноценный атом знания или привязать alias к существующей заметке.
|
||||
`
|
||||
}
|
||||
|
||||
async function rewritePlainLinks(vault, targets) {
|
||||
const changes = []
|
||||
const byFile = new Map()
|
||||
for (const target of targets) {
|
||||
for (const example of target.examples || []) {
|
||||
const rel = example.file
|
||||
if (!byFile.has(rel)) byFile.set(rel, [])
|
||||
byFile.get(rel).push({ display: example.display, target: target.target, kind: target.kind })
|
||||
}
|
||||
}
|
||||
|
||||
for (const [rel, items] of byFile) {
|
||||
const file = path.join(vault, rel)
|
||||
let text = await fs.readFile(file, 'utf8')
|
||||
const before = text
|
||||
for (const item of items) {
|
||||
const escapedDisplay = item.display.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
||||
text = text.replace(new RegExp(`\\[\\[${escapedDisplay}\\]\\]`, 'g'), plainReplacement(item.target, item.kind))
|
||||
}
|
||||
text = text.replace(/\[\[([^\]\n]*?)\\+\]\]/g, (_, inner) => `[[${inner.trim()}]]`)
|
||||
if (text !== before) {
|
||||
await fs.writeFile(file, text, 'utf8')
|
||||
changes.push(rel)
|
||||
}
|
||||
}
|
||||
return changes
|
||||
}
|
||||
|
||||
async function createBridgeNotes(vault, targets) {
|
||||
const created = []
|
||||
const skipped = []
|
||||
for (const target of targets) {
|
||||
if (shouldPlainText(target.target, target.kind)) continue
|
||||
const rel = target.target.includes('/')
|
||||
? safeRelTarget(target.target)
|
||||
: path.posix.join('99 Система', 'Wiki Link Bridges', `${bridgeTitle(target.target)}.md`)
|
||||
if (!rel) {
|
||||
skipped.push({ target: target.target, reason: 'unsafe path' })
|
||||
continue
|
||||
}
|
||||
const file = path.join(vault, rel)
|
||||
if (existsSync(file)) {
|
||||
skipped.push({ target: target.target, reason: 'exists', file: rel })
|
||||
continue
|
||||
}
|
||||
await fs.mkdir(path.dirname(file), { recursive: true })
|
||||
await fs.writeFile(file, bridgeNote(target.target, target.kind), 'utf8')
|
||||
created.push(rel)
|
||||
}
|
||||
return { created, skipped }
|
||||
}
|
||||
|
||||
async function applyCleanup({ vault, reportsDir, limit }) {
|
||||
const first = await runAudit({ vault, reportsDir, limit })
|
||||
const targets = first.report.targets
|
||||
const plainTargets = targets.filter(item => shouldPlainText(item.target, item.kind))
|
||||
const rewritten = await rewritePlainLinks(vault, plainTargets)
|
||||
const mid = await runAudit({ vault, reportsDir, limit })
|
||||
const bridges = await createBridgeNotes(vault, mid.report.targets)
|
||||
const second = await runAudit({ vault, reportsDir, limit })
|
||||
return { before: first.report.broken, after: second.report.broken, rewritten, bridges, report: second }
|
||||
}
|
||||
|
||||
async function collectVault(vault) {
|
||||
const files = []
|
||||
const dirs = new Set([''])
|
||||
|
||||
async function walk(dir) {
|
||||
for (const item of await fs.readdir(dir, { withFileTypes: true }).catch(() => [])) {
|
||||
if (['.git', '.obsidian', '.mnemazine'].includes(item.name) || item.name.startsWith('graphify-out')) continue
|
||||
const file = path.join(dir, item.name)
|
||||
const rel = path.relative(vault, file).replace(/\\/g, '/')
|
||||
if (item.isDirectory()) {
|
||||
dirs.add(rel)
|
||||
await walk(file)
|
||||
} else if (item.isFile() && item.name.endsWith('.md')) {
|
||||
files.push(file)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await walk(vault)
|
||||
return { files, dirs }
|
||||
}
|
||||
|
||||
function buildIndex(vault, files, dirs) {
|
||||
const index = new Map()
|
||||
for (const file of files) {
|
||||
const rel = path.relative(vault, file).replace(/\\/g, '/')
|
||||
const withoutExt = rel.replace(/\.md$/, '')
|
||||
const basename = path.basename(withoutExt)
|
||||
const text = linkScanText(readFileSync(file, 'utf8'))
|
||||
for (const key of [
|
||||
rel,
|
||||
withoutExt,
|
||||
basename,
|
||||
stripDate(basename),
|
||||
frontmatterValue(text, 'title'),
|
||||
...frontmatterAliases(text)
|
||||
]) {
|
||||
addIndex(index, key, rel)
|
||||
}
|
||||
}
|
||||
return { index, dirs }
|
||||
}
|
||||
|
||||
function targetExists(target, wiki) {
|
||||
const { normalized } = targetParts(target)
|
||||
if (!normalized || normalized.startsWith('#') || /^https?:\/\//i.test(normalized)) return true
|
||||
if (wiki.dirs.has(normalized) || wiki.index.has(normalized)) return true
|
||||
const basename = path.basename(normalized)
|
||||
return wiki.index.has(basename) || wiki.index.has(stripDate(basename))
|
||||
}
|
||||
|
||||
function collectBrokenLinks(vault, files, wiki) {
|
||||
const byTarget = new Map()
|
||||
const bySection = new Map()
|
||||
const byFile = new Map()
|
||||
const linkRe = /\[\[([^\]\n]+)\]\]/g
|
||||
let totalLinks = 0
|
||||
|
||||
for (const file of files) {
|
||||
const rel = path.relative(vault, file).replace(/\\/g, '/')
|
||||
const text = linkScanText(readFileSync(file, 'utf8'))
|
||||
let match
|
||||
while ((match = linkRe.exec(text))) {
|
||||
totalLinks += 1
|
||||
const { display, target } = targetParts(match[1])
|
||||
if (targetExists(target, wiki)) continue
|
||||
|
||||
const line = text.slice(0, match.index).split('\n').length
|
||||
const kind = classifyTarget(target)
|
||||
const hit = { file: rel, line, target, display, section: sectionOf(rel), kind }
|
||||
|
||||
if (!byTarget.has(target)) byTarget.set(target, { target, kind, action: suggestedAction(kind), count: 0, files: new Set(), examples: [] })
|
||||
const group = byTarget.get(target)
|
||||
group.count += 1
|
||||
group.files.add(rel)
|
||||
if (group.examples.length < 5) group.examples.push({ file: rel, line, display })
|
||||
|
||||
if (!bySection.has(hit.section)) bySection.set(hit.section, { section: hit.section, count: 0, targets: new Set(), files: new Set() })
|
||||
const sec = bySection.get(hit.section)
|
||||
sec.count += 1
|
||||
sec.targets.add(target)
|
||||
sec.files.add(rel)
|
||||
|
||||
if (!byFile.has(rel)) byFile.set(rel, { file: rel, section: hit.section, count: 0, targets: [] })
|
||||
const fileGroup = byFile.get(rel)
|
||||
fileGroup.count += 1
|
||||
if (fileGroup.targets.length < 20) fileGroup.targets.push({ line, target, kind })
|
||||
}
|
||||
}
|
||||
|
||||
const targets = [...byTarget.values()]
|
||||
.map(item => ({ ...item, files: [...item.files], file_count: item.files.size }))
|
||||
.sort((a, b) => b.count - a.count || a.target.localeCompare(b.target))
|
||||
const sections = [...bySection.values()]
|
||||
.map(item => ({ section: item.section, count: item.count, unique_targets: item.targets.size, files: item.files.size }))
|
||||
.sort((a, b) => b.count - a.count || a.section.localeCompare(b.section))
|
||||
const filesOut = [...byFile.values()]
|
||||
.sort((a, b) => b.count - a.count || a.file.localeCompare(b.file))
|
||||
|
||||
return { totalLinks, targets, sections, files: filesOut }
|
||||
}
|
||||
|
||||
function renderMarkdown(report, limit) {
|
||||
const lines = []
|
||||
lines.push(`# Wiki-link cleanup — ${report.date}`, '')
|
||||
lines.push('## Сводка', '')
|
||||
lines.push(`- Vault: \`${report.vault}\``)
|
||||
lines.push(`- Markdown files: ${report.checked.markdown_files}`)
|
||||
lines.push(`- Wiki links scanned: ${report.checked.wiki_links}`)
|
||||
lines.push(`- Broken links: ${report.broken.total}`)
|
||||
lines.push(`- Unique targets: ${report.broken.unique_targets}`)
|
||||
lines.push(`- Files with broken links: ${report.broken.files}`)
|
||||
lines.push('')
|
||||
lines.push('## Разделы', '')
|
||||
for (const section of report.sections.slice(0, limit)) {
|
||||
lines.push(`- ${section.section}: ${section.count} links · ${section.unique_targets} targets · ${section.files} files`)
|
||||
}
|
||||
lines.push('', '## Очередь по целям', '')
|
||||
for (const target of report.targets.slice(0, limit)) {
|
||||
lines.push(`### ${target.target}`)
|
||||
lines.push('')
|
||||
lines.push(`- Тип: ${target.kind}`)
|
||||
lines.push(`- Вхождений: ${target.count}`)
|
||||
lines.push(`- Файлов: ${target.file_count}`)
|
||||
lines.push(`- Действие: ${target.action}`)
|
||||
lines.push('- Примеры:')
|
||||
for (const example of target.examples) lines.push(` - \`${example.file}:${example.line}\` — \`[[${example.display}]]\``)
|
||||
lines.push('')
|
||||
}
|
||||
lines.push('## Очередь по файлам', '')
|
||||
for (const file of report.files.slice(0, limit)) {
|
||||
lines.push(`### ${file.file}`)
|
||||
lines.push('')
|
||||
lines.push(`- Broken links: ${file.count}`)
|
||||
for (const target of file.targets.slice(0, 10)) lines.push(`- L${target.line}: \`[[${target.target}]]\` (${target.kind})`)
|
||||
lines.push('')
|
||||
}
|
||||
return `${lines.join('\n').trim()}\n`
|
||||
}
|
||||
|
||||
async function runAudit({ vault, reportsDir, limit }) {
|
||||
const { files, dirs } = await collectVault(vault)
|
||||
const wiki = buildIndex(vault, files, dirs)
|
||||
const broken = collectBrokenLinks(vault, files, wiki)
|
||||
const date = new Date().toISOString().slice(0, 10)
|
||||
const report = {
|
||||
ok: true,
|
||||
date,
|
||||
vault,
|
||||
checked: {
|
||||
markdown_files: files.length,
|
||||
wiki_links: broken.totalLinks
|
||||
},
|
||||
broken: {
|
||||
total: broken.targets.reduce((sum, item) => sum + item.count, 0),
|
||||
unique_targets: broken.targets.length,
|
||||
files: broken.files.length
|
||||
},
|
||||
sections: broken.sections,
|
||||
targets: broken.targets,
|
||||
files: broken.files
|
||||
}
|
||||
|
||||
await fs.mkdir(reportsDir, { recursive: true })
|
||||
const base = path.join(reportsDir, `${date}-wiki-link-cleanup`)
|
||||
const json = `${base}.json`
|
||||
const md = `${base}.md`
|
||||
await fs.writeFile(json, `${JSON.stringify(report, null, 2)}\n`, 'utf8')
|
||||
await fs.writeFile(md, renderMarkdown(report, limit), 'utf8')
|
||||
return { report, json, md }
|
||||
}
|
||||
|
||||
async function selftest() {
|
||||
const temp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-wiki-cleanup-'))
|
||||
const vault = path.join(temp, 'vault')
|
||||
const reports = path.join(temp, 'reports')
|
||||
await fs.mkdir(path.join(vault, '01 Concepts'), { recursive: true })
|
||||
await fs.writeFile(path.join(vault, '01 Concepts', 'target.md'), `---
|
||||
title: "Живая цель"
|
||||
aliases: ["Алиас цели"]
|
||||
---
|
||||
|
||||
# Живая цель
|
||||
`, 'utf8')
|
||||
await fs.writeFile(path.join(vault, '01 Concepts', 'source.md'), `# Source
|
||||
|
||||
Живая ссылка: [[Алиас цели]].
|
||||
Битая ссылка: [[Несуществующая цель]].
|
||||
Placeholder: [[...]].
|
||||
Asset: [[artifacts/final.pdf]].
|
||||
Escaped: [[2026-05-29 — Kronos\\]].
|
||||
`, 'utf8')
|
||||
const { report } = await runAudit({ vault, reportsDir: reports, limit: 10 })
|
||||
if (report.broken.total !== 4) throw new Error(`selftest expected 4 broken links, got ${report.broken.total}`)
|
||||
if (!report.targets.some(item => item.target === 'Несуществующая цель')) throw new Error('selftest missed missing target')
|
||||
if (!report.targets.some(item => item.kind === 'placeholder')) throw new Error('selftest missed placeholder target')
|
||||
const applied = await applyCleanup({ vault, reportsDir: reports, limit: 10 })
|
||||
if (applied.after.total !== 0) throw new Error(`selftest apply expected 0 broken links, got ${applied.after.total}: ${applied.report.report.targets.map(item => item.target).join(', ')}`)
|
||||
console.log(JSON.stringify({ ok: true, selftest: true }, null, 2))
|
||||
}
|
||||
|
||||
if (flag('selftest')) {
|
||||
await selftest()
|
||||
} else {
|
||||
const vault = resolveVault({ cli: arg('vault') })
|
||||
const reportsDir = path.resolve(arg('reports', process.env.MNEMAZINE_REPORTS || path.join(ROOT, 'reports')))
|
||||
const limit = Number(arg('limit', '50'))
|
||||
if (flag('apply')) {
|
||||
const result = await applyCleanup({ vault, reportsDir, limit })
|
||||
console.log(JSON.stringify({
|
||||
ok: result.after.total === 0,
|
||||
vault,
|
||||
before: result.before,
|
||||
after: result.after,
|
||||
rewritten_files: result.rewritten.length,
|
||||
created_bridge_notes: result.bridges.created.length,
|
||||
skipped: result.bridges.skipped.length,
|
||||
report: {
|
||||
json: path.relative(ROOT, result.report.json),
|
||||
md: path.relative(ROOT, result.report.md)
|
||||
}
|
||||
}, null, 2))
|
||||
if (result.after.total !== 0) process.exit(1)
|
||||
} else {
|
||||
const { report, json, md } = await runAudit({ vault, reportsDir, limit })
|
||||
const output = {
|
||||
ok: true,
|
||||
vault,
|
||||
broken: report.broken,
|
||||
sections: report.sections.slice(0, 10),
|
||||
report: {
|
||||
json: path.relative(ROOT, json),
|
||||
md: path.relative(ROOT, md)
|
||||
}
|
||||
}
|
||||
console.log(JSON.stringify(output, null, 2))
|
||||
}
|
||||
}
|
||||
Executable
+189
@@ -0,0 +1,189 @@
|
||||
#!/usr/bin/env node
|
||||
import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
// No default vault path: a fallback here would write one person's layout into
|
||||
// everyone's install. Say what is missing and stop.
|
||||
const VAULT = process.env.MNEMAZINE_VAULT
|
||||
if (!VAULT) {
|
||||
console.error('MNEMAZINE_VAULT не задан — укажите путь к своему vault и повторите.')
|
||||
process.exit(1)
|
||||
}
|
||||
const SYS = join(VAULT, '99 Система')
|
||||
const OBS_LOG = join(SYS, '_run-observability.jsonl')
|
||||
const LEDGER = join(SYS, '_session-learning-ledger.jsonl')
|
||||
const REPORT = join(SYS, '_last-session-review.md')
|
||||
|
||||
const argv = process.argv.slice(2)
|
||||
const arg = (name, fallback = '') => {
|
||||
const hit = argv.find(a => a === `--${name}` || a.startsWith(`--${name}=`))
|
||||
if (!hit) return fallback
|
||||
if (hit.includes('=')) return hit.split('=').slice(1).join('=')
|
||||
const idx = argv.indexOf(hit)
|
||||
return argv[idx + 1] || fallback
|
||||
}
|
||||
|
||||
const RUN_ID = arg('run-id', process.env.MNEMAZINE_RUN_ID || 'unknown')
|
||||
const RUNTIME = arg('runtime', process.env.MNEMAZINE_RUNTIME || 'unknown')
|
||||
const TOKEN_JSON = arg('token-json', '')
|
||||
const RESULT_JSON = arg('result-json', '')
|
||||
|
||||
function parseJson(value, fallback = null) {
|
||||
if (!value) return fallback
|
||||
try { return JSON.parse(value) } catch { return fallback }
|
||||
}
|
||||
|
||||
function compact(value, n = 240) {
|
||||
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, n)
|
||||
}
|
||||
|
||||
function numberFromTokens(value) {
|
||||
const raw = String(value || '').replace(/[^0-9]/g, '')
|
||||
return raw ? Number(raw) : null
|
||||
}
|
||||
|
||||
const tokenUsage = parseJson(TOKEN_JSON, {})
|
||||
const result = parseJson(RESULT_JSON, {})
|
||||
const lines = existsSync(OBS_LOG) ? (await readFile(OBS_LOG, 'utf8')).split('\n').filter(Boolean) : []
|
||||
const samples = lines.map(line => {
|
||||
try { return JSON.parse(line) } catch { return null }
|
||||
}).filter(row => row && row.run_id === RUN_ID)
|
||||
|
||||
const nums = samples.map(row => numberFromTokens(row.tokens)).filter(n => Number.isFinite(n))
|
||||
const startTokens = tokenUsage.start_tokens ?? (nums.length ? nums[0] : null)
|
||||
const endTokens = tokenUsage.end_tokens ?? (nums.length ? nums[nums.length - 1] : null)
|
||||
const deltaTokens = tokenUsage.delta_tokens ?? tokenUsage.total_tokens ?? (
|
||||
startTokens != null && endTokens != null ? endTokens - startTokens : null
|
||||
)
|
||||
|
||||
const localRuns = Array.isArray(tokenUsage.local_runs) ? tokenUsage.local_runs : []
|
||||
const cloudRuns = Array.isArray(tokenUsage.runs) ? tokenUsage.runs : []
|
||||
const localLabels = new Set(localRuns.map(r => r.label).filter(Boolean))
|
||||
const cloudLabels = new Set(cloudRuns.map(r => r.label).filter(Boolean))
|
||||
const localFirstLabels = ['ocr-pass', 'transcribe-pass', 'triage', 'process', 'store', 'hash-record', 'embed-add', 'graphify', 'briefing']
|
||||
const localFirstViolations = localFirstLabels.filter(label => cloudLabels.has(label) && !localLabels.has(label))
|
||||
|
||||
const errors = []
|
||||
if (result && result.error) errors.push(String(result.error))
|
||||
if (Array.isArray(result?.unaccounted) && result.unaccounted.length) {
|
||||
errors.push(`unaccounted:${result.unaccounted.length}`)
|
||||
}
|
||||
if (result && result.balanced === false) errors.push('coverage_not_balanced')
|
||||
if (localFirstViolations.length) errors.push(`local_first_violations:${localFirstViolations.join(',')}`)
|
||||
if (deltaTokens != null && deltaTokens > 0 && cloudRuns.length === 0 && RUNTIME.includes('codex')) {
|
||||
errors.push('token_delta_without_cloud_runs')
|
||||
}
|
||||
|
||||
const tokenSummary = {
|
||||
runtime: RUNTIME,
|
||||
run_id: RUN_ID,
|
||||
source: tokenUsage.source || (tokenUsage.runtime === 'codex' ? 'codex exec output' : 'abtop'),
|
||||
total_tokens: deltaTokens,
|
||||
start_tokens: startTokens,
|
||||
end_tokens: endTokens,
|
||||
samples: tokenUsage.samples ?? samples.length,
|
||||
codex_agent_calls: tokenUsage.codex_agent_calls ?? cloudRuns.length,
|
||||
local_agent_calls: tokenUsage.local_agent_calls ?? localRuns.length,
|
||||
measured_agent_calls: tokenUsage.measured_agent_calls ?? null,
|
||||
}
|
||||
|
||||
const audit = {
|
||||
local_first_ok: localFirstViolations.length === 0,
|
||||
local_first_violations: localFirstViolations,
|
||||
protected_local_engines: ['Apple Vision OCR', 'whisper', 'MarkitDown', 'fastembed', 'Graphify', 'mnemozina-brief'],
|
||||
rule: 'OCR/transcribe/parse/dedup/embed/graph/brief must stay local unless user explicitly asks deep LLM synthesis.',
|
||||
}
|
||||
|
||||
const learning = {
|
||||
ts: new Date().toISOString(),
|
||||
run_id: RUN_ID,
|
||||
runtime: RUNTIME,
|
||||
token_summary: tokenSummary,
|
||||
audit,
|
||||
errors,
|
||||
lesson: errors.length
|
||||
? `Следующий прогон: сначала проверить ${errors.join('; ')}. Не тратить LLM на локальные стадии.`
|
||||
: 'Ошибок хвоста не найдено. Сохранять local-first cascade.',
|
||||
}
|
||||
|
||||
const agentTrace = Array.isArray(result?.agent_trace) ? result.agent_trace : []
|
||||
const okAgents = agentTrace.filter(a => a && (a.status === 'ok' || a.status === 'repaired')).map(a => a.name).filter(Boolean)
|
||||
const badAgents = agentTrace.filter(a => a && !['ok', 'repaired'].includes(a.status)).map(a => `${a.name}:${a.status}`).filter(Boolean)
|
||||
const gates = result?.gates && typeof result.gates === 'object' ? result.gates : {}
|
||||
const worked = []
|
||||
if (result?.status === 'done') worked.push('coverage closed with status=done')
|
||||
if (result?.graph_updated) worked.push('Graphify updated after intake')
|
||||
if (result?.briefing?.brief_md) worked.push('brief_md returned to chat')
|
||||
if (audit.local_first_ok) worked.push('local-first audit passed')
|
||||
if (okAgents.length) worked.push(`agent trace closed: ${okAgents.join(', ')}`)
|
||||
|
||||
const failed = []
|
||||
if (result?.status && result.status !== 'done') failed.push(`status=${result.status}`)
|
||||
if (Array.isArray(result?.unaccounted) && result.unaccounted.length) failed.push(`unaccounted=${result.unaccounted.length}`)
|
||||
if (result?.balanced === false) failed.push('ledger not balanced')
|
||||
if (!result?.graph_updated) failed.push('Graphify not updated or skipped')
|
||||
if (!result?.briefing?.brief_md) failed.push('brief_md missing')
|
||||
if (!audit.local_first_ok) failed.push(`local-first violations: ${audit.local_first_violations.join(', ')}`)
|
||||
if (badAgents.length) failed.push(`agent trace problems: ${badAgents.join(', ')}`)
|
||||
if (errors.length) failed.push(`errors: ${errors.join('; ')}`)
|
||||
|
||||
const mistakes = []
|
||||
if (failed.length) mistakes.push(...failed)
|
||||
if (result?.status === 'done' && !errors.length && audit.local_first_ok) {
|
||||
mistakes.push('no blocking mistakes detected')
|
||||
}
|
||||
|
||||
const fixes = []
|
||||
if (Array.isArray(result?.unaccounted) && result.unaccounted.length) fixes.push('rerun only unaccounted files before archive; keep them in inbox')
|
||||
if (result?.balanced === false) fixes.push('recompute ledger from disk, not agent summary')
|
||||
if (!audit.local_first_ok) fixes.push('move violated stages back to local engines before next intake')
|
||||
if (!result?.briefing?.brief_md) fixes.push('run mnemozina-brief and return brief_md in chat')
|
||||
if (!result?.graph_updated) fixes.push('initialize or repair Graphify before next knowledge run')
|
||||
if (!fixes.length) fixes.push('keep current contract; next improvement is more precise agent trace metrics')
|
||||
|
||||
const selfReflection = {
|
||||
worked,
|
||||
did_not_work: failed.length ? failed : ['no blocking failures detected'],
|
||||
mistakes,
|
||||
fixes,
|
||||
most_important: failed.length
|
||||
? `Fix first: ${failed[0]}`
|
||||
: 'Contract held: keep local-first, named-agent trace, Graphify, brief_md, and session review as non-optional tail.',
|
||||
agent_trace: agentTrace,
|
||||
gates,
|
||||
}
|
||||
learning.self_reflection = selfReflection
|
||||
|
||||
await mkdir(SYS, { recursive: true })
|
||||
await appendFile(LEDGER, JSON.stringify(learning) + '\n')
|
||||
|
||||
const md = `---\n` +
|
||||
`title: "Session Review"\n` +
|
||||
`type: "session-review"\n` +
|
||||
`run_id: "${RUN_ID}"\n` +
|
||||
`date: "${new Date().toISOString().slice(0, 10)}"\n` +
|
||||
`token_usage: ${deltaTokens == null ? 'null' : deltaTokens}\n` +
|
||||
`---\n\n` +
|
||||
`# Session Review: ${RUN_ID}\n\n` +
|
||||
`## Расход токенов\n\n` +
|
||||
`- Runtime: ${RUNTIME}\n` +
|
||||
`- Total/delta: ${deltaTokens == null ? 'unknown' : deltaTokens}\n` +
|
||||
`- Start/end: ${startTokens ?? 'unknown'} / ${endTokens ?? 'unknown'}\n` +
|
||||
`- Calls: cloud ${tokenSummary.codex_agent_calls}, local ${tokenSummary.local_agent_calls}\n\n` +
|
||||
`## Local-first audit\n\n` +
|
||||
`- Status: ${audit.local_first_ok ? 'OK' : 'VIOLATION'}\n` +
|
||||
`- Violations: ${localFirstViolations.length ? localFirstViolations.join(', ') : 'none'}\n` +
|
||||
`- Protected engines: ${audit.protected_local_engines.join(', ')}\n\n` +
|
||||
`## Ошибки и урок\n\n` +
|
||||
`- Errors: ${errors.length ? errors.map(compact).join('; ') : 'none'}\n` +
|
||||
`- Lesson: ${learning.lesson}\n\n` +
|
||||
`## Саморефлексия Мнемозины\n\n` +
|
||||
`- Что сработало: ${worked.length ? worked.map(compact).join('; ') : 'none'}\n` +
|
||||
`- Что не сработало: ${failed.length ? failed.map(compact).join('; ') : 'no blocking failures detected'}\n` +
|
||||
`- Ошибки: ${mistakes.length ? mistakes.map(compact).join('; ') : 'none'}\n` +
|
||||
`- Как исправить: ${fixes.length ? fixes.map(compact).join('; ') : 'none'}\n` +
|
||||
`- Самое важное: ${selfReflection.most_important}\n`
|
||||
|
||||
await writeFile(REPORT, md)
|
||||
console.log(JSON.stringify({ review_path: REPORT, ledger_path: LEDGER, token_summary: tokenSummary, audit, self_reflection: selfReflection, errors }, null, 2))
|
||||
Reference in New Issue
Block a user