release: native macOS preview, approved graph identity, and guarded CLI failover

This commit is contained in:
public-repo-gate
2026-09-13 16:36:15 +03:00
parent 74c9f07f59
commit 04d0ece7ff
56 changed files with 16087 additions and 4002 deletions
+26
View File
@@ -0,0 +1,26 @@
#!/bin/bash
set -euo pipefail
# Local development bundle, without distribution signing or notarization.
project_root="$(cd "$(dirname "$0")/.." && pwd)"
build_root="$project_root/.mnemazine/tmp/macos-build"
app_root="$project_root/.mnemazine/tmp/Mnemazine.app"
swift build --package-path "$project_root/macos" --scratch-path "$build_root" -c release
binary_root="$(swift build --package-path "$project_root/macos" --scratch-path "$build_root" -c release --show-bin-path)"
mkdir -p "$app_root/Contents/MacOS"
mkdir -p "$app_root/Contents/Resources" "$build_root/AppIcon.iconset"
icon_source="$project_root/docs/assets/pantheon/app-icon-mnemazine.png"
for size in 16 32 128 256 512; do
sips -z "$size" "$size" "$icon_source" --out "$build_root/AppIcon.iconset/icon_${size}x${size}.png" >/dev/null
retina_size=$((size * 2))
sips -z "$retina_size" "$retina_size" "$icon_source" --out "$build_root/AppIcon.iconset/icon_${size}x${size}@2x.png" >/dev/null
done
iconutil -c icns "$build_root/AppIcon.iconset" -o "$app_root/Contents/Resources/AppIcon.icns"
cp "$binary_root/Mnemazine" "$app_root/Contents/MacOS/Mnemazine"
cp "$project_root/macos/Info.plist" "$app_root/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Add :MnemazineRepository string $project_root" "$app_root/Contents/Info.plist"
if node_binary="$(command -v node)"; then
/usr/libexec/PlistBuddy -c "Add :MnemazineNode string $node_binary" "$app_root/Contents/Info.plist"
fi
codesign --force --sign - "$app_root"
printf '%s\n' "$app_root"
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env node
import { discoverProviders } from './mnemazine-cli-runtime.mjs'
try { console.log(JSON.stringify({ providers: discoverProviders() })) }
catch { console.error('Не удалось прочитать реестр CLI или состояние лимитов.'); process.exitCode = 1 }
+86
View File
@@ -0,0 +1,86 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { createHash, randomUUID } from 'node:crypto'
import { loadRegistry, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
export function resolveExecutable(binary, { env = process.env, home = os.homedir() } = {}) {
if (typeof binary !== 'string' || !binary || binary.includes('\0')) return null
const override = env[`MNEMAZINE_${binary.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_BIN`]
const executable = file => {
try { fs.accessSync(file, fs.constants.X_OK); return fs.statSync(file).isFile() ? path.resolve(file) : null } catch { return null }
}
const target = override || binary
if (target.includes(path.sep)) return executable(path.resolve(target))
const dirs = [...(env.PATH || '').split(path.delimiter).filter(Boolean),
path.join(home, '.local/bin'), path.join(home, '.npm-global/bin'), path.join(home, '.claude/local'),
'/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin']
for (const dir of dirs) { const found = executable(path.join(dir, target)); if (found) return found }
return null
}
function cooldownRoot(dir) {
return dir || process.env.MNEMAZINE_CLI_COOLDOWNS || path.join(os.homedir(), '.mnemazine', 'cli-cooldowns')
}
function providerDir(name, dir) {
return path.join(cooldownRoot(dir), createHash('sha256').update(name).digest('hex'))
}
export function readCooldown(name, { dir, now = Date.now() } = {}) {
const folder = providerDir(name, dir)
let files
try { files = fs.readdirSync(folder) } catch (error) { if (error.code === 'ENOENT') return null; throw error }
let latest = null
for (const file of files.filter(file => file.endsWith('.json'))) {
let record
try { record = JSON.parse(fs.readFileSync(path.join(folder, file), 'utf8')) }
catch (error) { if (error.code === 'ENOENT') continue; throw new Error('CLI cooldown state is unreadable') }
if (!['quota', 'rate_limit'].includes(record.reason) || !Number.isFinite(record.until)) throw new Error('Invalid CLI cooldown state')
if (record.until > now && (!latest || record.until > latest.until)) latest = record
}
return latest
}
export function recordCooldown(name, reason, { dir, now = Date.now(), retryAfterMs } = {}) {
if (!['quota', 'rate_limit'].includes(reason)) return null
const ttl = Math.min(24 * 3600000, Math.max(1000, Number.isFinite(retryAfterMs) ? retryAfterMs : reason === 'quota' ? 5 * 3600000 : 60000))
const folder = providerDir(name, dir)
fs.mkdirSync(folder, { recursive: true, mode: 0o700 })
const record = { reason, until: now + ttl }
// ponytail: immutable per-provider records prevent concurrent shards from
// overwriting a longer cooldown; readers take the maximum, no stale lock theft.
const file = path.join(folder, `${randomUUID()}.json`), tmp = `${file}.tmp`
const fd = fs.openSync(tmp, 'wx', 0o600)
try { fs.writeFileSync(fd, JSON.stringify(record)); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
fs.renameSync(tmp, file)
const parent = fs.openSync(folder, 'r')
try { fs.fsyncSync(parent) } finally { fs.closeSync(parent) }
for (const old of fs.readdirSync(folder).filter(value => value.endsWith('.json'))) {
try { if (JSON.parse(fs.readFileSync(path.join(folder, old), 'utf8')).until <= now) fs.unlinkSync(path.join(folder, old)) }
catch (error) { if (error.code !== 'ENOENT') throw error }
}
return record
}
export function classifyProcessFailure(result) {
if (result.status === 0) return null
if (result.status === 124) return 'timeout'
const output = `${result.stderr || ''}\n${result.stdout || ''}`
if (/insufficient_quota|quota.{0,60}(exceed|exhaust|limit)|(?:exceed|exhaust).{0,60}quota|out of credits|credit balance.{0,40}(low|exhaust)|usage limit.{0,40}(reach|exceed)|hit your.{0,30}limit/i.test(output)) return 'quota'
if (/rate.?limit|too many requests|\b429\b/i.test(output)) return 'rate_limit'
if (/unauthori[sz]ed|not logged in|authentication required|\b401\b/i.test(output)) return 'auth'
return 'process_error'
}
export function discoverProviders({ registry = loadRegistry(), env = process.env, home = os.homedir(), cooldownDir } = {}) {
const providers = Object.entries(registry).map(([name, entry]) => {
const binary = resolveExecutable(entry.invoke[0], { env, home })
return { name, installed: Boolean(binary), supported: Boolean(pickSchemaAdapter(entry)), binary,
model: entry.model, cost_tier: entry.cost_tier, data_classes: entry.data_classes,
capabilities: entry.capabilities, cooldown: readCooldown(name, { dir: cooldownDir }) }
})
for (const name of ['gemini', 'qwen', 'opencode', 'aider', 'goose', 'ollama']) {
if (registry[name]) continue
const binary = resolveExecutable(name, { env, home })
if (binary) providers.push({ name, installed: true, supported: false, binary, cooldown: null })
}
return providers
}
+21 -6
View File
@@ -2,6 +2,7 @@
import { promises as fs } from 'node:fs'
import { existsSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { spawn, spawnSync } from 'node:child_process'
import { resolveVault } from './mnemazine-paths.mjs'
@@ -20,6 +21,7 @@ function arg(name, fallback = '') {
const NEEDS_UPDATE_MAX_DAYS = Number(arg('needs-update-max-days', process.env.MNEMAZINE_NEEDS_UPDATE_MAX_DAYS || '1'))
const STRICT_GRAPH = argv.includes('--strict-graph')
const REQUIRE_DEEP = argv.includes('--require-deep') || process.env.MNEMAZINE_REQUIRE_DEEP === '1'
const BEFORE_ARCHIVE = argv.includes('--before-archive')
// Удаление протухшего маркера графа — только по этому явному флагу.
// Без него маркер остается на месте и ложится в warnings/failures (план П08).
const PRUNE_GRAPH_MARKER = argv.includes('--prune-graph-marker')
@@ -31,6 +33,8 @@ if (argv.includes('--help')) {
Использование: node scripts/mnemazine-complete-check.mjs [флаги]
--vault <путь> корпус (иначе MNEMAZINE_VAULT, last-run.vault или repo-local vault)
--require-deep требовать deep-прогон в last-run (или MNEMAZINE_REQUIRE_DEEP=1)
--before-archive проверить pending_archive перед переносом: inbox ещё полон,
но coverage и остальные гейты обязательны
--strict-graph маркер needs_update — failure, а не warning
--needs-update-max-days N возраст маркера до failure (по умолчанию 1)
--prune-graph-marker удалить протухший маркер graphify-out/needs_update
@@ -115,7 +119,7 @@ function isGraphSemanticFile(file) {
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.ok && !(BEFORE_ARCHIVE && lastRun.phase === 'pending_archive' && lastRun.pre_archive_ready === true)) failures.push(`last run failed: ${(lastRun.failures || [lastRun.failure || 'unknown']).join('; ')}`)
if (lastRun.draft_only) failures.push('last run was draft-only')
if (!lastRun.deep) failures.push('last run was not deep')
if (lastRun.strict_archive_knowledge !== true) failures.push('strict archive knowledge gate was not enabled')
@@ -129,16 +133,26 @@ function deepFailures(lastRun) {
return failures
}
export async function loadSpecCeiling({ root = ROOT, vault, ceiling = process.env.MNEMAZINE_SPEC_CEILING } = {}) {
const file = path.resolve(ceiling || path.join(root, '.mnemazine/state/spec-ceiling.json'))
const baseline = await readJson(file)
if (!baseline) return { file, error: 'spec ceiling has no baseline yet' }
if (typeof baseline.vault !== 'string' || path.resolve(baseline.vault) !== path.resolve(vault)) return { file, error: 'spec ceiling belongs to a different vault' }
return { file, error: null }
}
async function main() {
const failures = []
const warnings = []
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}`)
if (inboxFiles.length && !BEFORE_ARCHIVE) failures.push(`inbox not empty: ${inboxFiles.length}`)
const lastRunFile = path.join(STATE, 'last-run.json')
const lastRun = await readJson(lastRunFile)
if (BEFORE_ARCHIVE && (lastRun?.phase !== 'pending_archive' || lastRun?.pre_archive_ready !== true || lastRun?.archive_pending !== inboxFiles.length)) failures.push('pre-archive state does not match the current inbox')
if (!BEFORE_ARCHIVE && lastRun?.phase === 'pending_archive') failures.push('archive has not completed')
const VAULT = resolveVault({ cli: arg('vault'), env: process.env.MNEMAZINE_VAULT || lastRun?.vault })
const gateEnv = { MNEMAZINE_VAULT: VAULT }
const coverageArgs = ['scripts/mnemazine-coverage-check.mjs', '--vault', VAULT, '--inbox', INBOX, '--json']
@@ -156,12 +170,13 @@ async function main() {
// Потолок провалов спеки в продовом пути (план П06 шаг 6): гейт --spec виден
// приемке, а не только вручную. Ненулевой код прибора потолка → в failures.
const specCeilingFile = path.join(STATE, 'spec-ceiling.json')
if (!existsSync(specCeilingFile)) {
const baseline = await loadSpecCeiling({ vault: VAULT })
const specCeilingFile = baseline.file
if (baseline.error) {
// Свежая установка: потолок спеки — per-machine runtime (план П16, .mnemazine/state
// gitignored), на чистом клоне его нет и сравнивать не с чем. Это «нет данных», а не
// провал: ratchet без базы — no-op. doctor распознает эту строку как no-data (degraded, не fatal).
failures.push('spec ceiling has no baseline yet')
failures.push(baseline.error)
} 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}`)
@@ -238,7 +253,7 @@ async function main() {
if (!result.ok) process.exit(1)
}
main().catch(error => {
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main().catch(error => {
console.error(error.message || error)
process.exit(1)
})
+34 -4
View File
@@ -18,9 +18,14 @@
// возвращают ровно тот зеленый, что мастер-план §8 запрещает прибору оркестрации.
// Покрытым считается файл, чей basename встречается в теле или frontmatter хотя бы одной ноты vault —
// та же семантика, что у сверщика (`source:`/`sources:`), но без права ошибиться в регулярке.
// Для переименованных job snapshots дополнительно считается SHA-256 текущего файла:
// local-media hash засчитывается только из final verified enriched ноты (strictKnowledgeReady).
import { promises as fs } from 'node:fs'
import { constants } from 'node:fs'
import { createHash } from 'node:crypto'
import path from 'node:path'
import { resolveVault } from './mnemazine-paths.mjs'
import { strictKnowledgeReady } from './mnemazine-note-spec.mjs'
const argv = process.argv.slice(2)
const arg = (name, fallback = '') => {
@@ -32,16 +37,23 @@ const arg = (name, fallback = '') => {
/** Ноты vault одним чтением: корпус мал (< 20 МБ), а N грепов по файлу — это N спавнов и гонка. */
async function readCorpus(vault) {
const chunks = []
const verifiedRefs = 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 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'))
else if (item.isFile() && p.endsWith('.md')) {
const text = await fs.readFile(p, 'utf8')
chunks.push(text)
if (strictKnowledgeReady(text)) {
for (const match of text.matchAll(/\blocal-media:([a-f0-9]{64}|[a-f0-9]{16})(?![a-f0-9])/gi)) verifiedRefs.add(match[1].toLowerCase())
}
}
}
}
await walk(vault)
return chunks.join('\n')
return { text: chunks.join('\n'), verifiedRefs }
}
/**
@@ -92,8 +104,26 @@ if (census.length === 0 && !argv.includes('--allow-empty')) {
process.exit(2)
}
const corpus = (await readCorpus(VAULT)).normalize('NFC')
const uncovered = census.filter(f => !isCovered(corpus, f))
const corpus = await readCorpus(VAULT)
const corpusNfc = corpus.text.normalize('NFC')
const uncovered = []
for (const file of census) {
if (isCovered(corpusNfc, file)) continue
let coveredByHash = false
if (corpus.verifiedRefs.size) {
try {
const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
const hash = createHash('sha256')
try {
if (!(await handle.stat()).isFile()) throw new Error('Source is not a regular file')
for await (const chunk of handle.createReadStream({ autoClose: false })) hash.update(chunk)
} finally { await handle.close() }
const digest = hash.digest('hex')
coveredByHash = corpus.verifiedRefs.has(digest) || corpus.verifiedRefs.has(digest.slice(0, 16))
} catch { /* Unreadable sources cannot be proven covered by content. */ }
}
if (!coveredByHash) uncovered.push(file)
}
const report = { ok: uncovered.length === 0, vault: VAULT, census: census.length, covered: census.length - uncovered.length, uncovered }
if (argv.includes('--json')) console.log(JSON.stringify(report, null, 2))
+26
View File
@@ -6,12 +6,28 @@ ENV_INBOX="${MNEMAZINE_INBOX:-}"
ENV_VAULT="${MNEMAZINE_VAULT:-}"
ENV_DEEP="${MNEMAZINE_DEEP:-}"
ENV_REQUIRE_DEEP="${MNEMAZINE_REQUIRE_DEEP:-}"
ENV_REPORTS="${MNEMAZINE_REPORTS:-}"
ENV_STATE="${MNEMAZINE_STATE:-}"
ENV_ARCHIVE="${MNEMAZINE_ARCHIVE:-}"
ENV_CACHE="${MNEMAZINE_CACHE:-}"
ENV_EXTRACTS="${MNEMAZINE_EXTRACTS:-}"
ENV_RUN_ID="${MNEMAZINE_RUN_ID:-}"
ENV_JOB_GROUPS="${MNEMAZINE_JOB_GROUPS:-}"
DRY_RUN=0
[ "${1:-}" = "--dry-run" ] && DRY_RUN=1
[ -f "$REPO/.mnemazine/config.env" ] && . "$REPO/.mnemazine/config.env"
[ -f "$REPO/.mnemazine/config.local.sh" ] && . "$REPO/.mnemazine/config.local.sh"
# Explicit job paths must survive trusted owner configuration loading.
[ -z "$ENV_REPORTS" ] || export MNEMAZINE_REPORTS="$ENV_REPORTS"
[ -z "$ENV_STATE" ] || export MNEMAZINE_STATE="$ENV_STATE"
[ -z "$ENV_ARCHIVE" ] || export MNEMAZINE_ARCHIVE="$ENV_ARCHIVE"
[ -z "$ENV_CACHE" ] || export MNEMAZINE_CACHE="$ENV_CACHE"
[ -z "$ENV_EXTRACTS" ] || export MNEMAZINE_EXTRACTS="$ENV_EXTRACTS"
[ -z "$ENV_RUN_ID" ] || export MNEMAZINE_RUN_ID="$ENV_RUN_ID"
[ -z "$ENV_JOB_GROUPS" ] || export MNEMAZINE_JOB_GROUPS="$ENV_JOB_GROUPS"
CONFIG_VAULT=""
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)"
@@ -73,6 +89,16 @@ if [ "$DRY_RUN" = "1" ]; then
exit 0
fi
# Hold one canonical-vault lock across run AND complete. Child runs verify
# inherited ownership (nonce, process start and ancestry) before reentering.
if [ "${MNEMAZINE_DRAFT_ONLY:-0}" = "1" ]; then
echo "strict protocol vs draft-only: MNEMAZINE_REQUIRE_DEEP=1 и MNEMAZINE_DRAFT_ONLY=1 несовместимы" >&2
exit 2
fi
if ! node "$REPO/scripts/mnemazine-vault-lock.mjs" --check "$MNEMAZINE_VAULT"; then
exec node "$REPO/scripts/mnemazine-vault-lock.mjs" --vault "$MNEMAZINE_VAULT" -- bash "${BASH_SOURCE[0]}" "$@"
fi
ran=0
run_inbox "$BASE_INBOX"
+362
View File
@@ -0,0 +1,362 @@
#!/usr/bin/env node
// ponytail: one local queue/worker; all clients must use the same root.
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { randomUUID, createHash } from 'node:crypto'
import { spawn, spawnSync } from 'node:child_process'
import { parseArgs } from 'node:util'
const script = fileURLToPath(import.meta.url)
const repo = path.resolve(path.dirname(script), '..')
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const now = () => new Date().toISOString()
const alive = pid => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
function syncDir(directory) {
const fd = fs.openSync(directory, 'r')
try { fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
}
function atomic(file, value) {
const tmp = `${file}.${randomUUID()}.tmp`
const fd = fs.openSync(tmp, 'wx', 0o600)
try { fs.writeFileSync(fd, JSON.stringify(value)); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
fs.renameSync(tmp, file)
syncDir(path.dirname(file))
}
function identity(pid) {
return spawnSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout?.trim() || ''
}
function sameProcess(owner) { return owner?.pid > 0 && alive(owner.pid) && identity(owner.pid) === owner.started }
function ownedGroup(owner) {
if (!Number.isSafeInteger(owner?.pid) || owner.pid <= 1 || !owner.started) return false
const result = spawnSync('ps', ['-axo', 'pid=,pgid=,lstart='], { encoding: 'utf8' })
if (result.status !== 0) throw new Error('Cannot inspect process groups safely')
const members = result.stdout.split('\n').map(line => line.trim().match(/^(\d+)\s+(\d+)\s+(.+)$/))
.filter(match => match && Number(match[2]) === owner.pid)
.map(match => ({ pid: Number(match[1]), started: match[3].trim() }))
if (!members.length) return false
const leader = members.find(member => member.pid === owner.pid)
if (leader) return leader.started === owner.started
// A dead leader cannot prove group ownership across PID reuse after a crash.
throw new Error(`Ambiguous live process group ${owner.pid}: leader exited; queue paused until the group exits`)
}
async function lock(file, wait = true) {
for (let i = 0; i < (wait ? 600 : 1); i++) {
try {
fs.mkdirSync(file, { mode: 0o700 })
atomic(path.join(file, 'owner.json'), { pid: process.pid, started: identity(process.pid) })
return () => fs.rmSync(file, { recursive: true, force: true })
} catch (e) {
if (e.code !== 'EEXIST') throw e
let owner
try { owner = JSON.parse(fs.readFileSync(path.join(file, 'owner.json'), 'utf8')) } catch {}
// Never reclaim an owner that may still be publishing its lock record.
let stale = false
try { stale = owner ? !sameProcess(owner) : Date.now() - fs.statSync(file).mtimeMs > 30000 } catch (err) { if (err.code !== 'ENOENT') throw err; i--; continue }
if (stale) {
const reaper = path.join(file, '.reaper')
try {
fs.mkdirSync(reaper)
atomic(path.join(reaper, 'owner.json'), { pid: process.pid, started: identity(process.pid) })
let current
try { current = JSON.parse(fs.readFileSync(path.join(file, 'owner.json'), 'utf8')) } catch {}
if (current && sameProcess(current)) fs.rmSync(reaper, { recursive: true })
else fs.renameSync(file, `${file}.stale-${randomUUID()}`)
} catch (err) {
if (!['ENOENT', 'EEXIST'].includes(err.code)) throw err
if (err.code === 'EEXIST') {
let reaperOwner
try { reaperOwner = JSON.parse(fs.readFileSync(path.join(reaper, 'owner.json'), 'utf8')) } catch {}
try {
if (reaperOwner ? !sameProcess(reaperOwner) : Date.now() - fs.statSync(reaper).mtimeMs > 30000) fs.renameSync(reaper, `${reaper}.stale-${randomUUID()}`)
} catch (failure) { if (failure.code !== 'ENOENT') throw failure }
await sleep(50)
}
}
i--; continue
}
if (!wait) return null
await sleep(50)
}
}
throw new Error('Queue is busy; retry later')
}
function validateId(id) {
if (!/^[0-9a-f-]{36}$/.test(id || '')) throw new Error('Invalid job id')
return id
}
export class JobQueue {
constructor(root = path.join(repo, '.mnemazine/state/jobs')) {
this.root = path.resolve(root)
fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
}
dir(id) { return path.join(this.root, validateId(id)) }
read(id) { return JSON.parse(fs.readFileSync(path.join(this.dir(id), 'job.json'), 'utf8')) }
list() {
return fs.readdirSync(this.root).filter(x => /^[0-9a-f-]{36}$/.test(x) && fs.existsSync(path.join(this.root, x, 'job.json')))
.map(id => this.read(id)).sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id))
}
save(job, event) {
job.updated_at = now()
// State and event history commit together: no torn JSONL/state dual write.
job.events = [...(job.events || []), { at: job.updated_at, event, status: job.status }]
atomic(path.join(this.dir(job.id), 'job.json'), job)
return job
}
async transaction(fn) {
const release = await lock(path.join(this.root, '.state-lock'))
try { return fn() } finally { release() }
}
async submit({ kind, query, files = [], text, mode, project, provenance }) {
if (!['ingest', 'search', 'brief'].includes(kind)) throw new Error('kind must be ingest, search or brief')
mode ||= 'local'
if (!['local', 'deep'].includes(mode)) throw new Error('mode must be local or deep')
if (kind === 'ingest' && mode === 'local') throw new Error('Strict ingest requires deep mode; local ingest is not supported')
const hasText = text !== undefined
if (kind === 'ingest' ? (hasText === Boolean(files.length) || query !== undefined) : (!query?.trim() || files.length || hasText)) throw new Error('ingest requires either files or text; search/brief require a query and no intake inputs')
let input_text, input_kind, source_url
if (hasText) {
if (typeof text !== 'string' || !text.trim() || Buffer.byteLength(text, 'utf8') > 8192 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/u.test(text)) throw new Error('Text must contain 1–8192 UTF-8 bytes without control characters')
input_text = text.trim()
input_kind = 'title'
if (/^[A-Za-z][A-Za-z0-9+.-]*:/.test(input_text)) {
let url
try { url = new URL(input_text) } catch { throw new Error('Invalid URL') }
if (!/^https?:\/\//i.test(input_text) || !['http:', 'https:'].includes(url.protocol) || !url.hostname || url.username || url.password || /\s/.test(input_text)) throw new Error('Only http/https URLs without credentials are supported')
input_kind = 'url'
source_url = url.href
} else if (/^(?:\/\/|www\.)/i.test(input_text)) throw new Error('Use a complete http/https URL')
}
if (query && (query.length > 16000 || query.includes('\0'))) throw new Error('Invalid query')
if (project && !/^[\p{L}\p{N}_.-]{1,128}$/u.test(project)) throw new Error('Invalid project id')
if (provenance && (typeof provenance !== 'object' || Array.isArray(provenance) || JSON.stringify(provenance).length > 8192)) throw new Error('Invalid provenance')
// Snapshot before publication: worker never sees partially copied inputs.
const id = randomUUID(), dir = this.dir(id)
fs.mkdirSync(path.join(dir, 'sources'), { recursive: true, mode: 0o700 })
syncDir(this.root)
const copied = []
if (hasText) {
// Existing enrichment treats text as research seed; this is no factual note.
const request = `# Запрос на исследование\n\nТип входа: ${input_kind === 'url' ? 'ссылка' : 'название или тема'}.\n\nИсходный ввод пользователя:\n${input_text.split('\n').map(line => `> ${line}`).join('\n')}\n${source_url ? `\nИсточник: ${source_url}\n` : ''}\nЭто запрос на исследование, а не готовое знание и не подтверждение фактов. Сначала установите первичный источник и точный предмет запроса. Изучите доступный материал, проверьте утверждения по источникам и сохраните только подтверждённые выводы со ссылками. Если источник недоступен или название неоднозначно, явно сообщите ограничение; не выдумывайте содержание, автора, расшифровку видео или результаты.\n`
const hash = createHash('sha256').update(request).digest('hex')
const name = `${hash.slice(0, 16)}-research-request.md`
const snapshot = path.join(dir, 'sources', name)
const fd = fs.openSync(snapshot, 'wx', 0o600)
try { fs.writeFileSync(fd, request); fs.fsyncSync(fd) } finally { fs.closeSync(fd) }
copied.push({ snapshot, name, sha256: hash })
}
for (const source of files) {
const original = path.resolve(source)
const fd = fs.openSync(original, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK)
let data
try {
const stat = fs.fstatSync(fd)
if (!stat.isFile()) throw new Error('Input must be a regular file')
if (stat.size > 512 * 1024 * 1024) throw new Error('File exceeds the current 512 MiB intake limit')
data = fs.readFileSync(fd)
} finally { fs.closeSync(fd) }
const hash = createHash('sha256').update(data).digest('hex')
if (copied.some(f => f.sha256 === hash)) continue
const name = `${hash.slice(0, 16)}-${path.basename(original).replace(/^\.+/, '') || 'file'}`
const snapshot = path.join(dir, 'sources', name)
const out = fs.openSync(snapshot, 'wx', 0o600)
try { fs.writeFileSync(out, data); fs.fsyncSync(out) } finally { fs.closeSync(out) }
copied.push({ original, snapshot, name, sha256: hash })
}
syncDir(path.join(dir, 'sources'))
return this.transaction(() => {
const fingerprint = kind === 'ingest' ? createHash('sha256').update(JSON.stringify({ ...(hasText ? { input_text } : { hashes: copied.map(f => f.sha256).sort() }), project, provenance })).digest('hex') : null
const previous = fingerprint && this.list().find(j => j.fingerprint === fingerprint && ['queued', 'running', 'completed'].includes(j.status))
if (previous) { fs.rmSync(dir, { recursive: true }); return { ...previous, deduplicated: true } }
return this.save({ id, kind, query, mode, project, provenance, input_text, input_kind, files: copied, fingerprint, status: 'queued', created_at: now(), attempts: 0 }, 'submitted')
})
}
async change(id, action) {
return this.transaction(() => {
const job = this.read(id)
if (action === 'cancel' && ['queued', 'running'].includes(job.status)) {
job.cancel_requested = true
if (job.status === 'queued') job.status = 'cancelled'
return this.save(job, 'cancel_requested')
}
if (action === 'retry') {
if (!['failed', 'cancelled'].includes(job.status)) throw new Error('Only failed/cancelled jobs can be retried')
for (const blocked of this.list().filter(j => j.recovery_blocked || j.id === id)) recordedGroups(this.dir(blocked.id)).concat(blocked.child || []).forEach(ownedGroup)
job.status = 'queued'; delete job.error; delete job.result; delete job.cancel_requested
delete job.recovery_blocked
return this.save(job, 'retried')
}
return job
})
}
async work({ once = false, execute = executeJob } = {}) {
const release = await lock(path.join(this.root, '.worker-lock'), false)
if (!release) return { worker: 'already_running' }
let stopping = false, activeChild
const stop = () => { stopping = true; if (activeChild) terminate(activeChild) }
process.on('SIGTERM', stop); process.on('SIGINT', stop)
try {
// A killed worker may leave its separate child process group alive.
for (const job of this.list().filter(j => j.status === 'running' || j.recovery_blocked)) {
let groups
try {
groups = recordedGroups(this.dir(job.id)).concat(job.child || []).filter(ownedGroup)
for (const group of groups) terminate(group)
if (groups.length) await sleep(1000)
for (const group of groups) if (ownedGroup(group)) terminate(group, 'SIGKILL')
}
catch (error) {
await this.transaction(() => { const fresh = this.read(job.id); fresh.status = 'failed'; fresh.error = error.message; fresh.recovery_blocked = true; this.save(fresh, 'recovery_blocked') })
throw error
}
await this.transaction(() => {
const fresh = this.read(job.id)
fresh.status = job.recovery_blocked ? 'failed' : (fresh.cancel_requested ? 'cancelled' : 'queued')
delete fresh.recovery_blocked
delete fresh.child
this.save(fresh, 'worker_recovered')
})
}
do {
const job = await this.transaction(() => {
const next = this.list().find(j => j.status === 'queued')
if (!next) return null
next.status = 'running'; next.attempts++
return this.save(next, 'started')
})
if (!job) { if (once) break; await sleep(750); continue }
let result, error
try {
result = await execute(job, this.dir(job.id), async child => {
activeChild = child
await this.transaction(() => { const j = this.read(job.id); j.child = child; this.save(j, 'child_started') })
}, () => stopping || this.read(job.id).cancel_requested)
} catch (e) { error = e.message }
activeChild = null
await this.transaction(() => {
const fresh = this.read(job.id)
if (error?.includes('Ambiguous live process group')) fresh.recovery_blocked = true
fresh.status = fresh.recovery_blocked ? 'failed' : (fresh.cancel_requested ? 'cancelled' : (error ? 'failed' : 'completed'))
if (error) fresh.error = error
if (result) fresh.result = result
if (!fresh.recovery_blocked) delete fresh.child
this.save(fresh, fresh.status)
})
if (this.read(job.id).recovery_blocked) throw new Error(this.read(job.id).error)
} while (!once && !stopping)
return { worker: 'stopped' }
} finally { process.off('SIGTERM', stop); process.off('SIGINT', stop); release() }
}
}
function terminate(child, signal = 'SIGTERM') {
try { process.kill(-child.pid, signal) } catch (e) { if (e.code !== 'ESRCH') throw e }
}
function recordedGroups(dir) {
try {
return fs.readFileSync(path.join(dir, 'process-groups.jsonl'), 'utf8').split('\n').slice(0, -1).filter(Boolean).map(line => JSON.parse(line))
} catch (e) { if (e.code === 'ENOENT') return []; throw e }
}
export function pipelineFailure(dir, outcome) {
const details = []
try {
const state = JSON.parse(fs.readFileSync(path.join(dir, 'state/last-run.json'), 'utf8'))
details.push(...(Array.isArray(state.failures) ? state.failures : [state.failure]).filter(value => typeof value === 'string').map(value => value.slice(0, 500)))
const extracts = path.join(dir, 'cache/extracted')
for (const file of fs.readdirSync(extracts).filter(name => name.endsWith('.json')).slice(0, 20)) {
const record = JSON.parse(fs.readFileSync(path.join(extracts, file), 'utf8'))
if (record.status !== 'needs_manual_context' || typeof record.text_path !== 'string' || path.basename(record.text_path) !== record.text_path) continue
const fd = fs.openSync(path.join(extracts, record.text_path), 'r')
let text
try { const buffer = Buffer.alloc(16384); text = buffer.subarray(0, fs.readSync(fd, buffer)).toString('utf8') }
finally { fs.closeSync(fd) }
const length = text.replace(/^#{1,6}\s+/gm, '').replace(/\s+/g, ' ').trim().slice(0, 2000).length
details.unshift(length > 0 && length < 80
? `Файл прочитан, но текст слишком короткий: ${length} символов; нужно не менее 80. Добавьте содержательный контекст.`
: 'Недостаточно читаемого текста для обработки. Добавьте текстовый контекст или проверьте качество исходного файла.')
}
} catch { /* The pipeline can fail before state or extracts exist. Keep exit diagnostics. */ }
return `${[...new Set(details)].join(' ')}${details.length ? ' ' : ''}Pipeline exited ${outcome.code ?? outcome.signal}; see ${path.join(dir, 'error.log')}`
}
async function executeJob(job, dir, recordChild, cancelled) {
const env = { ...process.env, MNEMAZINE_ROOT: repo, MNEMAZINE_DEEP: job.mode === 'deep' ? '1' : '0', MNEMAZINE_SEARCH_VERIFY: job.mode === 'deep' ? '1' : '0', MNEMAZINE_SEARCH_LOG: path.join(dir, 'queries.jsonl'), MNEMAZINE_JOB_GROUPS: path.join(dir, 'process-groups.jsonl') }
let command = process.execPath, args
if (job.kind === 'ingest') {
for (const sub of ['inbox', 'state', 'reports', 'archive', 'cache/extracted']) fs.mkdirSync(path.join(dir, sub), { recursive: true })
for (const file of job.files) {
if (createHash('sha256').update(fs.readFileSync(file.snapshot)).digest('hex') !== file.sha256) throw new Error('Source snapshot integrity check failed')
fs.copyFileSync(file.snapshot, path.join(dir, 'inbox', file.name))
}
Object.assign(env, {
MNEMAZINE_INBOX: path.join(dir, 'inbox'), MNEMAZINE_STATE: path.join(dir, 'state'),
MNEMAZINE_REPORTS: path.join(dir, 'reports'), MNEMAZINE_ARCHIVE: path.join(dir, 'archive'),
MNEMAZINE_CACHE: path.join(dir, 'cache/hashes.json'), MNEMAZINE_EXTRACTS: path.join(dir, 'cache/extracted'),
MNEMAZINE_REQUIRE_DEEP: '1', MNEMAZINE_RUN_ID: job.id,
})
command = 'bash'; args = [path.join(repo, 'scripts/mnemazine-desktop-protocol.sh')]
} else {
args = [path.join(repo, 'scripts/mnemazine-kb-search.mjs'), `--topic=${job.query}`, '--result-json']
if (job.mode === 'deep') args.push('--deep', '--verify')
}
const outputPath = path.join(dir, 'output.log'), errorPath = path.join(dir, 'error.log')
const output = fs.openSync(outputPath, 'w', 0o600), errors = fs.openSync(errorPath, 'w', 0o600)
let child
try { child = spawn(command, args, { cwd: repo, env, detached: true, stdio: ['ignore', output, errors] }) }
finally { fs.closeSync(output); fs.closeSync(errors) }
const completion = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', (code, signal) => resolve({ code, signal })) })
if (child.pid) await recordChild({ pid: child.pid, started: identity(child.pid) })
let killedAt = 0
let monitorError
const killedGroups = new Map()
const cancelGroups = () => {
for (const group of recordedGroups(dir).filter(ownedGroup)) {
if (!killedGroups.has(group.pid)) { killedGroups.set(group.pid, group); terminate(group) }
}
if (!killedAt) { killedAt = Date.now(); terminate(child) }
else if (Date.now() - killedAt > 2000) terminate(child, 'SIGKILL')
}
const timer = setInterval(() => {
try { if (child.pid && cancelled()) cancelGroups() }
catch (e) { monitorError = e; killedAt ||= Date.now(); if (child.pid) terminate(child) }
}, 100)
let outcome
try {
outcome = await completion
if (child.pid && cancelled() && !monitorError) cancelGroups()
if (killedAt) {
await sleep(Math.max(0, 2000 - (Date.now() - killedAt)))
terminate(child, 'SIGKILL')
for (const group of killedGroups.values()) if (ownedGroup(group)) terminate(group, 'SIGKILL')
}
} finally { clearInterval(timer) }
if (monitorError) throw monitorError
if (outcome.code !== 0) throw new Error(pipelineFailure(dir, outcome))
const result = job.kind === 'ingest' ? { text: 'Обработка копий завершена. Оригиналы сохранены.' } : JSON.parse(fs.readFileSync(outputPath, 'utf8'))
if (typeof result.text !== 'string') throw new Error('Search returned no report text')
const { text } = result
const report_path = path.join(dir, 'result.md')
fs.writeFileSync(report_path, text, { mode: 0o600 })
return { ...result, report_path }
}
function startWorker(root) {
const child = spawn(process.execPath, [script, 'work', '--root', root], { cwd: repo, detached: true, stdio: 'ignore' })
child.unref()
}
async function main() {
const { positionals, values } = parseArgs({ allowPositionals: true, options: {
root: { type: 'string' }, kind: { type: 'string' }, id: { type: 'string' }, file: { type: 'string', multiple: true },
query: { type: 'string' }, text: { type: 'string' }, mode: { type: 'string' }, project: { type: 'string' }, provenance: { type: 'string' },
'no-start': { type: 'boolean' }, once: { type: 'boolean' },
} })
const [action] = positionals
if (positionals.length !== 1 || !['submit', 'list', 'status', 'cancel', 'retry', 'work'].includes(action)) throw new Error('Usage: mnemazine-jobs.mjs submit|list|status|cancel|retry|work [options]')
const queue = new JobQueue(values.root)
let result
if (action === 'submit') result = { job: await queue.submit({ ...values, files: values.file, provenance: values.provenance ? JSON.parse(values.provenance) : undefined }) }
if (action === 'list') result = { jobs: queue.list() }
if (action === 'status') result = { job: queue.read(values.id) }
if (['cancel', 'retry'].includes(action)) result = { job: await queue.change(values.id, action) }
if (action === 'work') result = await queue.work({ once: values.once })
if (!values['no-start'] && (['submit', 'retry'].includes(action) || (['list', 'status'].includes(action) && queue.list().some(j => ['queued', 'running'].includes(j.status))))) startWorker(queue.root)
process.stdout.write(JSON.stringify(result) + '\n')
}
if (process.argv[1] && path.resolve(process.argv[1]) === script) main().catch(e => { console.error(e.message); process.exitCode = 1 })
+76 -26
View File
@@ -15,8 +15,10 @@
// engages the LLM swarm. Report written to reports/ as Markdown; path printed.
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { resolveVault } from './mnemazine-paths.mjs'
import { activeProvider, llmAvailable, llmJson, fenceUntrusted } from './mnemazine-llm.mjs'
import { classifyFile, loadTaxonomy, parseFrontmatter } from './mnemazine-machine-class-gate.mjs'
const argv = process.argv.slice(2)
const SELFTEST = argv.includes('--selftest')
@@ -29,6 +31,7 @@ function arg(name, fb = '') {
const DEEP = argv.includes('--deep') || process.env.MNEMAZINE_DEEP === '1'
const STDOUT = argv.includes('--stdout')
const JSON_OUT = argv.includes('--json')
const RESULT_JSON = argv.includes('--result-json')
if (argv.includes('--help')) {
console.log(`mnemazine-kb-search.mjs — тематический поиск по корпусу знаний.
@@ -41,8 +44,10 @@ if (argv.includes('--help')) {
каталог внутри корпуса — отказ с кодом 2
--stdout отчет в stdout, файл не создается
--json машинная выдача в stdout: results[] с note/score/subject/snippets
--result-json готовая справка и источники в stdout: {text,sources,stats}
--deep LLM-рой: планирование запроса, шард-агенты, синтез
--verify отбраковка необоснованных находок (только с --deep)
--verify совместимость: проверка включена всегда с --deep
--project ID фильтр projects (не механизм авторизации)
--concurrency N параллелизм роя (по умолчанию 4)
--max-notes N потолок кандидатов для роя (по умолчанию 60)
--shard-size N заметок на агента (по умолчанию 6)
@@ -59,10 +64,9 @@ const MAX_NOTES = Number(arg('max-notes', '60')) // candidate cap fed to the
const SHARD_SIZE = Number(arg('shard-size', '6')) // notes per agent
const MAX_SHARDS = Number(arg('max-shards', process.env.MNEMAZINE_SEARCH_MAX_SHARDS || '12')) // deep cost cap: hard limit on agents spawned
const EXCERPT = 2500 // chars of each note shown to an agent
// 2B perspective-diverse verify: opt-in (extra K agents). Default OFF to keep
// the token budget tight — enable when groundedness matters. One call per
// top-K finding, judging 3 lenses at once (grounded/relevant/actionable).
const VERIFY = argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY === '1'
// Verification is mandatory for deep findings. The budget bounds accepted
// findings too: unreviewed findings never leak around the verifier.
const VERIFY = DEEP || argv.includes('--verify') || process.env.MNEMAZINE_SEARCH_VERIFY === '1'
const MAX_VERIFY = Number(arg('max-verify', '5')) // top-K findings to verify
// --- helpers -----------------------------------------------------------------
@@ -78,7 +82,7 @@ async function walk(dir, out = []) {
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)
else if (e.isFile() && e.name.endsWith('.md')) out.push(full)
}
return out
}
@@ -126,6 +130,30 @@ function snippets(text, terms, max = 3) {
return out
}
// ponytail: bounded windows cover the whole note without a second index.
// A persistent chunk index can replace this when the corpus latency warrants it.
export function evidenceExcerpt(text, topic) {
const terms = uniq(tokens(topic))
const windows = []
for (let start = 0; start < text.length; start += 800) {
const body = text.slice(start, start + 1000)
const found = new Set(tokens(body))
windows.push({ start, body, score: terms.filter(t => found.has(t)).length })
}
return windows.sort((a, b) => b.score - a.score || a.start - b.start)
.slice(0, 2).sort((a, b) => a.start - b.start)
.map(w => `[символы ${w.start + 1}–${w.start + w.body.length}]\n${w.body}`)
.join('\n\n').slice(0, EXCERPT)
}
export function cloudReadable(file, taxonomy) {
const classification = classifyFile(file, taxonomy)
if (classification.undetermined || !['public', 'infra', 'text'].includes(classification.klass)) return false
// Directory ancestry can raise sensitivity even when frontmatter omits the
// section or the note lives in a nested folder inside a private section.
return !path.resolve(file).split(path.sep).some(segment => ['personal', 'pd'].includes(taxonomy.by_section[segment]))
}
function frontmatterSubject(text) {
if (!text.startsWith('---')) return null
const end = text.indexOf('\n---', 3)
@@ -142,7 +170,7 @@ function frontmatterSubject(text) {
}
async function logQuery(entry) {
const file = path.resolve('.mnemazine', 'state', 'kb-search-log.jsonl')
const file = path.resolve(process.env.MNEMAZINE_SEARCH_LOG || path.join('.mnemazine', 'state', 'kb-search-log.jsonl'))
await fs.mkdir(path.dirname(file), { recursive: true })
await fs.appendFile(file, `${JSON.stringify(entry)}\n`, 'utf8')
}
@@ -261,7 +289,7 @@ function assignFacet(note, facets) {
async function extractShard(topic, shard, facet) {
if (DEEP && llmAvailable(PROVIDER)) {
const blob = shard.map(n =>
fenceUntrusted('NOTE', `### ${n.rel}\n${n.text.slice(0, EXCERPT)}`)).join('\n\n')
fenceUntrusted('NOTE', `### ${n.rel}\n${evidenceExcerpt(n.text, topic)}`)).join('\n\n')
const focus = facet ? `\nФокус-ось этого шарда: «${facet}» — приоритет находкам по этой оси (но не пропускай иное важное по теме).` : ''
const prompt = `Ты агент-исследователь. Тема: "${topic}".${focus}
Из заметок ниже выбери ТОЛЬКО релевантное теме. Для каждой находки: note (путь заметки), source (URL/ссылка из заметки, если есть), insight (1-2 предложения по-русски — что важного для темы), relevance (1-5). Ничего не выдумывай сверх заметок.
@@ -269,7 +297,8 @@ async function extractShard(topic, shard, facet) {
${blob}`
try {
const out = await llmJson(prompt, FINDINGS_SCHEMA, { provider: PROVIDER, tools: [] })
return (out.findings || []).filter(f => f.insight && f.relevance >= 2)
return (out.findings || []).filter(f => f.insight && f.relevance >= 2 && shard.some(n => n.rel === f.note))
.map(f => ({ ...f, source: shard.find(n => n.rel === f.note).text.includes(f.source || '\0') && /^https?:\/\//.test(f.source || '') ? f.source : '' }))
} catch (e) {
console.error(`[kb-search] shard agent failed: ${e.message}; local fallback`)
}
@@ -286,10 +315,9 @@ ${blob}`
// One agent per finding, judging 3 lenses at once (grounded/relevant/actionable)
// against the note's own text. Bounded (K calls). Drops ungrounded findings —
// the anti-hallucination gate (§6 claim->content). Opt-in via VERIFY.
async function verifyFindings(topic, findings, textByNote) {
if (!VERIFY || !DEEP || !llmAvailable(PROVIDER) || !findings.length) return { kept: findings, dropped: 0 }
export async function verifyFindings(topic, findings, textByNote, verify = llmJson, enabled = VERIFY && DEEP && llmAvailable(PROVIDER)) {
if (!enabled || !findings.length) return { kept: findings, dropped: 0 }
const top = findings.slice(0, MAX_VERIFY)
const rest = findings.slice(MAX_VERIFY)
const verdicts = []
await mapLimit(top, CONCURRENCY, async (f, idx) => {
const note = textByNote.get(f.note) || ''
@@ -297,12 +325,12 @@ async function verifyFindings(topic, findings, textByNote) {
"${f.insight}"
Оцени по 3 осям относительно текста заметки ниже: grounded (находка реально опирается на текст, не выдумана), relevant (по теме), actionable (полезна на практике). Верни булевы + reason.
${fenceUntrusted('NOTE', note.slice(0, EXCERPT))}`
try { verdicts[idx] = await llmJson(prompt, VERDICT_SCHEMA, { provider: PROVIDER, tools: [] }) }
catch (e) { console.error(`[kb-search] verify failed for ${f.note}: ${e.message}; keeping finding`); verdicts[idx] = { grounded: true, relevant: true, actionable: true } }
${fenceUntrusted('NOTE', evidenceExcerpt(note, `${topic} ${f.insight}`))}`
try { verdicts[idx] = note ? await verify(prompt, VERDICT_SCHEMA, { provider: PROVIDER, tools: [], dataClass: 'text' }) : null }
catch (e) { console.error(`[kb-search] verify failed for ${f.note}: ${e.message}; finding withheld`); verdicts[idx] = null }
})
const kept = top.filter((_, i) => verdicts[i]?.grounded !== false).concat(rest)
return { kept, dropped: top.length - (kept.length - rest.length) }
const kept = top.filter((_, i) => verdicts[i]?.grounded === true && verdicts[i]?.relevant === true)
return { kept, dropped: findings.length - kept.length }
}
// --- orchestrator: synthesize findings into a report -------------------------
@@ -313,7 +341,7 @@ async function synthesize(topic, findings, facets = []) {
const prompt = `Ты оркестратор. Собери из находок агентов справку по теме "${topic}" на РУССКОМ, стиль humanizer — живо, ясно, по делу, без воды и канцелярита. Дедуплицируй, сгруппируй по под-темам (themes), отметь связи (connections), противоречия (contradictions), пробелы знаний (gaps) и следующие шаги (next). Не выдумывай сверх находок.${axes}
Находки:
${blob}`
${fenceUntrusted('FINDINGS', blob)}`
try { return await llmJson(prompt, SYNTH_SCHEMA, { provider: PROVIDER }) }
catch (e) { console.error(`[kb-search] synthesis failed: ${e.message}; local assembly`) }
}
@@ -342,7 +370,7 @@ function renderReport(topic, report, meta) {
L.push(`> Поиск по базе знаний · ${meta.stamp} · просмотрено ${meta.scanned} заметок, отобрано ${meta.candidates}, находок ${meta.findings} · режим: ${meta.deep ? 'рой агентов (deep)' : 'локальный'}`, '')
if (meta.facets?.length) L.push(`> Оси разбора: ${meta.facets.join(' · ')}`, '')
if (meta.droppedNotes) L.push(`> ⚠️ Лимит стоимости: ${meta.droppedNotes} заметок-кандидатов не разобраны (--max-shards). Подними лимит для полного охвата.`, '')
if (meta.droppedByVerify) L.push(`> 🔎 Verify: ${meta.droppedByVerify} находок отброшено как необоснованные.`, '')
if (meta.droppedByVerify) L.push(`> Проверка: не включено ${meta.droppedByVerify} находок (нет подтверждения, ошибка проверки или предел проверок).`, '')
L.push('## Главное', '', report.summary || '—', '')
if (report.themes?.length) {
L.push('## По под-темам', '')
@@ -361,17 +389,27 @@ function renderReport(topic, report, meta) {
}
// --- main --------------------------------------------------------------------
async function run(topic, vault, outDir, { stdout = false, json = false } = {}) {
async function run(topic, vault, outDir, { stdout = false, json = false, resultJson = false } = {}) {
const stamp = new Date().toISOString()
const { terms, facets } = await plan(topic)
// RECON
const files = await walk(vault)
const scored = []
const taxonomy = DEEP ? loadTaxonomy() : null
let withheld = 0
const project = arg('project')
for (const f of files) {
const text = await fs.readFile(f, 'utf8').catch(() => '')
if (!text) continue
if (project && !parseFrontmatter(text).fields?.projects?.includes(project)) continue
if (DEEP) {
// Cloud research only sees ordinary/public notes. A missing class must
// not inherit the LLM bridge's default infra class.
if (!cloudReadable(f, taxonomy)) { withheld++; continue }
}
const rel = path.relative(vault, f)
const score = scoreNote(text, rel, terms)
// Expanded synonyms are alternatives, never extra mandatory query words.
const score = Math.max(scoreNote(text, rel, tokens(topic)), ...terms.map(term => scoreNote(text, rel, [term])))
if (score > 0) scored.push({ rel, text, score, subject: frontmatterSubject(text), url: text.match(/https?:\/\/\S+/)?.[0] || '' })
}
scored.sort((a, b) => b.score - a.score)
@@ -384,7 +422,7 @@ async function run(topic, vault, outDir, { stdout = false, json = false } = {})
snippets: snippets(n.text, terms)
}))
await logQuery({ ts: stamp, topic, mode: 'json', results: results.length })
process.stdout.write(`${JSON.stringify({ topic, scanned: files.length, results }, null, 2)}\n`)
process.stdout.write(`${JSON.stringify({ topic, scanned: files.length, withheld, results }, null, 2)}\n`)
return null
}
// FAN-OUT — shard within facet groups so each shard carries one focus axis
@@ -416,12 +454,22 @@ async function run(topic, vault, outDir, { stdout = false, json = false } = {})
catch (e) { console.error(`[kb-search] shard failed: ${e.message}`) }
})
findings.sort((a, b) => (b.relevance || 0) - (a.relevance || 0))
// VERIFY (2B, opt-in): drop ungrounded top findings before synthesis.
// VERIFY: withhold unchecked findings before synthesis.
const textByNote = new Map(candidates.map(c => [c.rel, c.text]))
const { kept, dropped: droppedByVerify } = await verifyFindings(topic, findings, textByNote)
// 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) })
let md = renderReport(topic, report, { stamp, scanned: files.length, candidates: candidates.length, findings: kept.length, deep: DEEP && llmAvailable(PROVIDER), droppedNotes, droppedByVerify, facets: facets.map(f => f.label) })
if (withheld) md += `\n\nИз облачной обработки исключено заметок по классу данных: ${withheld}. Для локального поиска выключи deep.\n`
if (kept.length) md += '\n\n## Источники ответа\n\n' + [...new Set(kept.map(f => f.note))].map(note => {
const target = path.join(vault, note)
return `- [${note.replace(/[\[\]]/g, '')}](<${target.replace(/>/g, '%3E')}>)`
}).join('\n') + '\n'
if (resultJson) {
const sources = [...new Set(kept.map(f => f.note))].map(note => ({ title: note, path: path.join(vault, note) }))
process.stdout.write(JSON.stringify({ text: md, sources, stats: { scanned: files.length, findings: kept.length, withheld, droppedByVerify, droppedNotes } }) + '\n')
return null
}
await logQuery({ ts: stamp, topic, mode: DEEP && llmAvailable(PROVIDER) ? 'deep' : 'local', results: kept.length })
if (stdout) {
process.stdout.write(md.endsWith('\n') ? md : `${md}\n`)
@@ -451,6 +499,7 @@ async function selftest() {
console.log('selftest ok')
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
if (SELFTEST) {
selftest().catch(e => { console.error(e.message); process.exit(1) })
} else {
@@ -461,11 +510,12 @@ if (SELFTEST) {
// fail-closed: каталог отчета внутри корпуса превращает просмотр в правку
// корпуса — отказ держит код, а не привычку (план П08). С --stdout файла нет.
const relOut = path.relative(vault, outDir)
if (!STDOUT && !JSON_OUT && (relOut === '' || (!relOut.startsWith('..') && !path.isAbsolute(relOut)))) {
if (!STDOUT && !JSON_OUT && !RESULT_JSON && (relOut === '' || (!relOut.startsWith('..') && !path.isAbsolute(relOut)))) {
console.error(`[kb-search] отказ: каталог отчета внутри корпуса (out=${outDir}, vault=${vault}). Укажи --out вне корпуса или --stdout.`)
process.exit(2)
}
run(topic, vault, outDir, { stdout: STDOUT, json: JSON_OUT })
run(topic, vault, outDir, { stdout: STDOUT, json: JSON_OUT, resultJson: RESULT_JSON })
.then(p => { if (p) console.log(p) })
.catch(e => { console.error(`[kb-search] ${e.message}`); process.exit(1) })
}
}
+74 -66
View File
@@ -14,10 +14,11 @@
//
// Default pipeline never calls an LLM — only the opt-in --deep path does.
import { spawnSync, spawn } from 'node:child_process'
import { existsSync, promises as fs } from 'node:fs'
import { appendFileSync, promises as fs } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { loadRegistry, orderCandidates, pickSchemaAdapter } from './mnemazine-cli-router.mjs'
import { resolveExecutable, readCooldown, recordCooldown, classifyProcessFailure } from './mnemazine-cli-runtime.mjs'
const PROGRESS_EVERY_MS = Number(process.env.MNEMAZINE_LLM_PROGRESS_EVERY_MS || '30000')
const PROGRESS = process.env.MNEMAZINE_LLM_PROGRESS !== '0'
@@ -27,7 +28,6 @@ const TIMEOUT_MS = Number(process.env.MNEMAZINE_LLM_TIMEOUT_MS || '420000')
// this machine). A CLI without stdin_prompt gets the prompt in argv; over this we
// 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) {
@@ -48,6 +48,22 @@ function runProc(bin, args, { input, timeoutMs, cwd, label } = {}) {
// убит руками. Родитель по-прежнему дожидается ребенка: unref не зовется.
try { child = spawn(bin, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'], detached: true }) }
catch (e) { return resolve({ status: 1, stdout: '', stderr: String(e.message) }) }
// The durable job owns cancellation of every detached LLM group, including
// CLI wrappers that outlive the pipeline process. PID start time prevents
// killing an unrelated process after a job/worker restart.
if (child.pid && process.env.MNEMAZINE_JOB_GROUPS) {
try {
const started = spawnSync('ps', ['-p', String(child.pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout?.trim()
if (!started) throw new Error('cannot record LLM process identity')
appendFileSync(process.env.MNEMAZINE_JOB_GROUPS, JSON.stringify({ pid: child.pid, started }) + '\n', { mode: 0o600 })
} catch (error) {
try { process.kill(-child.pid, 'SIGKILL') } catch { /* child already exited */ }
child.on('error', () => {})
child.stdin.on('error', () => {})
child.stdin.end()
return resolve({ status: 1, stdout: '', stderr: `job process tracking failed: ${error.message}` })
}
}
let out = '', err = '', killed = false, grace = null
const started = Date.now()
progress(label, `start timeout=${timeoutMs || 0}ms`)
@@ -106,41 +122,17 @@ function providerChain(dataClass, capabilities) {
}
// --- 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',
path.join(HOME, '.local/bin/claude'),
path.join(HOME, '.npm-global/bin/claude'),
'/Applications/Claude.app/Contents/Resources/claude'
]
}
const _binCache = {}
// Resolve executable files from PATH/common install directories; never
// interpolate a registry value into shell code or invoke auth probes.
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
return resolveExecutable(binName)
}
function binExists(bin) {
if (bin.includes('/')) return existsSync(bin)
const which = spawnSync(process.env.SHELL || '/bin/zsh', ['-lic', `command -v ${bin}`], { encoding: 'utf8' })
return which.status === 0 && Boolean(which.stdout.trim())
return Boolean(bin && resolveExecutable(bin))
}
function requireBin(provider, entry) {
@@ -176,7 +168,7 @@ export function providerCostTier(provider) {
}
function needsWebTools(opts = {}) {
return (opts.tools || []).some(tool => WEB_TOOL_RE.test(tool))
return (opts.capabilities || []).includes('web_search') || (opts.tools || []).some(tool => WEB_TOOL_RE.test(tool))
}
function ensureWebCapable(provider, entry, opts) {
@@ -190,8 +182,9 @@ function ensureWebCapable(provider, entry, opts) {
// 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))
const caps = [...(opts.capabilities || []), ...(needsWebTools(opts) ? ['web_search'] : [])]
return orderCandidates(registry(), { dataClass: opts.dataClass || 'infra', capabilities: caps, tier: opts.tier }).candidates
.map(entry => entry.name).filter(name => name !== provider && llmAvailable(name))
}
// --- untrusted input fence (unchanged; primary prompt-injection defense) -------
@@ -259,11 +252,12 @@ function assertSchema(value, schema, where = '$') {
}
function procError(label, res) {
const stderr = String(res.stderr || '').trim()
if (stderr) return `${label} failed (status ${res.status}): ${stderr.slice(-400)}`
const stdout = String(res.stdout || '').trim()
if (stdout) return `${label} failed (status ${res.status}): ${stdout.slice(-400)}`
return `${label} failed (status ${res.status}): empty stderr/stdout`
const reason = classifyProcessFailure(res)
const error = new Error(`${label} failed (${reason}; status ${res.status})`)
error.reason = reason
const retry = `${res.stderr || ''}\n${res.stdout || ''}`.match(/\bretry-after\s*:\s*(\d+)\b/i)
if (retry) error.retryAfterMs = Number(retry[1]) * 1000
return error
}
// Prompt goes on stdin when the CLI declares stdin_prompt; otherwise as the last
@@ -305,7 +299,7 @@ async function inlineSchemaJson(provider, entry, prompt, schema, opts) {
args = [...args, '--json-schema', JSON.stringify(strictOutputSchema(schema))]
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))
if (res.status !== 0) throw procError(`${provider} json`, res)
return extractJson(unwrap(res.stdout))
}
@@ -321,7 +315,7 @@ async function fileSchemaJson(provider, entry, prompt, schema, 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))
if (res.status !== 0) throw procError(`${provider} exec`, res)
const raw = await fs.readFile(outFile, 'utf8').catch(() => '')
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)}`) }
@@ -335,7 +329,7 @@ async function inPromptJson(provider, entry, prompt, schema, opts) {
const full = `${prompt}\n\nReturn ONLY a single JSON object matching this JSON Schema (no prose, no code fence):\n${JSON.stringify(strictOutputSchema(schema))}`
const { 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))
if (res.status !== 0) throw procError(`${provider} json`, res)
const output = extractJson(unwrap(res.stdout))
assertSchema(output, strictOutputSchema(schema))
return output
@@ -354,24 +348,7 @@ async function jsonOnce(provider, prompt, schema, opts) {
// 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)
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')
return dispatch(opts, (candidate, callOpts) => jsonOnce(candidate, prompt, schema, callOpts))
}
// --- plain-text path (no schema; vision/extraction fallback) ------------------
@@ -385,7 +362,7 @@ async function textOnce(provider, prompt, opts) {
args = insertCwd(args, opts.cwd || process.cwd())
args = [...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))
if (res.status !== 0) throw procError(`${provider} exec`, res)
return String(res.stdout || '').trim()
}
// Flat-invoke CLI (claude inline / kimi in-prompt): tools via --allowedTools
@@ -394,24 +371,55 @@ async function textOnce(provider, prompt, opts) {
if (adapter === 'json_schema_inline') args = withAllowedTools(args, opts)
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))
if (res.status !== 0) throw procError(`${provider} text`, res)
return unwrap(res.stdout).trim()
}
export async function llmText(prompt, opts = {}) {
return dispatch(opts, (candidate, callOpts) => textOnce(candidate, prompt, callOpts))
}
async function dispatch(opts, invoke) {
const provider = activeProvider(opts)
const dataClass = opts.dataClass || 'infra'
const admission = orderCandidates(registry(), { dataClass }).candidates.map(entry => entry.name)
opts.attempts = []
delete opts.provider_used
// A forbidden explicit/owner-pinned primary is a policy error, never a
// reason to move private material to a more permissive cloud provider.
if (!admission.includes(provider)) {
opts.attempts.push({ provider, status: 'denied', reason: 'privacy' })
throw new Error(`Provider ${provider} is not admitted for data class ${dataClass}`)
}
const caps = [...(opts.capabilities || []), ...(needsWebTools(opts) ? ['web_search'] : [])]
const allowed = orderCandidates(registry(), { dataClass, capabilities: caps, tier: opts.tier }).candidates
.filter(entry => pickSchemaAdapter(entry)).map(entry => entry.name)
const chain = [...new Set([provider, ...fallbackProviders(provider, opts)])]
const requestedBudget = Number(opts.totalTimeoutMs ?? process.env.MNEMAZINE_LLM_CHAIN_TIMEOUT_MS ?? TIMEOUT_MS)
const deadline = Date.now() + Math.max(1, Math.min(Number.isFinite(requestedBudget) ? requestedBudget : 420000, 1800000))
let lastError
for (const candidate of chain) {
if (!allowed.includes(candidate)) { opts.attempts.push({ provider: candidate, status: 'skipped', reason: 'capability_or_tier' }); continue }
const cooling = readCooldown(candidate)
if (cooling) { opts.attempts.push({ provider: candidate, status: 'skipped', reason: cooling.reason, until: cooling.until }); continue }
const remaining = deadline - Date.now()
if (remaining <= 0) { lastError = new Error('CLI chain time budget exhausted'); break }
try {
const result = await textOnce(candidate, prompt, opts)
opts.provider_used = candidate // actual executor, so a fallback is never silent
const perCall = Number(opts.timeoutMs || TIMEOUT_MS)
const result = await invoke(candidate, { ...opts, timeoutMs: Math.max(1, Math.min(Number.isFinite(perCall) ? perCall : remaining, remaining)) })
opts.attempts.push({ provider: candidate, status: 'completed' })
opts.provider_used = candidate
return result
}
catch (error) {
lastError = error
progress(opts.label || 'text', `fallback ${candidate}: ${String(error.message || error).slice(0, 160)}`)
const reason = error.reason || 'invalid_output_or_unavailable'
// Provider stderr and malformed output may echo the original document.
// Return only a category across the bridge, including on final failure.
lastError = Object.assign(new Error(`CLI ${candidate} failed: ${reason}`), { reason })
const cooling = recordCooldown(candidate, reason, { retryAfterMs: error.retryAfterMs })
opts.attempts.push({ provider: candidate, status: 'failed', reason, ...(cooling ? { until: cooling.until } : {}) })
progress(opts.label || 'llm', `fallback ${candidate}: ${reason}`)
}
}
throw lastError || new Error('no provider available for llmText')
throw lastError || new Error('No admitted CLI available: missing capability or active cooldown')
}
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env node
// Coordinator-only bridge. The god sandbox must not expose this CLI or the jobs root.
import { execFileSync } from 'node:child_process';
import { closeSync, constants, fstatSync, lstatSync, mkdtempSync, openSync, readSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { parseArgs } from 'node:util';
const jobsCLI = fileURLToPath(new URL('./mnemazine-jobs.mjs', import.meta.url));
const MAX_BYTES = 256 * 1024;
const token = /^[a-z0-9][a-z0-9_-]{0,127}$/i;
function core(root, args) {
try {
return JSON.parse(execFileSync(process.execPath, [jobsCLI, ...args, '--root', root], {
encoding: 'utf8', maxBuffer: 8 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'],
}));
} catch {
// Core stderr may contain vault paths or source text; only coordinator diagnostics may expose it.
throw new Error('JOBS_ERROR: операция очереди не выполнена; проверьте журнал координатора');
}
}
function view(job) {
return { job: {
id: job.id, kind: job.kind, status: job.status, provenance: job.provenance,
created_at: job.created_at, updated_at: job.updated_at,
// Ingest logs can mention unrelated vault material. Return a receipt, never those logs.
result: job.status === 'completed' ? { accepted: true } : null,
citations: [], error: job.error ? 'Обработка не завершена; подробности у координатора' : null,
} };
}
export function runAdapter(argv) {
const { values: v, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
root: { type: 'string' }, god: { type: 'string' }, run: { type: 'string' },
project: { type: 'string' }, worktree: { type: 'string' }, file: { type: 'string' },
id: { type: 'string' }, query: { type: 'string' }, mode: { type: 'string' }, 'no-start': { type: 'boolean' },
} });
const [command] = positionals;
if (positionals.length !== 1 || !['submit', 'status', 'cancel', 'retry', 'search', 'brief'].includes(command)) {
throw new Error('Ожидается submit, status, cancel, retry, search или brief');
}
if (!v.root || !isAbsolute(v.root)) throw new Error('--root должен быть абсолютным путём очереди координатора');
for (const key of ['god', 'run', 'project']) {
if (!token.test(v[key] ?? '')) throw new Error(`Некорректный --${key}`);
}
const provenance = { client: 'olympuz', god: v.god, run: v.run, project: v.project };
if (command === 'search' || command === 'brief') {
throw new Error('PROJECT_SCOPE_UNAVAILABLE: поиск для богов закрыт до проверки доступа к корпусу проекта');
}
if (command !== 'submit') {
if (!v.id) throw new Error('Требуется --id');
const { job } = core(v.root, ['status', '--id', v.id, '--no-start']);
if (job.kind !== 'ingest' || Object.entries(provenance).some(([key, value]) => job.provenance?.[key] !== value)) {
throw new Error('JOB_SCOPE_MISMATCH: задача не принадлежит этому запуску бога');
}
return view(command === 'status' ? job : core(v.root, [command, '--id', v.id, ...(v['no-start'] ? ['--no-start'] : [])]).job);
}
if (!v.worktree || !isAbsolute(v.worktree) || !v.file || !isAbsolute(v.file)) {
throw new Error('Требуются абсолютные --worktree и --file');
}
if (v.mode !== 'deep') throw new Error('Требуется --mode deep: intake использует внешний конвейер; разрешение задаёт координатор');
const worktree = realpathSync(v.worktree);
const research = join(worktree, 'research');
const source = join(realpathSync(dirname(v.file)), basename(v.file));
const name = basename(source);
if (!/^agent-research--[a-z0-9][a-z0-9-]*--[a-z0-9][a-z0-9-]*\.md$/.test(name)
|| !name.startsWith(`agent-research--${v.project}--`)
|| dirname(source) !== research || lstatSync(research).isSymbolicLink()) {
throw new Error('SOURCE_SCOPE_MISMATCH: нужен agent-research--PROJECT--SLUG.md в worktree/research');
}
const fd = openSync(source, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
let content;
try {
const stat = fstatSync(fd);
if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_BYTES || realpathSync(research) !== research) {
throw new Error('Источник должен быть обычным файлом без ссылок, не больше 256 KiB');
}
const buffer = Buffer.alloc(MAX_BYTES + 1);
let bytes = 0;
while (bytes < buffer.length) {
const read = readSync(fd, buffer, bytes, buffer.length - bytes, null);
if (!read) break;
bytes += read;
}
if (bytes > MAX_BYTES) throw new Error('Источник превышает 256 KiB');
content = buffer.subarray(0, bytes);
} finally { closeSync(fd); }
// ponytail: a private temporary snapshot closes the god-file mutation window; core owns persistence.
const stage = mkdtempSync(join(tmpdir(), 'mnemazine-olympuz-'));
try {
const snapshot = join(stage, name);
// Delivery time lives in job.created_at; stable source bytes preserve core deduplication on retries.
const stamp = `<!-- olympuz: god=${v.god} run=${v.run} project=${v.project} -->\n`;
writeFileSync(snapshot, Buffer.concat([Buffer.from(stamp), content]), { mode: 0o600 });
const { job } = core(v.root, ['submit', '--kind', 'ingest', '--mode', 'deep', '--file', snapshot,
'--project', v.project, '--provenance', JSON.stringify(provenance), ...(v['no-start'] ? ['--no-start'] : [])]);
return view(job);
} finally { rmSync(stage, { recursive: true, force: true }); }
}
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
try { console.log(JSON.stringify(runAdapter(process.argv.slice(2)))); }
catch (error) { console.error(JSON.stringify({ error: error.message })); process.exitCode = 1; }
}
+55 -8
View File
@@ -200,6 +200,7 @@ async function demoSmoke() {
// Список копирования ручной, и врезка Метиды его не пополнила - гейт краснел на исправном коде.
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-metiz.mjs'), path.join(scripts, 'mnemazine-metiz.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-llm.mjs'), path.join(scripts, 'mnemazine-llm.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-runtime.mjs'), path.join(scripts, 'mnemazine-cli-runtime.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-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'))
@@ -208,7 +209,7 @@ async function demoSmoke() {
await fs.copyFile(path.join(ROOT, 'config/project-categories.json'), path.join(config, 'project-categories.json'))
await fs.writeFile(path.join(config, 'cli-registry.local.json'), '{}\n', 'utf8')
await must('demo intake smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
const mixedRun = await run(process.execPath, ['scripts/mnemazine-run.mjs'], {
env: {
MNEMAZINE_ROOT: temp,
MNEMAZINE_INBOX: inbox,
@@ -220,10 +221,18 @@ async function demoSmoke() {
MNEMAZINE_FINISH: '0'
}
})
if (mixedRun.code === 0) throw new Error('demo smoke failed: mixed batch with unextractable input passed')
if (!existsSync(path.join(inbox, 'example-guide.md')) || !existsSync(path.join(inbox, 'empty-source.bin'))) throw new Error('demo smoke failed: failed batch archived an input')
if ((await listFiles(path.join(temp, '.mnemazine/archive'))).length) throw new Error('demo smoke failed: failed batch must archive nothing')
// Isolate the rejected fixture; only the now-complete batch may archive.
await fs.rename(path.join(inbox, 'empty-source.bin'), path.join(temp, 'empty-source.bin'))
await must('demo validated-source archive smoke', process.execPath, ['scripts/mnemazine-run.mjs'], {
env: { MNEMAZINE_ROOT: temp, MNEMAZINE_INBOX: inbox, MNEMAZINE_VAULT: vault, MNEMAZINE_FINISH: '0' }
})
const inboxFiles = await fs.readdir(inbox)
if (inboxFiles.length !== 1 || inboxFiles[0] !== 'empty-source.bin') {
throw new Error(`demo smoke failed: expected only unextractable source in inbox (${inboxFiles.join(', ')})`)
if (inboxFiles.length !== 0) {
throw new Error(`demo smoke failed: expected validated inbox to be empty (${inboxFiles.join(', ')})`)
}
const notes = (await listFiles(vault))
@@ -259,8 +268,8 @@ async function demoSmoke() {
}
})
const cachedInboxFiles = await fs.readdir(inbox)
if (cachedInboxFiles.length !== 1 || cachedInboxFiles[0] !== 'empty-source.bin') {
throw new Error(`demo cached smoke failed: expected only unextractable source in inbox (${cachedInboxFiles.join(', ')})`)
if (cachedInboxFiles.length !== 0) {
throw new Error(`demo cached smoke failed: expected validated inbox to be empty (${cachedInboxFiles.join(', ')})`)
}
const archivedAfterCachedRun = await listFiles(path.join(temp, '.mnemazine/archive'))
if (archivedAfterCachedRun.length !== 2) throw new Error(`demo cached smoke failed: expected 2 archived finalized sources, got ${archivedAfterCachedRun.length}`)
@@ -286,6 +295,7 @@ async function strictArchiveGateSmoke() {
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-humanize-gate.mjs'), path.join(scripts, 'mnemazine-humanize-gate.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-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-runtime.mjs'), path.join(scripts, 'mnemazine-cli-runtime.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-router.mjs'), path.join(scripts, 'mnemazine-cli-router.mjs'))
await fs.copyFile(path.join(ROOT, 'scripts/mnemazine-cli-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'))
@@ -390,7 +400,35 @@ Local source refs:
- Держать эту ноту как smoke fixture для strict archive gate.
`)
await must('strict archive gate smoke:good', process.execPath, ['scripts/mnemazine-run.mjs'], {
const noCompletion = await run(process.execPath, ['scripts/mnemazine-run.mjs'], {
env: { MNEMAZINE_ROOT: goodTemp, MNEMAZINE_INBOX: good.inbox, MNEMAZINE_VAULT: good.vault,
MNEMAZINE_DEEP: '1', MNEMAZINE_REQUIRE_DEEP: '1', MNEMAZINE_SYNTHESIZE: '0', MNEMAZINE_FINISH: '0' }
})
if (noCompletion.code === 0 || !existsSync(good.sourceFile)) throw new Error('strict archive gate smoke failed: cached knowledge without completion must retain source')
if (!`${noCompletion.stdout}\n${noCompletion.stderr}`.includes('completion failed before archive')) throw new Error('strict archive gate smoke failed: expected explicit missing-completion rejection')
// Strict cached intake still requires real completion gates with FINISH=0.
// Supply measured fixture baseline and truthful fixture reports, never a PASS shim.
for (const name of ['complete-check', 'coverage-check', 'spec-ceiling', 'report-quality-gate']) {
await fs.copyFile(path.join(ROOT, `scripts/mnemazine-${name}.mjs`), path.join(goodTemp, `scripts/mnemazine-${name}.mjs`))
}
const goodState = path.join(goodTemp, '.mnemazine/state')
const goodReports = path.join(goodTemp, 'reports')
await fs.mkdir(goodState, { recursive: true })
await fs.mkdir(goodReports, { recursive: true })
await fs.mkdir(path.join(good.vault, '99 Система'), { recursive: true })
await fs.writeFile(path.join(good.vault, '99 Система/_ПРОЕКТЫ.md'), '# Проекты тестовой базы\n\n## Мнемозина\n\nЛокальная проверка конвейера.\n', 'utf8')
await must('strict fixture measured baseline', process.execPath, [path.join(goodTemp, 'scripts/mnemazine-spec-ceiling.mjs'), '--update', '--vault', good.vault], {
env: { MNEMAZINE_ROOT: goodTemp, MNEMAZINE_VAULT: good.vault }
})
await fs.writeFile(path.join(goodReports, 'visual-knowledge-report.html'), `<!doctype html><html lang="ru"><body>
<h1>Отчет Mnemazine</h1><h2>Новые и обновленные знания</h2>
<p>Синтез: тестовый материал описывает преобразование документов в текст и сохраняет ссылки на происхождение. Эта фикстура проверяет порядок завершения локального конвейера и не представляет результат нового внешнего исследования.</p>
<h2>Источники</h2><a href="https://github.com/microsoft/markitdown">Репозиторий</a><a href="https://github.com/microsoft/markitdown/issues">Обсуждения</a><a href="https://github.com/microsoft/markitdown/releases">Выпуски</a>
<h2>Применение</h2><p>Проверить сохранность источника до успешного завершения всех обязательных проверок.</p>
<h2>Проверка</h2><p>Используется заранее подготовленная локальная тестовая запись. Сетевые запросы и обращения к модели в этой проверке не выполняются.</p>
<h2>Следующее действие</h2><p>После успешной проверки перенести только покрытый тестовый источник в архив.</p></body></html>`, 'utf8')
await fs.writeFile(path.join(goodState, 'last-action-brief.md'), '# Короткий отчет Mnemazine\n\n## Статус\n\nПодготовлена локальная фикстура проверки очередности архивирования.\n\n## Следующие действия\n\nЗавершить проверки и сохранить источник при любом отказе.\n', 'utf8')
await must('strict archive gate smoke:real-completion', process.execPath, ['scripts/mnemazine-run.mjs'], {
env: {
MNEMAZINE_ROOT: goodTemp,
MNEMAZINE_INBOX: good.inbox,
@@ -694,7 +732,8 @@ async function completeGateSmoke() {
}, null, 2), 'utf8')
// Потолок спеки для демо-корпуса (план П06 шаг 8): единственная демо-нота спеке
// не отвечает, потолок честно равен 1 — spec-ceiling --check из complete-check
// держится, а не краснеет. Пишется во временный MNEMAZINE_STATE, не в репозиторий.
// держится, а не краснеет. Runtime state изолирован; путь fixture baseline
// передается явно, чтобы не выбирать baseline другого (живого) корпуса.
await fs.writeFile(path.join(state, 'spec-ceiling.json'), JSON.stringify({
vault: path.join(ROOT, 'demo/vault'),
ceiling: 1
@@ -704,7 +743,8 @@ async function completeGateSmoke() {
MNEMAZINE_VAULT: path.join(ROOT, 'demo/vault'),
MNEMAZINE_INBOX: inbox,
MNEMAZINE_REPORTS: reports,
MNEMAZINE_STATE: state
MNEMAZINE_STATE: state,
MNEMAZINE_SPEC_CEILING: path.join(state, 'spec-ceiling.json')
}
})
}
@@ -924,6 +964,13 @@ async function searchEvalSmoke() {
// (LLM judge) is opt-in via `npm run search:eval -- --deep`, not in the gate.
await must('kb-search selftest', process.execPath, ['scripts/mnemazine-kb-search.mjs', '--selftest'])
await must('kb-search eval (Tier A)', process.execPath, ['tests/search-eval.mjs'])
await must('kb-search evidence regressions', process.execPath, ['tests/test-search-evidence.mjs'])
await must('durable jobs', process.execPath, ['tests/test-jobs.mjs'])
await must('CLI failover', process.execPath, ['tests/test-cli-failover.mjs'])
await must('prearchive validation', process.execPath, ['tests/test-prearchive-validation.mjs'])
await must('coverage hash', process.execPath, ['tests/test-coverage-hash.mjs'])
await must('shared vault lock', process.execPath, ['tests/test-vault-lock.mjs'])
await must('Olympuz jobs adapter', process.execPath, ['tests/test-olympuz-adapter.mjs'])
}
async function repoMetadataCheck() {
+30 -6
View File
@@ -9,6 +9,7 @@ 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'
import { acquireVaultLock } from './mnemazine-vault-lock.mjs'
const ROOT = process.env.MNEMAZINE_ROOT || path.resolve(process.cwd())
@@ -690,8 +691,8 @@ function finishGateOk(key, entry) {
// result.ok больше не литерал: прогон зеленый только если ноль файлов упало И
// каждый обязательный элемент finish.* в легальном состоянии. Коды гейтов,
// собранные finishRun, наконец читаются — до архива они решали, после архива
// теперь не «советуют», а считаются. finish === null (черновая ветка/FINISH=0):
// собранные finishRun, должны пройти до переноса оригиналов в архив.
// finish === null (черновая ветка/FINISH=0):
// решает только failed.
function computeRunOk(failed, finish) {
if (Number(failed || 0) !== 0) return false
@@ -703,6 +704,14 @@ function computeRunOk(failed, finish) {
return true
}
export async function archiveAfterValidation({ failed, finish, validate, items, archive = archiveFile }) {
if (!computeRunOk(failed, finish)) throw new Error('final validation failed before archive')
await validate()
const archived = []
for (const item of items) archived.push(await archive(item.file, item.hash))
return archived
}
async function finishRun(runStartedAt) {
const result = {}
result.tool_queue = runLocalNodeScript('mnemazine-tool-decision-queue.mjs', ['--changed-since', runStartedAt, '--session', new Date().toISOString().slice(0, 10)])
@@ -953,9 +962,21 @@ async function main() {
}, human.status || 1)
}
}
const archived = []
for (const item of toArchive) archived.push(await archiveFile(item.file, item.hash))
const finish = FINISH ? await finishRun(runStartedAt) : { skipped: true }
const pending = { ok: false, phase: 'pending_archive', pre_archive_ready: computeRunOk(failed, finish), archive_pending: toArchive.length, archived: 0, inbox: entries.length, processed, cached_only: cachedOnly, failed, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt }
await writeRunState(pending)
let archived
try {
archived = await archiveAfterValidation({ failed, finish, items: toArchive, validate: async () => {
if (!FINISH && !REQUIRE_DEEP) return
const check = runLocalNodeScript('mnemazine-complete-check.mjs', ['--before-archive', ...(REQUIRE_DEEP ? ['--require-deep'] : [])])
if (!check.ok) throw new Error(`completion failed before archive: ${check.stderr || check.stdout || check.reason || 'unknown error'}`)
} })
} catch (error) {
await writeRunState({ ...pending, pre_archive_ready: false, failure: error.message, finished_at: new Date().toISOString() })
console.error(error.message)
process.exit(1)
}
const result = { ok: computeRunOk(failed, finish), inbox: entries.length, processed, cached_only: cachedOnly, failed, archived: archived.length, deep: DEEP, deep_required: REQUIRE_DEEP, enrich_required: ENRICH_REQUIRED, strict_archive_knowledge: STRICT_ARCHIVE_KNOWLEDGE, synthesize, finish, vault: VAULT, started_at: runStartedAt, finished_at: new Date().toISOString() }
await writeRunState(result)
console.log(JSON.stringify(result, null, 2))
@@ -965,8 +986,11 @@ async function main() {
// а не импортируется. Импорт нужен пробе runLocalNodeScript (harness на две строки)
// и любому будущему потребителю экспортов — он не должен гонять пайплайн.
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main().catch(err => {
Promise.resolve().then(async () => {
const release = acquireVaultLock(VAULT)
try { await main() } finally { release() }
}).catch(err => {
console.error(err)
process.exit(1)
process.exit(err.code === 'MNEMAZINE_VAULT_BUSY' ? 75 : 1)
})
}
+6 -2
View File
@@ -721,7 +721,7 @@ ${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.
@@ -1019,7 +1019,7 @@ ${addedFacts}
- ${compact(atom.next, 240) || 'Применить в ближайшей задаче по теме кластера.'}
- Тема: ${clusterTitleRu(cluster.id)} — смотреть сюда, когда всплывет этот вопрос.
## Достоверность
## Проверка
- Статус проверки: **${v.status}**${v.note ? ` (${v.note})` : ''}.
${isVerified
@@ -1054,6 +1054,10 @@ if (argv.includes('--selftest')) {
for (const line of junk) if (!looksLikeCode(line)) throw new Error(`selftest: junk passed the filter: ${line}`)
for (const line of 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')
const fixtureCluster = { id: 'misc', records: [{ text: prose.join('\n'), source_ref: 'local-media:fixture' }] }
const draft = makeAtomNote(fixtureCluster, { title: 'Проверка заметки', what: prose[0], sources: [] }, { status: 'unknown' })
if (!/^## Проверка$/m.test(draft) || !/^## Проверка$/m.test(makeNote(fixtureCluster))) throw new Error('selftest: producer must use the human-layer verification section')
if (!draft.includes('verification_status: "unknown"') || !draft.includes('status: "draft"') || draft.includes('Утверждение сверено с указанными источниками')) throw new Error('selftest: section rename must not upgrade unverified facts')
console.log(JSON.stringify({ ok: true, selftest: 'source-scrape junk filter' }))
process.exit(0)
}
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env node
import { realpathSync, mkdirSync, readFileSync, writeFileSync, unlinkSync, rmdirSync } from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import { spawn, spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const ENV = 'MNEMAZINE_VAULT_LOCK'
function identity(pid) {
const result = spawnSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8' })
return result.status === 0 ? result.stdout.trim() : ''
}
function descendant(pid) {
let current = process.pid
for (let depth = 0; current > 1 && depth < 128; depth++) {
if (current === pid) return true
const result = spawnSync('ps', ['-p', String(current), '-o', 'ppid='], { encoding: 'utf8' })
current = Number(result.stdout?.trim())
}
return false
}
function location(vault) {
return path.join(realpathSync(vault), '.mnemazine-pipeline-lock')
}
export function ownsVaultLock(vault) {
try {
const owner = JSON.parse(readFileSync(path.join(location(vault), 'owner.json'), 'utf8'))
return owner.nonce === process.env[ENV] && Number.isInteger(owner.pid) &&
owner.start && identity(owner.pid) === owner.start && descendant(owner.pid)
} catch { return false }
}
export function acquireVaultLock(vault) {
if (ownsVaultLock(vault)) return () => {}
const dir = location(vault)
const owner = { pid: process.pid, start: identity(process.pid), nonce: randomUUID() }
if (!owner.start) throw new Error('Cannot determine pipeline process identity')
try { mkdirSync(dir, { mode: 0o700 }) } catch (error) {
if (error.code !== 'EEXIST') throw error
// ponytail: never steal stale locks; manual recovery avoids ABA races.
const busy = new Error(`Vault pipeline busy or interrupted: ${dir}. Retry after the running pipeline; inspect a stale lock before manual recovery.`)
busy.code = 'MNEMAZINE_VAULT_BUSY'
throw busy
}
try { writeFileSync(path.join(dir, 'owner.json'), JSON.stringify(owner), { flag: 'wx', mode: 0o600 }) }
catch (error) { try { rmdirSync(dir) } catch {} ; throw error }
const previous = process.env[ENV]
process.env[ENV] = owner.nonce
let released = false
const release = () => {
if (released) return
released = true
process.removeListener('exit', release)
try {
if (JSON.parse(readFileSync(path.join(dir, 'owner.json'), 'utf8')).nonce === owner.nonce) {
unlinkSync(path.join(dir, 'owner.json'))
rmdirSync(dir)
}
} catch {}
if (previous === undefined) delete process.env[ENV]
else process.env[ENV] = previous
}
// Cancellation can leave grandchildren draining: retain the lock for inspection.
release.abandon = () => { released = true; process.removeListener('exit', release) }
process.once('exit', release)
return release
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2)
const vault = args[1]
if (args[0] === '--check') process.exit(ownsVaultLock(vault) ? 0 : 1)
try {
if (args[0] !== '--vault' || args[2] !== '--' || !args[3]) throw new Error('Usage: --vault PATH -- COMMAND [ARGS]')
const release = acquireVaultLock(vault)
const child = spawn(args[3], args.slice(4), { stdio: 'inherit', env: process.env })
// Keep ownership until the child exits, including while cancellation drains it.
const signals = ['SIGTERM', 'SIGINT', 'SIGHUP']
const handlers = signals.map(signal => () => { release.abandon?.(); child.kill(signal) })
signals.forEach((signal, i) => process.on(signal, handlers[i]))
const finish = code => {
signals.forEach((signal, i) => process.removeListener(signal, handlers[i]))
release()
process.exitCode = code
}
child.once('error', error => { console.error(error.message); finish(1) })
child.once('exit', (code, signal) => finish(code ?? (signal === 'SIGINT' ? 130 : 143)))
} catch (error) {
console.error(error.message)
process.exitCode = error.code === 'MNEMAZINE_VAULT_BUSY' ? 75 : 1
}
}