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
+84
View File
@@ -0,0 +1,84 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { discoverProviders, resolveExecutable, readCooldown, recordCooldown, classifyProcessFailure } from '../scripts/mnemazine-cli-runtime.mjs'
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-cli-failover-'))
const previous = { ...process.env }
try {
process.env.MNEMAZINE_LLM = 'claude'
process.env.MNEMAZINE_LLM_PROGRESS = '0'
process.env.MNEMAZINE_CLI_COOLDOWNS = path.join(tmp, 'cooldowns')
process.env.FIXTURE_CALLS = path.join(tmp, 'calls')
delete process.env.MNEMAZINE_CLI_REGISTRY_LOCAL
delete process.env.MNEMAZINE_JOB_GROUPS
delete process.env.MNEMAZINE_LLM_FALLBACK
const mock = `#!${process.execPath}
const fs = require('node:fs'), path = require('node:path');
const name = path.basename(process.argv[1]);
fs.appendFileSync(process.env.FIXTURE_CALLS, name+'\\n');
if(name==='claude' && process.env.FIXTURE_MODE==='timeout') { setInterval(()=>{},1000); }
else if(name==='claude' && process.env.FIXTURE_MODE==='quota') { console.error('quota exceeded; private-token-fixture');process.exitCode=1; }
else if(name==='claude' && process.env.FIXTURE_MODE==='bad') { console.log('not json'); }
else { const value=JSON.stringify({ok:true}); const i=process.argv.indexOf('-o'); if(i>=0)fs.writeFileSync(process.argv[i+1],value); else console.log(value); }
`
for (const name of ['claude', 'codex', 'kimi']) {
const file = path.join(tmp, name); fs.writeFileSync(file, mock, { mode: 0o700 })
process.env[`MNEMAZINE_${name.toUpperCase()}_BIN`] = file
}
const { llmJson, llmText } = await import('../scripts/mnemazine-llm.mjs')
const schema = { type: 'object', additionalProperties: false, required: ['ok'], properties: { ok: { type: 'boolean' } } }
process.env.FIXTURE_MODE = 'quota'
const first = { provider: 'claude', dataClass: 'text' }
assert.deepEqual(await llmJson('fixture only', schema, first), { ok: true })
assert.equal(first.provider_used, 'kimi')
assert.equal(first.attempts[0].reason, 'quota')
assert(readCooldown('claude'))
const second = { provider: 'claude', dataClass: 'text' }
await llmJson('fixture only', schema, second)
assert.equal(second.attempts[0].status, 'skipped')
assert.equal(fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8').split('\n').filter(x => x === 'claude').length, 1)
const before = fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8')
for (const call of [() => llmJson('private fixture', schema, { provider: 'kimi', dataClass: 'pd' }),
() => llmText('private fixture', { provider: 'codex', dataClass: 'personal' })]) await assert.rejects(call, /not admitted/)
assert.equal(fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8'), before, 'denied primary cannot dispatch even a fallback')
const web = { provider: 'kimi', dataClass: 'text', capabilities: ['web_search'] }
await llmJson('fixture only', schema, web)
assert.equal(web.provider_used, 'codex')
assert.equal(web.attempts[0].reason, 'capability_or_tier')
process.env.MNEMAZINE_CLI_COOLDOWNS = path.join(tmp, 'nonquota')
process.env.FIXTURE_MODE = 'bad'
const malformed = { provider: 'claude', dataClass: 'text' }
await llmJson('fixture', schema, malformed)
assert.equal(malformed.provider_used, 'kimi', 'non-quota fallback remains supported')
assert.equal(readCooldown('claude'), null)
process.env.FIXTURE_MODE = 'timeout'
const timing = { provider: 'claude', dataClass: 'text', totalTimeoutMs: 80 }
const start = Date.now()
await assert.rejects(() => llmJson('fixture', schema, timing))
assert(Date.now() - start < 3000)
assert.equal(timing.attempts.length, 1, 'budget prevents another provider call')
assert.equal(classifyProcessFailure({ status: 0, stdout: 'quota exceeded' }), null)
assert.equal(classifyProcessFailure({ status: 1, stderr: 'insufficient permissions' }), 'process_error')
assert.equal(classifyProcessFailure({ status: 1, stderr: 'HTTP 429 too many requests' }), 'rate_limit')
const dir = path.join(tmp, 'durable')
recordCooldown('example', 'quota', { dir, now: 1000 })
recordCooldown('example', 'rate_limit', { dir, now: 2000 })
assert.equal(readCooldown('example', { dir, now: 3000 }).reason, 'quota', 'shorter concurrent record cannot downgrade cooldown')
assert.equal(readCooldown('example', { dir, now: 100000000 }), null)
const weird = path.join(tmp, 'binary with spaces;$(touch unsafe)')
fs.writeFileSync(weird, mock, { mode: 0o700 })
assert.equal(resolveExecutable(weird), weird)
assert.equal(resolveExecutable('$(touch should-not-exist)', { env: { PATH: tmp }, home: tmp }), null)
fs.writeFileSync(path.join(tmp, 'gemini'), mock, { mode: 0o700 })
const listed = discoverProviders({ env: { ...process.env, PATH: tmp }, home: tmp })
assert(listed.some(item => item.name === 'gemini' && item.installed && !item.supported))
assert(!JSON.stringify(listed).includes('private-token-fixture'))
assert.equal(fs.readFileSync(process.env.FIXTURE_CALLS, 'utf8').includes('gemini'), false, 'discovery executes no CLI')
console.log('CLI failover: admission, quota, shared cooldown, capabilities, deadline, safe discovery passed')
} finally {
for (const key of Object.keys(process.env)) if (!(key in previous)) delete process.env[key]
Object.assign(process.env, previous)
fs.rmSync(tmp, { recursive: true, force: true })
}
+33
View File
@@ -0,0 +1,33 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { createHash } from 'node:crypto'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const script = fileURLToPath(new URL('../scripts/mnemazine-coverage-check.mjs', import.meta.url))
const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-coverage-hash-'))
try {
const vault = path.join(temp, 'vault'), inbox = path.join(temp, 'inbox')
fs.mkdirSync(vault); fs.mkdirSync(inbox)
const source = path.join(inbox, 'renamed-source.txt')
const data = 'Fixture source content for independently calculated SHA-256 coverage.'
fs.writeFileSync(source, data)
const hash = createHash('sha256').update(data).digest('hex')
const note = `---\nstatus: "final"\nverified: подтвержден\nverification_status: "verified"\nenrichment: "external-research"\n---\n# Проверенная фикстура\n\n## Источники\n\nlocal-media:${hash.slice(0, 16)}\n\nПубличные источники:\n- https://example.com/source\n\n## Расширение знания\n\nФакты, добавленные до атомизации:\n- Первый проверенный факт фикстуры.\n- Второй проверенный факт фикстуры.\n`
const file = path.join(vault, 'knowledge.md')
const check = () => spawnSync(process.execPath, [script, '--vault', vault, '--inbox', inbox, '--json'], { encoding: 'utf8', timeout: 5000 })
fs.writeFileSync(file, note)
assert.equal(check().status, 0, 'renamed source covered by matching verified SHA-256 source_ref')
fs.writeFileSync(source, `${data} changed`)
assert.equal(check().status, 1, 'different bytes must not match old hash')
fs.writeFileSync(source, data)
fs.writeFileSync(file, note.replace('status: "final"', 'status: "draft"'))
assert.equal(check().status, 1, 'draft with correct source hash does not prove coverage')
fs.writeFileSync(file, note.replace('verified: подтвержден', 'verified: не-проверялось'))
assert.equal(check().status, 1, 'unverified source hash must not count')
fs.writeFileSync(file, 'Source: renamed-source.txt')
assert.equal(check().status, 0, 'existing basename contract remains intact')
console.log('coverage hash passed: renamed verified source, changed bytes, draft/unverified rejection, basename compatibility')
} finally { fs.rmSync(temp, { recursive: true, force: true }) }
+201
View File
@@ -0,0 +1,201 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawn, spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { JobQueue, pipelineFailure } from '../scripts/mnemazine-jobs.mjs'
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-jobs-test-'))
try {
const queue = new JobQueue(path.join(tmp, 'queue'))
const textQueue = new JobQueue(path.join(tmp, 'text-queue'))
const textInputs = ['https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'https://example.com/article', 'HTTPS://EXAMPLE.COM/article', 'Мнемозина']
for (const input of textInputs) {
const submitted = await textQueue.submit({ kind: 'ingest', mode: 'deep', text: ` ${input} ` })
assert.equal(submitted.input_text, input)
assert.equal(submitted.input_kind, /^https:/i.test(input) ? 'url' : 'title')
assert.equal((await textQueue.submit({ kind: 'ingest', mode: 'deep', text: input })).id, submitted.id)
assert.notEqual((await textQueue.submit({ kind: 'ingest', mode: 'deep', text: input, project: 'other' })).id, submitted.id)
assert.equal(submitted.files.length, 1)
assert.equal(submitted.files[0].original, undefined)
const snapshot = fs.readFileSync(submitted.files[0].snapshot, 'utf8')
assert(snapshot.includes(input))
if (submitted.input_kind === 'url') assert(snapshot.includes(`Источник: ${new URL(input).href}`))
assert.match(snapshot, /Это запрос на исследование, а не готовое знание/)
assert(snapshot.length > 80)
assert.equal(path.dirname(submitted.files[0].snapshot), path.join(textQueue.root, submitted.id, 'sources'))
}
for (const input of ['', ' ', 'file:///tmp/private', 'javascript:alert(1)', 'ftp://example.com/file', 'https://user:password@example.com', 'https://', 'https:example.com', 'www.example.com', 'x'.repeat(8193), 'test\u0000']) {
await assert.rejects(textQueue.submit({ kind: 'ingest', mode: 'deep', text: input }))
}
await assert.rejects(textQueue.submit({ kind: 'ingest', mode: 'deep', text: 'Название', files: ['/unused'] }), /either files or text/)
await assert.rejects(textQueue.submit({ kind: 'search', query: 'поиск', text: 'Название' }), /no intake inputs/)
const original = path.join(tmp, 'source.md')
fs.writeFileSync(original, '# Исходный материал\nПамять агентов.')
await assert.rejects(queue.submit({ kind: 'ingest', files: [original] }), /deep/)
const job = await queue.submit({ kind: 'ingest', mode: 'deep', files: [original, original] })
assert.equal(job.files.length, 1)
assert.equal((await queue.submit({ kind: 'ingest', mode: 'deep', files: [original] })).id, job.id)
fs.writeFileSync(original, 'Изменённый оригинал')
assert.match(fs.readFileSync(job.files[0].snapshot, 'utf8'), /Память/)
await queue.change(job.id, 'cancel')
assert.equal(queue.read(job.id).status, 'cancelled')
await queue.change(job.id, 'retry')
await queue.work({ once: true, execute: async () => { throw new Error('fixture failure') } })
assert.equal(queue.read(job.id).status, 'failed')
await queue.change(job.id, 'retry')
await queue.work({ once: true, execute: async () => ({ text: 'fixture completed' }) })
assert.equal(queue.read(job.id).status, 'completed')
assert.equal(fs.readFileSync(original, 'utf8'), 'Изменённый оригинал')
const pending = await queue.submit({ kind: 'search', query: 'память' })
await queue.transaction(() => { const j = queue.read(pending.id); j.status = 'running'; queue.save(j, 'fixture_crash') })
fs.mkdirSync(path.join(queue.root, '.worker-lock'))
fs.writeFileSync(path.join(queue.root, '.worker-lock/owner.json'), JSON.stringify({ pid: 99999999, started: 'dead' }))
await queue.work({ once: true, execute: async () => ({ text: 'recovered' }) })
assert.equal(queue.read(pending.id).status, 'completed')
assert(queue.read(pending.id).events.some(e => e.event === 'worker_recovered'))
const orphanJob = await queue.submit({ kind: 'search', query: 'orphan fixture' })
const orphan = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true, stdio: 'ignore' })
const exited = new Promise(resolve => orphan.once('exit', resolve))
try {
const startedAt = spawnSync('ps', ['-p', String(orphan.pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout.trim()
fs.writeFileSync(path.join(queue.dir(orphanJob.id), 'process-groups.jsonl'), JSON.stringify({ pid: orphan.pid, started: startedAt }) + '\n')
await queue.transaction(() => { const j = queue.read(orphanJob.id); j.status = 'running'; queue.save(j, 'fixture_orphan') })
await queue.work({ once: true, execute: async () => ({ text: 'orphan recovered' }) })
await exited
assert.equal(queue.read(orphanJob.id).status, 'completed')
assert.throws(() => process.kill(orphan.pid, 0), { code: 'ESRCH' })
} finally { try { process.kill(-orphan.pid, 'SIGKILL') } catch {} }
const leaderlessJob = await queue.submit({ kind: 'search', query: 'leaderless fixture' })
const orphanPidFile = path.join(tmp, 'orphan-pid')
const wrapper = spawn(process.execPath, ['-e', `const {spawn}=require('node:child_process');const fs=require('node:fs');const child=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});fs.writeFileSync(${JSON.stringify(orphanPidFile)},String(child.pid));setTimeout(()=>process.exit(0),500)`], { detached: true, stdio: 'ignore' })
const wrapperExited = new Promise(resolve => wrapper.once('exit', resolve))
try {
const startedAt = spawnSync('ps', ['-p', String(wrapper.pid), '-o', 'lstart='], { encoding: 'utf8' }).stdout.trim()
fs.writeFileSync(path.join(queue.dir(leaderlessJob.id), 'process-groups.jsonl'), JSON.stringify({ pid: wrapper.pid, started: startedAt }) + '\n')
await wrapperExited
const grandchildPid = Number(fs.readFileSync(orphanPidFile, 'utf8'))
process.kill(grandchildPid, 0)
await queue.transaction(() => { const j = queue.read(leaderlessJob.id); j.status = 'running'; queue.save(j, 'fixture_leader_exited') })
let executed = false
await assert.rejects(queue.work({ once: true, execute: async () => { executed = true; return { text: 'unsafe' } } }), /Ambiguous live process group/)
assert.equal(executed, false)
assert.equal(queue.read(leaderlessJob.id).status, 'failed')
assert.equal(queue.read(leaderlessJob.id).recovery_blocked, true)
assert.match(queue.read(leaderlessJob.id).error, /leader exited/)
process.kill(grandchildPid, 0)
await assert.rejects(queue.change(leaderlessJob.id, 'retry'), /Ambiguous live process group/)
const waiting = await queue.submit({ kind: 'search', query: 'must remain queued behind orphan' })
await assert.rejects(queue.work({ once: true, execute: async () => { executed = true } }), /Ambiguous live process group/)
assert.equal(executed, false)
assert.equal(queue.read(waiting.id).status, 'queued')
await queue.change(waiting.id, 'cancel')
} finally { try { process.kill(-wrapper.pid, 'SIGKILL') } catch {} }
await new Promise(resolve => setTimeout(resolve, 200))
// Fixture cleanup also removes the intentionally ambiguous historical record.
fs.writeFileSync(path.join(queue.dir(leaderlessJob.id), 'process-groups.jsonl'), '')
await queue.change(leaderlessJob.id, 'retry')
await queue.work({ once: true, execute: async () => ({ text: 'explicit retry after orphan exits' }) })
const unrelatedJob = await queue.submit({ kind: 'search', query: 'reused leader must not be killed' })
const unrelated = spawn(process.execPath, ['-e', 'setInterval(()=>{},1000)'], { detached: true, stdio: 'ignore' })
try {
fs.writeFileSync(path.join(queue.dir(unrelatedJob.id), 'process-groups.jsonl'), JSON.stringify({ pid: unrelated.pid, started: 'Thu Jan 1 00:00:00 1970' }) + '\n')
await queue.transaction(() => { const j = queue.read(unrelatedJob.id); j.status = 'running'; queue.save(j, 'fixture_reused_pid') })
await queue.work({ once: true, execute: async () => ({ text: 'old group already gone' }) })
process.kill(unrelated.pid, 0)
} finally { try { process.kill(-unrelated.pid, 'SIGKILL') } catch {} }
const concurrent = await queue.submit({ kind: 'search', query: 'one worker' })
let entered
const started = new Promise(resolve => { entered = resolve })
let finish
const finishing = new Promise(resolve => { finish = resolve })
const first = queue.work({ once: true, execute: async () => { entered(); await finishing; return { text: 'done' } } })
await started
assert.equal((await new JobQueue(queue.root).work({ once: true })).worker, 'already_running')
await queue.change(concurrent.id, 'cancel')
finish(); await first
assert.equal(queue.read(concurrent.id).status, 'cancelled')
await assert.rejects(queue.change('../escape', 'cancel'), /Invalid job id/)
const link = path.join(tmp, 'symlink.md'); fs.symlinkSync(original, link)
await assert.rejects(queue.submit({ kind: 'ingest', mode: 'deep', files: [link] }))
const oversized = path.join(tmp, 'oversized.mp4')
fs.closeSync(fs.openSync(oversized, 'w')); fs.truncateSync(oversized, 512 * 1024 * 1024 + 1)
await assert.rejects(queue.submit({ kind: 'ingest', mode: 'deep', files: [oversized] }), /512 MiB/)
const fifo = path.join(tmp, 'input.fifo')
assert.equal(spawnSync('mkfifo', [fifo]).status, 0)
const fifoSubmit = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-jobs.mjs'), 'submit', '--root', path.join(tmp, 'fifo-queue'), '--kind', 'ingest', '--mode', 'deep', '--file', fifo, '--no-start'], { encoding: 'utf8', timeout: 2000 })
assert.equal(fifoSubmit.status, 1, 'FIFO must fail promptly instead of blocking open')
assert.match(fifoSubmit.stderr, /regular file/)
// Real CLI + real local search against a tiny fixture. No LLM, inbox or live vault.
const vault = path.join(tmp, 'vault'); fs.mkdirSync(vault)
fs.writeFileSync(path.join(vault, 'memory.md'), '# Память\nПамять агентов хранит источники.')
const cliRoot = path.join(tmp, 'cli-queue')
const cli = args => {
const out = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-jobs.mjs'), ...args, '--root', cliRoot], {
encoding: 'utf8', env: { ...process.env, MNEMAZINE_VAULT: vault, MNEMAZINE_DEEP: '1', MNEMAZINE_SEARCH_LOG: path.join(tmp, 'queries.jsonl') },
})
assert.equal(out.status, 0, out.stderr)
return JSON.parse(out.stdout)
}
const search = cli(['submit', '--kind', 'search', '--query', 'память', '--no-start']).job
cli(['work', '--once'])
const found = cli(['status', '--id', search.id]).job
assert.equal(found.status, 'completed')
assert.match(found.result.text, /memory.md/)
assert.match(found.result.text, /локальн/)
assert(found.result.sources.some(source => source.path === path.join(vault, 'memory.md')))
const titleIntake = cli(['submit', '--kind', 'ingest', '--mode', 'deep', '--text', 'Название для исследования', '--no-start']).job
assert.equal(titleIntake.input_text, 'Название для исследования')
assert.equal(titleIntake.status, 'queued')
// Trusted config cannot redirect isolated paths; fake npm records invocation env.
const fixtureRepo = path.join(tmp, 'protocol'); fs.mkdirSync(path.join(fixtureRepo, '.mnemazine'), { recursive: true })
fs.mkdirSync(path.join(fixtureRepo, 'scripts'))
fs.copyFileSync(path.join(repo, 'scripts/mnemazine-vault-lock.mjs'), path.join(fixtureRepo, 'scripts/mnemazine-vault-lock.mjs'))
const inbox = path.join(tmp, 'job-inbox'); fs.mkdirSync(inbox); fs.writeFileSync(path.join(inbox, 'a.md'), 'fixture')
fs.writeFileSync(path.join(fixtureRepo, '.mnemazine/config.local.sh'), 'export MNEMAZINE_INBOX=/wrong\nexport MNEMAZINE_STATE=/wrong\nexport MNEMAZINE_REPORTS=/wrong\nexport MNEMAZINE_ARCHIVE=/wrong\nexport MNEMAZINE_CACHE=/wrong\nexport MNEMAZINE_EXTRACTS=/wrong\nexport MNEMAZINE_RUN_ID=wrong\n')
const bin = path.join(tmp, 'bin'); fs.mkdirSync(bin)
fs.writeFileSync(path.join(bin, 'npm'), '#!/bin/sh\nnode -e \'const fs=require("fs");fs.appendFileSync(process.env.PROBE,JSON.stringify(Object.fromEntries(Object.entries(process.env).filter(([k])=>k.startsWith("MNEMAZINE_"))))+"\\n")\'\n', { mode: 0o700 })
const env = { ...process.env, PATH: `${bin}:${process.env.PATH}`, MNEMAZINE_ROOT: fixtureRepo, MNEMAZINE_VAULT: vault, MNEMAZINE_INBOX: inbox, PROBE: path.join(tmp, 'probe.jsonl') }
for (const key of ['STATE', 'REPORTS', 'ARCHIVE', 'CACHE', 'EXTRACTS', 'RUN_ID']) env[`MNEMAZINE_${key}`] = path.join(tmp, key)
const protocol = spawnSync('bash', [path.join(repo, 'scripts/mnemazine-desktop-protocol.sh')], { env, encoding: 'utf8' })
assert.equal(protocol.status, 0, protocol.stderr)
const records = fs.readFileSync(env.PROBE, 'utf8').trim().split('\n').map(JSON.parse)
assert.equal(records.length, 2)
for (const record of records) for (const key of ['INBOX', 'STATE', 'REPORTS', 'ARCHIVE', 'CACHE', 'EXTRACTS', 'RUN_ID']) assert.equal(record[`MNEMAZINE_${key}`], env[`MNEMAZINE_${key}`])
// Hidden job ancestors are valid inboxes. Short text fails the content gate,
// not scanning. Disable synthesis explicitly: this probe must never use LLMs.
for (const [name, content, processed] of [
['short', '# Короткая проверка\nПроверяем перенос файла в приложение.', 0],
['long', '# Проверка очереди\nПамять агента должна сохранять исходный материал, связывать заметки с проверяемыми источниками и возвращать справку с понятными ссылками на документы.', 1],
['url-seed', fs.readFileSync(textQueue.list().find(job => job.input_kind === 'url').files[0].snapshot, 'utf8'), 1],
['title-seed', fs.readFileSync(textQueue.list().find(job => job.input_kind === 'title').files[0].snapshot, 'utf8'), 1],
]) {
const root = path.join(tmp, '.hidden-jobs', name)
fs.mkdirSync(path.join(root, 'inbox'), { recursive: true })
fs.writeFileSync(path.join(root, 'inbox', 'fixture.md'), content)
const probe = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-run.mjs'), '--require-deep'], {
encoding: 'utf8', timeout: 10000, cwd: tmp,
env: { ...process.env, MNEMAZINE_ROOT: repo, MNEMAZINE_VAULT: vault,
MNEMAZINE_INBOX: path.join(root, 'inbox'), MNEMAZINE_STATE: path.join(root, 'state'),
MNEMAZINE_REPORTS: path.join(root, 'reports'), MNEMAZINE_ARCHIVE: path.join(root, 'archive'),
MNEMAZINE_CACHE: path.join(root, 'cache/hashes.json'), MNEMAZINE_EXTRACTS: path.join(root, 'cache/extracted'),
MNEMAZINE_DEEP: '0', MNEMAZINE_SYNTHESIZE: '0', MNEMAZINE_FINISH: '0', MNEMAZINE_DRAFT_ONLY: '0',
},
})
assert.equal(probe.status, processed ? 2 : 1, probe.stderr) // No synthesized notes: quality gate must also fail.
const state = JSON.parse(fs.readFileSync(path.join(root, 'state/last-run.json'), 'utf8'))
assert.equal(state.inbox, 1)
assert.equal(state.processed, processed)
assert.equal(state.failed, 1 - processed)
assert.equal(state.synthesize.skipped, true)
const diagnosis = pipelineFailure(root, { code: probe.status })
if (!processed) assert.match(diagnosis, /Файл прочитан, но текст слишком короткий.*не менее 80/)
else assert.match(diagnosis, /run vault quality failed/)
assert(fs.existsSync(path.join(root, 'inbox/fixture.md')), 'fixture source must not be archived')
}
console.log('jobs tests passed: copy/dedup, retry/cancel, recovery, worker exclusion, local search, protocol isolation')
} finally { fs.rmSync(tmp, { recursive: true, force: true }) }
+62
View File
@@ -0,0 +1,62 @@
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { setTimeout } from 'node:timers/promises';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { runAdapter } from '../scripts/mnemazine-olympuz.mjs';
const root = mkdtempSync(join(tmpdir(), 'mnemazine-olympuz-test-'));
const cli = fileURLToPath(new URL('../scripts/mnemazine-jobs.mjs', import.meta.url));
const state = join(root, 'shared-state');
const worktree = join(root, 'god-worktree');
const research = join(worktree, 'research');
const base = ['--root', state, '--god', 'athena', '--run', 'run-1', '--project', 'example', '--mode', 'deep'];
const core = (...args) => JSON.parse(execFileSync(process.execPath, [cli, ...args, '--root', state, '--no-start'], { encoding: 'utf8' }));
try {
mkdirSync(research, { recursive: true });
const file = join(research, 'agent-research--example--public-source.md');
const content = '# Public fixture\nWater freezes at 0 °C under standard pressure.\n';
writeFileSync(file, content);
const { job } = runAdapter(['submit', ...base, '--worktree', worktree, '--file', file, '--no-start']);
assert.equal(job.kind, 'ingest');
assert.equal(job.status, 'queued');
assert.deepEqual(job.provenance, { client: 'olympuz', god: 'athena', run: 'run-1', project: 'example' });
assert.equal(readFileSync(file, 'utf8'), content, 'god source survives queue acceptance');
await setTimeout(20);
const redelivered = runAdapter(['submit', ...base, '--worktree', worktree, '--file', file, '--no-start']).job;
assert.equal(redelivered.id, job.id, 'unchanged delivery after clock tick reuses the same job');
assert.equal(redelivered.created_at, job.created_at, 'redelivery keeps original queue timestamp');
assert.equal(core('list').jobs.length, 1, 'redelivery adds no second job');
assert.throws(() => runAdapter(['submit', ...base.filter((x, i) => i < base.length - 2), '--worktree', worktree, '--file', file, '--no-start']), /--mode deep/);
assert.equal(core('status', '--id', job.id).job.id, job.id, 'desktop/core sees Olympuz job');
assert(core('list').jobs.some(item => item.id === job.id));
const desktop = core('submit', '--kind', 'search', '--query', 'public fixture', '--no-start').job;
assert.throws(() => runAdapter(['status', ...base, '--id', desktop.id]), /JOB_SCOPE_MISMATCH/);
assert.throws(() => runAdapter(['status', ...base.map(x => x === 'run-1' ? 'run-2' : x), '--id', job.id]), /JOB_SCOPE_MISMATCH/);
assert.equal(runAdapter(['cancel', ...base, '--id', job.id]).job.status, 'cancelled');
assert.equal(core('status', '--id', job.id).job.status, 'cancelled');
const retry = runAdapter(['retry', ...base, '--id', job.id, '--no-start']).job;
assert.equal(retry.status, 'queued');
assert.deepEqual(retry.provenance, job.provenance);
for (const command of ['search', 'brief']) {
assert.throws(() => runAdapter([command, ...base, '--query', 'private information']), /PROJECT_SCOPE_UNAVAILABLE/);
}
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', file, '--vault', root]), /Unknown option/);
const link = join(research, 'agent-research--example--link.md');
symlinkSync(file, link);
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', link, '--no-start']));
const hardlink = join(research, 'agent-research--example--hardlink.md');
linkSync(file, hardlink);
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', hardlink, '--no-start']), /обычным файлом/);
rmSync(hardlink);
const wrongProject = join(research, 'agent-research--another--source.md');
writeFileSync(wrongProject, content);
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', wrongProject, '--no-start']), /SOURCE_SCOPE_MISMATCH/);
const oversized = join(research, 'agent-research--example--oversized.md');
writeFileSync(oversized, Buffer.alloc(256 * 1024 + 1));
assert.throws(() => runAdapter(['submit', ...base, '--worktree', worktree, '--file', oversized, '--no-start']), /256 KiB/);
assert(existsSync(file));
console.log('PASS Olympuz/shared jobs: provenance, visibility, cancellation/retry, scope and hostile files');
} finally { rmSync(root, { recursive: true, force: true }); }
+61
View File
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'mnemazine-prearchive-'))
try {
const vault = path.join(tmp, 'vault'); fs.mkdirSync(vault)
process.env.MNEMAZINE_VAULT = vault
const { archiveAfterValidation } = await import('../scripts/mnemazine-run.mjs')
const { loadSpecCeiling } = await import('../scripts/mnemazine-complete-check.mjs')
const source = path.join(tmp, 'source.md'), archived = path.join(tmp, 'archived.md')
fs.writeFileSync(source, 'Original fixture must survive failed validation.')
const events = []
const archive = async file => { events.push('archive'); fs.renameSync(file, archived); return archived }
const items = [{ file: source, hash: 'fixture' }]
await assert.rejects(archiveAfterValidation({ failed: 0, finish: { human_layer: { ok: false, code: 1 } }, items, archive, validate: async () => events.push('complete') }), /final validation failed/)
assert(fs.existsSync(source))
assert.deepEqual(events, [])
await assert.rejects(archiveAfterValidation({ failed: 0, finish: { human_layer: { ok: true } }, items, archive, validate: async () => { events.push('complete'); throw new Error('spec ceiling failed') } }), /spec ceiling failed/)
assert(fs.existsSync(source))
assert.deepEqual(events, ['complete'])
events.length = 0
await archiveAfterValidation({ failed: 0, finish: { human_layer: { ok: true } }, items, archive, validate: async () => events.push('complete') })
assert.deepEqual(events, ['complete', 'archive'])
assert(fs.existsSync(archived))
const state = path.join(tmp, '.mnemazine/state'); fs.mkdirSync(state, { recursive: true })
const baseline = path.join(state, 'spec-ceiling.json')
assert.match((await loadSpecCeiling({ root: tmp, vault })).error, /no baseline/)
fs.writeFileSync(baseline, JSON.stringify({ vault, checked: 10, ceiling: 0 }))
const before = fs.readFileSync(baseline, 'utf8')
const loaded = await loadSpecCeiling({ root: tmp, vault })
assert.equal(loaded.error, null)
assert.equal(loaded.file, baseline)
assert.match((await loadSpecCeiling({ root: tmp, vault: path.join(tmp, 'other-vault') })).error, /different vault/)
assert.equal(fs.readFileSync(baseline, 'utf8'), before, 'baseline must not be copied, updated or fabricated')
const scripts = path.join(tmp, 'scripts'); fs.mkdirSync(scripts)
for (const name of ['coverage-check', 'vault-quality-gate', 'spec-ceiling', 'report-quality-gate', 'human-layer-gate']) fs.writeFileSync(path.join(scripts, `mnemazine-${name}.mjs`), 'console.log("fixture gate passed")\n')
const jobState = path.join(tmp, 'job-state'), inbox = path.join(tmp, 'inbox'), reports = path.join(tmp, 'reports')
for (const folder of [jobState, inbox, reports]) fs.mkdirSync(folder)
fs.writeFileSync(path.join(inbox, 'source.md'), 'source fixture')
fs.writeFileSync(path.join(reports, 'visual-knowledge-report.html'), '<html>fixture</html>')
fs.writeFileSync(path.join(jobState, 'last-action-brief.md'), 'fixture brief')
const pending = { ok: false, phase: 'pending_archive', pre_archive_ready: true, archive_pending: 1, processed: 1, deep: true, enrich_required: true, strict_archive_knowledge: true, synthesize: { atomized: 1, enriched: 1 }, vault }
fs.writeFileSync(path.join(jobState, 'last-run.json'), JSON.stringify(pending))
const check = (beforeArchive = true) => spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-complete-check.mjs'), '--require-deep', ...(beforeArchive ? ['--before-archive'] : [])], { encoding: 'utf8', timeout: 10000, cwd: tmp, env: { ...process.env, MNEMAZINE_ROOT: tmp, MNEMAZINE_STATE: jobState, MNEMAZINE_INBOX: inbox, MNEMAZINE_REPORTS: reports, MNEMAZINE_VAULT: vault } })
assert.equal(check().status, 0, 'valid pending state uses real canonical fixture baseline, not job-state baseline')
assert.equal(check(false).status, 1, 'normal completion must reject pending archive')
fs.writeFileSync(path.join(scripts, 'mnemazine-coverage-check.mjs'), 'console.error("fixture uncovered source");process.exit(1)\n')
const failedCoverage = check()
assert.equal(failedCoverage.status, 1)
assert.match(failedCoverage.stdout, /coverage failed/)
assert(fs.existsSync(path.join(inbox, 'source.md')))
const producer = spawnSync(process.execPath, [path.join(repo, 'scripts/mnemazine-synthesize.mjs'), '--selftest'], { encoding: 'utf8', timeout: 10000, cwd: tmp, env: { ...process.env, MNEMAZINE_ROOT: repo, MNEMAZINE_VAULT: vault, MNEMAZINE_STATE: path.join(tmp, 'job-state'), MNEMAZINE_DEEP: '0' } })
assert.equal(producer.status, 0, producer.stderr)
console.log('prearchive passed: failed finish/complete retain source, gate-before-move, canonical vault-bound baseline, truthful producer sections')
} finally { fs.rmSync(tmp, { recursive: true, force: true }) }
+42
View File
@@ -0,0 +1,42 @@
import assert from 'node:assert/strict'
import { promises as fs } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { evidenceExcerpt, verifyFindings, cloudReadable } from '../scripts/mnemazine-kb-search.mjs'
import { loadTaxonomy } from '../scripts/mnemazine-machine-class-gate.mjs'
const longNote = '# Документ\n' + 'Нерелевантное описание. '.repeat(600) + '\nЛазурный двигатель: ресурс 840 циклов.'
assert.ok(evidenceExcerpt(longNote, 'лазурный двигатель').includes('840 циклов'), 'evidence at the end is readable')
assert.ok(evidenceExcerpt(longNote, 'лазурный двигатель').length <= 2500)
const finding = { note: 'source.md', insight: 'Лазурный двигатель: ресурс 840 циклов.', relevance: 5 }
const corpus = new Map([['source.md', longNote]])
let result = await verifyFindings('лазурный двигатель', [finding], corpus, async prompt => {
assert.ok(prompt.includes('840 циклов'))
return { grounded: true, relevant: true, actionable: true }
}, true)
assert.equal(result.kept.length, 1)
result = await verifyFindings('лазурный двигатель', [finding], corpus, async () => { throw new Error('offline verifier fixture') }, true)
assert.deepEqual(result, { kept: [], dropped: 1 }, 'verifier error cannot certify evidence')
for (const verdict of [{}, { grounded: true, relevant: false }, { grounded: false, relevant: true }]) {
result = await verifyFindings('лазурный двигатель', [finding], corpus, async () => verdict, true)
assert.equal(result.kept.length, 0, 'missing/negative verdict is not support')
}
result = await verifyFindings('лазурный двигатель', [finding], new Map(), async () => { throw new Error('must not run for missing source') }, true)
assert.equal(result.kept.length, 0)
result = await verifyFindings('лазурный двигатель', Array(7).fill(finding), corpus, async () => ({ grounded: true, relevant: true }), true)
assert.equal(result.kept.length, 5)
assert.equal(result.dropped, 2, 'over-budget findings must not bypass verification')
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-evidence-'))
try {
const nested = path.join(tmp, '02 Здоровье', 'nested')
await fs.mkdir(nested, { recursive: true })
const privateFile = path.join(nested, 'private.md')
await fs.writeFile(privateFile, '---\ndata_class: text\n---\nЛичное')
assert.equal(cloudReadable(privateFile, loadTaxonomy()), false, 'nested private section cannot be downgraded')
const ordinary = path.join(tmp, 'public.md')
await fs.writeFile(ordinary, '---\ndata_class: public\n---\nОткрытое')
assert.equal(cloudReadable(ordinary, loadTaxonomy()), true)
await fs.writeFile(ordinary, 'Нет frontmatter')
assert.equal(cloudReadable(ordinary, loadTaxonomy()), false, 'missing classification is private')
} finally { await fs.rm(tmp, { recursive: true, force: true }) }
console.log('search evidence regressions: passed')
+57
View File
@@ -0,0 +1,57 @@
import assert from 'node:assert/strict'
import { mkdtempSync, mkdirSync, symlinkSync, existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawn, spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { acquireVaultLock } from '../scripts/mnemazine-vault-lock.mjs'
const script = fileURLToPath(new URL('../scripts/mnemazine-vault-lock.mjs', import.meta.url))
const root = mkdtempSync(path.join(os.tmpdir(), 'mnemazine-vault-lock-test-'))
const vault = path.join(root, 'vault')
const alias = path.join(root, 'alias')
mkdirSync(vault)
symlinkSync(vault, alias)
const dir = path.join(vault, '.mnemazine-pipeline-lock')
const run = (target, code, env = process.env) => spawnSync(process.execPath,
[script, '--vault', target, '--', process.execPath, '-e', code], { encoding: 'utf8', env })
let holder
try {
// A real independent process owns the vault while another uses a symlink.
holder = spawn(process.execPath, [script, '--vault', vault, '--', process.execPath,
'-e', 'console.log("ready"); process.stdin.resume()'], { stdio: ['pipe', 'pipe', 'pipe'] })
await new Promise((resolve, reject) => {
holder.stdout.once('data', resolve)
holder.once('error', reject)
holder.once('exit', code => reject(new Error(`holder exited ${code}`)))
})
assert.equal(run(alias, '').status, 75)
const otherOwner = JSON.parse(readFileSync(path.join(dir, 'owner.json'), 'utf8'))
assert.equal(run(alias, '', { ...process.env, MNEMAZINE_VAULT_LOCK: otherOwner.nonce }).status, 75,
'knowing nonce does not make an unrelated process a descendant')
const exit = new Promise(resolve => holder.once('exit', resolve))
holder.stdin.end()
assert.equal(await exit, 0)
assert.equal(existsSync(dir), false)
const release = acquireVaultLock(vault)
assert.equal(run(alias, '').status, 0, 'descendant inherits verified lock')
assert.equal(run(alias, '', { ...process.env, MNEMAZINE_VAULT_LOCK: 'wrong' }).status, 75)
assert.equal(existsSync(dir), true, 'child must not release parent ownership')
release()
assert.equal(run(vault, 'process.exit(7)').status, 7)
assert.equal(existsSync(dir), false, 'command failure cleans lock')
const direct = spawnSync(process.execPath, ['--input-type=module', '-e',
`import { acquireVaultLock } from ${JSON.stringify(new URL('../scripts/mnemazine-vault-lock.mjs', import.meta.url).href)}; acquireVaultLock(${JSON.stringify(vault)}); process.exit(9)`])
assert.equal(direct.status, 9)
assert.equal(existsSync(dir), false, 'process.exit cleans direct lock')
mkdirSync(dir)
writeFileSync(path.join(dir, 'owner.json'), JSON.stringify({ pid: 2147483647, start: 'stale', nonce: 'stale' }))
assert.equal(run(vault, '').status, 75)
assert.equal(existsSync(dir), true, 'stale ownership is never stolen')
console.log('vault lock: concurrency, aliases, reentrancy, stale and failure cleanup passed')
} finally {
holder?.kill('SIGTERM')
rmSync(root, { recursive: true, force: true })
}