feat: имя бога — Гелиоз (helioz), Z-канон пантеона; ребренд всех приборов и состояния; README EN+RU по канону Pantheon Design System; docs/BRAND.md с промптами визуалов; graphify-out вне публичного репо

This commit is contained in:
Зарубин Филипп
2026-08-24 16:33:27 +03:00
parent 40a1eb8512
commit 29666ce638
39 changed files with 316 additions and 4628 deletions
-33
View File
@@ -1,33 +0,0 @@
#!/bin/bash
# ЗАПУСК КОНВЕЙЕРА ОДНОЙ СТРОКОЙ: приборы зелёные → heartbeat → отбивка → что дальше.
set -u
SELF="$(cd "$(dirname "$0")" && pwd)"
HOME_DIR="$(dirname "$SELF")"
cd "$HOME_DIR"
echo "== Проверка приборов (selftests) =="
fail=0
for t in "node scripts/conveyor-gate.mjs --selftest" \
"node scripts/conveyor-zeus.mjs --selftest" \
"node scripts/conveyor-exec.mjs --selftest" \
"node scripts/conveyor-council.mjs --selftest" \
"bash scripts/conveyor-watchdog.sh --selftest"; do
if $t >/dev/null 2>&1; then echo " ok $t"; else echo " FAIL $t"; fail=1; fi
done
[ "$fail" -eq 0 ] || { echo "приборы красные — запуск запрещён (fail-closed)"; exit 2; }
node scripts/conveyor-gate.mjs --beat "start.sh"
node scripts/conveyor-zeus.mjs send --text "🚀 Конвейер запущен. Очередь: $(ls queue/tasks/*.task.md 2>/dev/null | wc -l | tr -d ' ') задач. «стоп» — заморозить, «пуск» — продолжить." >/dev/null 2>&1 || true
echo
echo "== Очередь =="
node scripts/conveyor-gate.mjs --status || true
echo
if ! launchctl print "gui/$(id -u)/com.conveyor.watchdog" >/dev/null 2>&1; then
echo "⚠️ Сторож не установлен. Один раз:"
echo " cp launchd/com.conveyor.watchdog.plist ~/Library/LaunchAgents/ && launchctl bootstrap gui/\$(id -u) ~/Library/LaunchAgents/com.conveyor.watchdog.plist"
fi
if [ ! -f .conveyor/state/budget.json ]; then
echo "⚠️ Нет .conveyor/state/budget.json — задай потолок: {\"started_at\":\"$(date -u +%FT%TZ)\",\"ceiling_usd\":N}"
fi
echo "Оркестратор поднимет сторож при протухшем heartbeat, либо вручную: сессия Claude Code в этой папке с промтом ORCHESTRATOR.md"
@@ -17,11 +17,11 @@ import { fileURLToPath } from 'node:url'
import path from 'node:path'
import os from 'node:os'
const HOME = process.env.CONVEYOR_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'conveyor.json'), 'utf8')) } catch { return {} } })()
const STATE = path.join(HOME, '.conveyor', 'state')
const HOME = process.env.HELIOZ_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'helioz.json'), 'utf8')) } catch { return {} } })()
const STATE = path.join(HOME, '.helioz', 'state')
const DILEMMAS = path.join(HOME, 'queue', 'dilemmas')
const EXEC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'conveyor-exec.mjs')
const EXEC = path.join(path.dirname(fileURLToPath(import.meta.url)), 'helioz-exec.mjs')
const now = () => new Date().toISOString()
const FORBIDDEN = ['prod', 'foreign', 'expensive']
@@ -127,7 +127,7 @@ async function cmdDecide(id, day) {
const noneVotes = positions.filter(p => p.choice === 'none').length
if (noneVotes * 2 >= positions.length) {
appendFileSync(path.join(STATE, 'ledger.jsonl'), JSON.stringify({ ts: now(), kind: 'council-abstain', dilemma: id, why: `ни один вариант не служит цели владельца (${noneVotes}/${positions.length} голосов)` }) + '\n')
const zeusA = path.join(path.dirname(EXEC), 'conveyor-zeus.mjs')
const zeusA = path.join(path.dirname(EXEC), 'helioz-zeus.mjs')
spawnSync(process.execPath, [zeusA, 'send', '--text', `🌙 Совет ВОЗДЕРЖАЛСЯ по развилке ${id}: большинство линз считает, что ни один вариант не служит твоей цели. Развилка ждёт тебя: «${id} <номер>».`, '--quiet'], { encoding: 'utf8', env: process.env })
console.error(`совет воздержался: ни один вариант не служит цели (${noneVotes}/${positions.length})`)
return 1
@@ -162,7 +162,7 @@ async function cmdDecide(id, day) {
const decision = sr.status === 0 ? parseChoice(stext.replace(/РЕШЕНИЕ/i, 'ВЫБОР'), d.options.length) : null
if (decision === 'none') {
appendFileSync(path.join(STATE, 'ledger.jsonl'), JSON.stringify({ ts: now(), kind: 'council-abstain', dilemma: id, why: 'синтез: ни один вариант не служит цели владельца' }) + '\n')
const zeusB = path.join(path.dirname(EXEC), 'conveyor-zeus.mjs')
const zeusB = path.join(path.dirname(EXEC), 'helioz-zeus.mjs')
spawnSync(process.execPath, [zeusB, 'send', '--text', `🌙 Совет ВОЗДЕРЖАЛСЯ по развилке ${id}: синтез счёл, что ни один вариант не служит твоей цели. Ждёт тебя: «${id} <номер>».`, '--quiet'], { encoding: 'utf8', env: process.env })
console.error('синтез: ни один вариант не служит цели — воздержание')
return 1
@@ -182,7 +182,7 @@ async function cmdDecide(id, day) {
lenses: positions.map(p => ({ lens: p.lens, cli: p.cli, choice: p.choice, position_file: p.file })),
synthesis_cli: scli, rationale,
}) + '\n')
const zeus = path.join(path.dirname(EXEC), 'conveyor-zeus.mjs')
const zeus = path.join(path.dirname(EXEC), 'helioz-zeus.mjs')
spawnSync(process.execPath, [zeus, 'send', '--text',
`🌙 Совет решил развилку ${id}: вариант ${finalChoice + 1} (${d.options[finalChoice]}).\n${rationale.slice(0, 500)}\nПереиграть: ответь «${id} <номер>».`,
'--quiet'], { encoding: 'utf8', env: process.env })
@@ -193,7 +193,7 @@ async function cmdDecide(id, day) {
// --- selftest: стаб-советники ---------------------------------------------------------------------
async function cmdSelftest() {
const { strictEqual: eq, ok } = await import('node:assert')
const tmp = mkdtempSync(path.join(os.tmpdir(), 'conveyor-council-'))
const tmp = mkdtempSync(path.join(os.tmpdir(), 'helioz-council-'))
try {
const bin = path.join(tmp, 'bin'); mkdirSync(bin, { recursive: true })
// стаб: читает промт со stdin, голосует за вариант 2; синтез отвечает РЕШЕНИЕ: 2
@@ -201,7 +201,7 @@ async function cmdSelftest() {
writeFileSync(adv, '#!/bin/sh\ninput=$(cat)\ncase "$input" in *"синтез ночного совета"*) echo "РЕШЕНИЕ: 2"; echo "ОБОСНОВАНИЕ: так надёжнее по всем линзам."; echo "РАЗНОГЛАСИЯ: не было.";; *) echo "ВЫБОР: 2"; echo "ПОЧЕМУ: линза велит."; echo "РИСК ОШИБКИ: небольшой.";; esac\n')
chmodSync(adv, 0o755)
for (const sub of ['config', 'queue/dilemmas', 'scripts']) mkdirSync(path.join(tmp, sub), { recursive: true })
writeFileSync(path.join(tmp, 'config', 'conveyor.json'), JSON.stringify({
writeFileSync(path.join(tmp, 'config', 'helioz.json'), JSON.stringify({
quiet_hours: { start: '00:00', end: '23:59' }, // «всегда ночь» для теста
council: { lenses: ['риск', 'цена отката', 'простота'], min_advisors: 3, synthesis_order: ['claude'] },
probe_timeout_sec: 5, run_timeout_sec: 5,
@@ -215,7 +215,7 @@ async function cmdSelftest() {
status: 'asked', asked_at: now(), answered_at: null, answer: null, decided_by: null, council: null, replay: [],
}))
const self = fileURLToPath(import.meta.url)
const run = (args) => spawnSync(process.execPath, [self, ...args], { env: { ...process.env, CONVEYOR_HOME: tmp }, encoding: 'utf8' })
const run = (args) => spawnSync(process.execPath, [self, ...args], { env: { ...process.env, HELIOZ_HOME: tmp }, encoding: 'utf8' })
// 0а. Без конечной цели владельца совет решать НЕ ВПРАВЕ (exit 2).
mkDil('DNoGoal', 'default')
@@ -242,21 +242,21 @@ async function cmdSelftest() {
const d2 = JSON.parse(readFileSync(path.join(tmp, 'queue', 'dilemmas', 'DOK.json'), 'utf8'))
eq(d2.decided_by, 'council'); eq(d2.answer, 1, 'советники выбрали вариант 2 → индекс 1')
eq(d2.council.lenses.length, 3)
const led = readFileSync(path.join(tmp, '.conveyor', 'state', 'ledger.jsonl'), 'utf8').trim().split('\n').map(JSON.parse)
const led = readFileSync(path.join(tmp, '.helioz', 'state', 'ledger.jsonl'), 'utf8').trim().split('\n').map(JSON.parse)
const ce = led.find(l => l.kind === 'council' && l.dilemma === 'DOK')
ok(ce && ce.rationale && ce.lenses.length === 3, 'ledger несёт решение с обоснованием и позициями')
// позиции советников лежат файлами (изоляция: каждый писал в свой)
const cdir = readdirSync(path.join(tmp, '.conveyor', 'state', 'council', 'DOK'))
const cdir = readdirSync(path.join(tmp, '.helioz', 'state', 'council', 'DOK'))
ok(cdir.filter(f => f.startsWith('advisor-')).length === 3, 'три файла позиций')
// отбивка легла в outbox (Telegram-стаба нет — недоставленная, но durable)
const obox = readdirSync(path.join(tmp, '.conveyor', 'state', 'outbox'))
const obox = readdirSync(path.join(tmp, '.helioz', 'state', 'outbox'))
ok(obox.length >= 1, 'отбивка о решении в outbox')
// 3. Мало голосов (лимит 3, живой CLI один и его роль advise убрана) → совет не собрался, exit 1.
writeFileSync(path.join(tmp, 'config', 'clis.json'), JSON.stringify({
claude: { invoke_read: [adv], invoke_write: [adv], stdin_prompt: true, roles: ['synthesize'] },
}))
rmSync(path.join(tmp, '.conveyor', 'state', 'cli-health.json'), { force: true })
rmSync(path.join(tmp, '.helioz', 'state', 'cli-health.json'), { force: true })
mkDil('DThin', 'default')
eq(run(['decide', '--dilemma', 'DThin']).status, 1, 'нет советников → совет не решает')
@@ -264,7 +264,7 @@ async function cmdSelftest() {
eq(run(['decide', '--dilemma', 'DOK']).status, 2)
// 5. Цель в промте каждого советника; советники голосуют «0 = ни один не служит цели» → воздержание.
const p0 = readFileSync(path.join(tmp, '.conveyor', 'state', 'council', 'DOK', 'prompt-0.txt'), 'utf8')
const p0 = readFileSync(path.join(tmp, '.helioz', 'state', 'council', 'DOK', 'prompt-0.txt'), 'utf8')
ok(p0.includes('КОНЕЧНАЯ ЦЕЛЬ ВЛАДЕЛЬЦА') && p0.includes('24/7 без потерь'), 'цель владельца в промте советника')
const advNone = path.join(bin, 'advnone')
writeFileSync(advNone, '#!/bin/sh\ncat >/dev/null\necho "ВЫБОР: 0"; echo "ПОЧЕМУ: ни один вариант не служит цели."; echo "РИСК ОШИБКИ: нет."\n')
@@ -273,13 +273,13 @@ async function cmdSelftest() {
claude: { invoke_read: [advNone], invoke_write: [advNone], stdin_prompt: true, roles: ['execute', 'verify', 'advise', 'synthesize'] },
codex: { invoke_read: [advNone], invoke_write: [advNone], stdin_prompt: true, roles: ['execute', 'verify', 'advise', 'synthesize'] },
}))
rmSync(path.join(tmp, '.conveyor', 'state', 'cli-health.json'), { force: true })
rmSync(path.join(tmp, '.helioz', 'state', 'cli-health.json'), { force: true })
mkDil('DNone', 'default')
const rn = run(['decide', '--dilemma', 'DNone'])
eq(rn.status, 1, 'все за 0 → совет воздержался')
const dn = JSON.parse(readFileSync(path.join(tmp, 'queue', 'dilemmas', 'DNone.json'), 'utf8'))
eq(dn.status, 'asked', 'развилка осталась владельцу')
const led2 = readFileSync(path.join(tmp, '.conveyor', 'state', 'ledger.jsonl'), 'utf8').trim().split('\n').map(JSON.parse)
const led2 = readFileSync(path.join(tmp, '.helioz', 'state', 'ledger.jsonl'), 'utf8').trim().split('\n').map(JSON.parse)
ok(led2.some(l => l.kind === 'council-abstain' && l.dilemma === 'DNone'), 'воздержание записано в ledger')
console.log('selftest ok — без цели не решает, запретные отложены, default решён по цели, воздержание при «ни один», тонкий совет не решает')
@@ -294,7 +294,7 @@ async function main() {
})
if (v.selftest) return cmdSelftest()
if (positionals[0] === 'decide') return cmdDecide(v.dilemma, v.day)
console.log('conveyor-council: decide --dilemma <DID> [--day] | --selftest')
console.log('helioz-council: decide --dilemma <DID> [--day] | --selftest')
return 0
}
main().then(c => process.exit(c)).catch(e => { console.error(String(e && e.message || e)); process.exit(1) })
@@ -18,10 +18,10 @@ import { fileURLToPath } from 'node:url'
import path from 'node:path'
import os from 'node:os'
const HOME = process.env.CONVEYOR_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'conveyor.json'), 'utf8')) } catch { return {} } })()
const HOME = process.env.HELIOZ_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'helioz.json'), 'utf8')) } catch { return {} } })()
const CLIS = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'clis.json'), 'utf8')) } catch { return {} } })()
const STATE = path.join(HOME, '.conveyor', 'state')
const STATE = path.join(HOME, '.helioz', 'state')
const HEALTH = path.join(STATE, 'cli-health.json')
const now = () => new Date().toISOString()
const cliNames = () => Object.keys(CLIS).filter(k => !k.startsWith('_'))
@@ -142,7 +142,7 @@ function cmdRun(cli, promptFile, write, timeoutSec, log) {
// --- selftest: стаб-бинари ------------------------------------------------------------------------
async function cmdSelftest() {
const { strictEqual: eq, ok } = await import('node:assert')
const tmp = mkdtempSync(path.join(os.tmpdir(), 'conveyor-exec-'))
const tmp = mkdtempSync(path.join(os.tmpdir(), 'helioz-exec-'))
try {
const bin = path.join(tmp, 'bin'); mkdirSync(bin, { recursive: true })
const mkbin = (name, script) => { const f = path.join(bin, name); writeFileSync(f, '#!/bin/sh\n' + script + '\n'); chmodSync(f, 0o755); return f }
@@ -153,7 +153,7 @@ async function cmdSelftest() {
const empty = mkbin('empty', 'exit 0')
mkdirSync(path.join(tmp, 'config'), { recursive: true })
mkdirSync(path.join(tmp, 'queue', 'tasks'), { recursive: true })
writeFileSync(path.join(tmp, 'config', 'conveyor.json'), JSON.stringify({ probe_timeout_sec: 5, run_timeout_sec: 5 }))
writeFileSync(path.join(tmp, 'config', 'helioz.json'), JSON.stringify({ probe_timeout_sec: 5, run_timeout_sec: 5 }))
const clis = {
claude: { invoke_read: [alive, '-p'], invoke_write: [alive, '-p', '--w'], stdin_prompt: true, roles: ['execute', 'verify', 'advise', 'synthesize'] },
codex: { invoke_read: [broken, 'exec'], invoke_write: [broken, 'exec'], stdin_prompt: true, roles: ['execute', 'verify', 'advise'] },
@@ -161,7 +161,7 @@ async function cmdSelftest() {
}
writeFileSync(path.join(tmp, 'config', 'clis.json'), JSON.stringify(clis))
const self = fileURLToPath(import.meta.url)
const run = (args) => spawnSync(process.execPath, [self, ...args], { env: { ...process.env, CONVEYOR_HOME: tmp }, encoding: 'utf8' })
const run = (args) => spawnSync(process.execPath, [self, ...args], { env: { ...process.env, HELIOZ_HOME: tmp }, encoding: 'utf8' })
// 1. Зонд: живой зелёный, сломанный вызов КРАСНЫЙ (не «provider list зелёный»), пустой ответ КРАСНЫЙ.
eq(run(['probe', '--cli', 'claude']).status, 0)
@@ -189,14 +189,14 @@ async function cmdSelftest() {
].join('\n'))
const e1 = run(['task', '--id', 'T9', '--role', 'executor'])
eq(e1.status, 0)
const rec = JSON.parse(readFileSync(path.join(tmp, '.conveyor', 'state', 'exec', 'T9.json'), 'utf8'))
const rec = JSON.parse(readFileSync(path.join(tmp, '.helioz', 'state', 'exec', 'T9.json'), 'utf8'))
eq(rec.executor_used, 'claude')
ok(existsSync(path.join(tmp, rec.executor_log)), 'лог исполнителя на диске')
const v1 = run(['task', '--id', 'T9', '--role', 'verifier', '--cli', 'claude'])
eq(v1.status, 2, 'проверяющий = исполнитель → отказ (генератор не судит себя)')
const v2 = run(['task', '--id', 'T9', '--role', 'verifier'])
eq(v2.status, 0)
const rec2 = JSON.parse(readFileSync(path.join(tmp, '.conveyor', 'state', 'exec', 'T9.json'), 'utf8'))
const rec2 = JSON.parse(readFileSync(path.join(tmp, '.helioz', 'state', 'exec', 'T9.json'), 'utf8'))
ok(rec2.verifier_used && rec2.verifier_used !== 'claude', 'ротация выбрала другой CLI')
// 5. Роль без промта → 2.
@@ -225,7 +225,7 @@ async function main() {
if (cmd === 'pick') return cmdPick(v.role, v.exclude, v.prefer)
if (cmd === 'task') return cmdTask(v.id, v.role, v.cli)
if (cmd === 'run') return cmdRun(v.cli, v['prompt-file'], v.write, Number(v.timeout) || 0, v.log)
console.log('conveyor-exec: probe --cli|--all · pick --role [--exclude,--prefer] · task --id --role [--cli] · run --cli --prompt-file [--write] | --selftest')
console.log('helioz-exec: probe --cli|--all · pick --role [--exclude,--prefer] · task --id --role [--cli] · run --cli --prompt-file [--write] | --selftest')
return 0
}
main().then(c => process.exit(c)).catch(e => { console.error(String(e && e.message || e)); process.exit(1) })
@@ -24,10 +24,10 @@ import { fileURLToPath } from 'node:url'
import path from 'node:path'
import os from 'node:os'
const HOME = process.env.CONVEYOR_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = readJson(path.join(HOME, 'config', 'conveyor.json')) || {}
const HOME = process.env.HELIOZ_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = readJson(path.join(HOME, 'config', 'helioz.json')) || {}
const S = {
state: path.join(HOME, '.conveyor', 'state'),
state: path.join(HOME, '.helioz', 'state'),
tasks: path.join(HOME, 'queue', 'tasks'),
dilemmas: path.join(HOME, 'queue', 'dilemmas'),
}
@@ -113,7 +113,7 @@ export function readMarker(id) {
if (!existsSync(f)) return { status: 'missing' }
let d
try { d = JSON.parse(readFileSync(f, 'utf8')) } catch { return { status: 'tampered', reason: 'нечитаемый json' } }
if (d.written_by !== 'conveyor-gate') return { status: 'tampered', reason: 'нет written_by:"conveyor-gate"', data: d }
if (d.written_by !== 'helioz-gate') return { status: 'tampered', reason: 'нет written_by:"helioz-gate"', data: d }
for (const k of ['task', 'base', 'head', 'sha_of_changed_files', 'finished_at']) {
if (d[k] === undefined || d[k] === null || d[k] === '') return { status: 'tampered', reason: `нет поля целостности ${k}`, data: d }
}
@@ -139,7 +139,7 @@ function writeMarker(id, { checkCmd, executor, verifier, base }) {
task: id, check_cmd: checkCmd || '', exit_code: 0,
base: baseSha, head, sha_of_changed_files: changedFilesSha(baseSha, head),
executor_cli: executor || null, verifier_cli: verifier || null,
finished_at: now(), written_by: 'conveyor-gate',
finished_at: now(), written_by: 'helioz-gate',
}
writeFileSync(markerFile(id), JSON.stringify(marker, null, 2) + '\n')
return marker
@@ -430,9 +430,9 @@ async function cmdSelftest() {
eq(noCheck.valid, false, 'задача без check_cmd обязана быть invalid')
// 2–7. Изолированное состояние в tmp git-репо.
const tmp = mkdtempSync(path.join(os.tmpdir(), 'conveyor-selftest-'))
const tmp = mkdtempSync(path.join(os.tmpdir(), 'helioz-selftest-'))
try {
const env = { ...process.env, CONVEYOR_HOME: tmp }
const env = { ...process.env, HELIOZ_HOME: tmp }
const self = fileURLToPath(import.meta.url)
const run = (args) => spawnSync(process.execPath, [self, ...args], { env, encoding: 'utf8' })
mkdirSync(path.join(tmp, 'queue', 'tasks'), { recursive: true })
@@ -472,15 +472,15 @@ async function cmdSelftest() {
// маркер: пишется только при exit 0, ловит подделку
eq(run(['--task', 'A', '--check-cmd', 'false']).status, 1, 'красная проверка не пишет маркер')
ok(!existsSync(path.join(tmp, '.conveyor', 'state', 'markers', 'A.done.json')))
ok(!existsSync(path.join(tmp, '.helioz', 'state', 'markers', 'A.done.json')))
eq(run(['--task', 'A', '--check-cmd', 'true', '--executor', 'kimi', '--verifier', 'codex']).status, 0)
eq(run(['--require', 'A']).status, 0)
// подделка руками → tampered
const mf = path.join(tmp, '.conveyor', 'state', 'markers', 'B.done.json')
const mf = path.join(tmp, '.helioz', 'state', 'markers', 'B.done.json')
writeFileSync(mf, JSON.stringify({ task: 'B', written_by: 'orchestrator', finished_at: now() }))
eq(run(['--require', 'B']).status, 2, 'рукописный маркер обязан быть tampered')
// обрезание полей у настоящего маркера → tampered
const af = path.join(tmp, '.conveyor', 'state', 'markers', 'A.done.json')
const af = path.join(tmp, '.helioz', 'state', 'markers', 'A.done.json')
const good = JSON.parse(readFileSync(af, 'utf8'))
const cut = { ...good }; delete cut.sha_of_changed_files
writeFileSync(af, JSON.stringify(cut))
@@ -490,7 +490,7 @@ async function cmdSelftest() {
writeFileSync(af, JSON.stringify({ ...good, sha_of_changed_files: 'deadbeef' }) + '\n')
eq(run(['--require', 'A']).status, 2, 'битый sha обязан быть tampered')
// ревью codex: копия чужого ВАЛИДНОГО маркера → tampered (маркер не привязан был к id)
writeFileSync(path.join(tmp, '.conveyor', 'state', 'markers', 'C.done.json'), JSON.stringify(good) + '\n')
writeFileSync(path.join(tmp, '.helioz', 'state', 'markers', 'C.done.json'), JSON.stringify(good) + '\n')
eq(run(['--require', 'C']).status, 2, 'чужой валидный маркер копией обязан быть tampered')
// ревью codex+kimi: exit_code ≠ 0 → tampered
writeFileSync(af, JSON.stringify({ ...good, exit_code: 1 }) + '\n')
@@ -501,10 +501,10 @@ async function cmdSelftest() {
writeFileSync(af, JSON.stringify(good) + '\n')
eq(run(['--require', 'A']).status, 0, 'восстановленный честный маркер снова done')
// ревью codex+kimi: битый running.json → fail-closed, не пустой список
writeFileSync(path.join(tmp, '.conveyor', 'state', 'running.json'), '{')
writeFileSync(path.join(tmp, '.helioz', 'state', 'running.json'), '{')
eq(run(['--ready']).status, 2, 'битый running.json обязан давать fail-closed')
eq(run(['--start', 'C']).status, 2, 'старт при битом running.json запрещён')
rmSync(path.join(tmp, '.conveyor', 'state', 'running.json'))
rmSync(path.join(tmp, '.helioz', 'state', 'running.json'))
// requires: D ждёт маркер E
mk('D', ['docs/d.md'], 'requires: [E]\n')
@@ -512,9 +512,9 @@ async function cmdSelftest() {
ok(rd.stdout.includes('ждёт маркер E'), 'зависимость без маркера блокирует')
// STOP → ready/start exit 4
writeFileSync(path.join(tmp, '.conveyor', 'state', 'STOP'), now())
writeFileSync(path.join(tmp, '.helioz', 'state', 'STOP'), now())
eq(run(['--ready']).status, 4); eq(run(['--start', 'C']).status, 4)
rmSync(path.join(tmp, '.conveyor', 'state', 'STOP'))
rmSync(path.join(tmp, '.helioz', 'state', 'STOP'))
// adopt: идемпотентно, без потерь
const ext = path.join(tmp, 'ext'); mkdirSync(path.join(ext, 'dilemmas'), { recursive: true })
@@ -522,13 +522,13 @@ async function cmdSelftest() {
writeFileSync(path.join(ext, 'dilemmas', 'DX.json'), JSON.stringify({ id: 'DX', kind: 'default', status: 'open', question: 'q', options: ['a'], recommend: 0 }))
eq(run(['--adopt', ext]).status, 0)
eq(run(['--adopt', ext]).status, 0)
const led = readFileSync(path.join(tmp, '.conveyor', 'state', 'ledger.jsonl'), 'utf8').split('\n').filter(Boolean)
const led = readFileSync(path.join(tmp, '.helioz', 'state', 'ledger.jsonl'), 'utf8').split('\n').filter(Boolean)
eq(led.length, 1, 'adopt дважды не дублирует ledger')
ok(existsSync(path.join(tmp, 'queue', 'dilemmas', 'DX.json')))
// beat
eq(run(['--beat', 'selftest']).status, 0)
ok(existsSync(path.join(tmp, '.conveyor', 'state', 'heartbeat.json')))
ok(existsSync(path.join(tmp, '.helioz', 'state', 'heartbeat.json')))
// бюджет: нет budget.json → 2; с потолком 1 токен и нулевым расходом (пустые каталоги) → 0
eq(run(['--budget']).status, 2, 'нет budget.json — потолок не подтверждён')
@@ -567,7 +567,7 @@ async function main() {
if (v.stop) { writeFileSync(stopFile(), now()); console.log('STOP поставлен'); return 0 }
if (v.go) { rmSync(stopFile(), { force: true }); console.log('STOP снят'); return 0 }
if (v.adopt) return cmdAdopt(v.adopt)
console.log('conveyor-gate: --ready --start --finish --task --check-cmd --require --status --beat --budget --stop --go --adopt --selftest --json')
console.log('helioz-gate: --ready --start --finish --task --check-cmd --require --status --beat --budget --stop --go --adopt --selftest --json')
return 0
}
main().then(c => process.exit(c)).catch(e => { console.error(e && e.message || e); process.exit(1) })
@@ -1,7 +1,7 @@
#!/usr/bin/env node
// ШЕСТЬ ВРАЖДЕБНЫХ ПРОБ КОНВЕЙЕРА (порядок стройки, п.3). Все обязаны дать правильный красный/зелёный.
// Только этот прибор пишет READY.json — и только когда все шесть зелёные. Пробы гоняются в изолированном
// CONVEYOR_HOME, боевое состояние не трогается (кроме записи READY.json при успехе).
// HELIOZ_HOME, боевое состояние не трогается (кроме записи READY.json при успехе).
//
// Коды: 0 — все пробы правильные, READY записан · 1 — хотя бы одна проба дала неверный цвет.
import { existsSync, readFileSync, writeFileSync, mkdirSync, mkdtempSync, rmSync, readdirSync, chmodSync } from 'node:fs'
@@ -11,7 +11,7 @@ import path from 'node:path'
import os from 'node:os'
const SCRIPTS = path.dirname(fileURLToPath(import.meta.url))
const HOME = process.env.CONVEYOR_HOME || path.dirname(SCRIPTS)
const HOME = process.env.HELIOZ_HOME || path.dirname(SCRIPTS)
const now = () => new Date().toISOString()
const results = []
function probe(name, ok, detail) {
@@ -20,8 +20,8 @@ function probe(name, ok, detail) {
}
function mkHome() {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'conveyor-probe-'))
for (const d of ['queue/tasks', 'queue/dilemmas', '.conveyor/state', 'docs', 'scripts', 'config']) mkdirSync(path.join(tmp, d), { recursive: true })
const tmp = mkdtempSync(path.join(os.tmpdir(), 'helioz-probe-'))
for (const d of ['queue/tasks', 'queue/dilemmas', '.helioz/state', 'docs', 'scripts', 'config']) mkdirSync(path.join(tmp, d), { recursive: true })
for (const s of readdirSync(SCRIPTS)) if (s.endsWith('.mjs') || s.endsWith('.sh')) writeFileSync(path.join(tmp, 'scripts', s), readFileSync(path.join(SCRIPTS, s)))
execFileSync('git', ['-C', tmp, 'init', '-q'])
writeFileSync(path.join(tmp, 'seed.txt'), 'seed\n')
@@ -30,7 +30,7 @@ function mkHome() {
writeFileSync(path.join(tmp, 'seed.txt'), 'seed\nwork\n')
execFileSync('git', ['-C', tmp, 'add', '-A'])
execFileSync('git', ['-C', tmp, '-c', 'user.email=p@c', '-c', 'user.name=probe', 'commit', '-qm', 'work'])
writeFileSync(path.join(tmp, 'config', 'conveyor.json'), JSON.stringify({ quiet_hours: { start: '00:00', end: '23:59' }, council: { lenses: ['риск', 'цена отката', 'простота'], min_advisors: 3 }, probe_timeout_sec: 5, run_timeout_sec: 5 }))
writeFileSync(path.join(tmp, 'config', 'helioz.json'), JSON.stringify({ quiet_hours: { start: '00:00', end: '23:59' }, council: { lenses: ['риск', 'цена отката', 'простота'], min_advisors: 3 }, probe_timeout_sec: 5, run_timeout_sec: 5 }))
const stub = path.join(tmp, 'bin-adv')
writeFileSync(stub, '#!/bin/sh\ncat >/dev/null 2>&1\necho "ВЫБОР: 1"; echo "ПОЧЕМУ: так."; echo "РИСК ОШИБКИ: нет."\n')
chmodSync(stub, 0o755)
@@ -42,7 +42,7 @@ function mkHome() {
return tmp
}
const task = (id, p, extra = '') => `---\nid: ${id}\npaths:\n - ${p}\nexecutor: claude\nverifier: codex\ncheck_cmd: "true"\n${extra}---\n## Промт исполнителя\nx\n## Промт проверяющего\ny\n`
const gate = (tmp, args) => spawnSync(process.execPath, [path.join(tmp, 'scripts', 'conveyor-gate.mjs'), ...args], { env: { ...process.env, CONVEYOR_HOME: tmp }, encoding: 'utf8' })
const gate = (tmp, args) => spawnSync(process.execPath, [path.join(tmp, 'scripts', 'helioz-gate.mjs'), ...args], { env: { ...process.env, HELIOZ_HOME: tmp }, encoding: 'utf8' })
async function main() {
// ---- 1. Убить оркестратора посреди задачи → новый продолжает без потерь --------------------------
@@ -71,10 +71,10 @@ async function main() {
const tmp = mkHome()
writeFileSync(path.join(tmp, 'queue', 'tasks', 'A.task.md'), task('A', 'docs/a.md'))
gate(tmp, ['--task', 'A', '--check-cmd', 'true'])
const mf = path.join(tmp, '.conveyor', 'state', 'markers', 'A.done.json')
const mf = path.join(tmp, '.helioz', 'state', 'markers', 'A.done.json')
const good = JSON.parse(readFileSync(mf, 'utf8'))
// рукописный
writeFileSync(path.join(tmp, '.conveyor', 'state', 'markers', 'B.done.json'), JSON.stringify({ task: 'B', written_by: 'orchestrator', finished_at: now() }))
writeFileSync(path.join(tmp, '.helioz', 'state', 'markers', 'B.done.json'), JSON.stringify({ task: 'B', written_by: 'orchestrator', finished_at: now() }))
const hand = gate(tmp, ['--require', 'B']).status === 2
// обрезанный (без поля целостности)
const cut = { ...good }; delete cut.sha_of_changed_files
@@ -101,14 +101,14 @@ async function main() {
{
const tmp = mkHome()
writeFileSync(path.join(tmp, 'tg.env'), 'OLYMPUZ_TELEGRAM_TOKEN=PROBETOKEN\nOLYMPUZ_TELEGRAM_CHAT=42\n')
const zeus = path.join(tmp, 'scripts', 'conveyor-zeus.mjs')
const env = api => ({ ...process.env, CONVEYOR_HOME: tmp, CONVEYOR_TG_ENV: path.join(tmp, 'tg.env'), CONVEYOR_TG_API: api })
const zeus = path.join(tmp, 'scripts', 'helioz-zeus.mjs')
const env = api => ({ ...process.env, HELIOZ_HOME: tmp, HELIOZ_TG_ENV: path.join(tmp, 'tg.env'), HELIOZ_TG_API: api })
const runZ = (args, api) => new Promise(res => {
const p = spawn(process.execPath, [zeus, ...args], { env: env(api) })
let out = ''; p.stdout.on('data', c => out += c); p.on('close', status => res({ status, out }))
})
const dead = await runZ(['send', '--text', 'отбивка в никуда'], 'http://127.0.0.1:1')
const obDir = path.join(tmp, '.conveyor', 'state', 'outbox')
const obDir = path.join(tmp, '.helioz', 'state', 'outbox')
const box = () => readdirSync(obDir).map(f => JSON.parse(readFileSync(path.join(obDir, f), 'utf8')))
const kept = dead.status === 0 && box().some(m => !m.delivered_at)
const { createServer } = await import('node:http')
@@ -127,7 +127,7 @@ async function main() {
let all = true, det = []
for (const kind of ['prod', 'foreign', 'expensive']) {
writeFileSync(path.join(tmp, 'queue', 'dilemmas', `DF-${kind}.json`), JSON.stringify({ id: `DF-${kind}`, task: null, kind, question: 'q', options: ['a', 'b'], recommend: 0, status: 'asked', asked_at: now(), answered_at: null, answer: null, decided_by: null, council: null, replay: [] }))
const r = spawnSync(process.execPath, [path.join(tmp, 'scripts', 'conveyor-council.mjs'), 'decide', '--dilemma', `DF-${kind}`, '--day'], { env: { ...process.env, CONVEYOR_HOME: tmp }, encoding: 'utf8' })
const r = spawnSync(process.execPath, [path.join(tmp, 'scripts', 'helioz-council.mjs'), 'decide', '--dilemma', `DF-${kind}`, '--day'], { env: { ...process.env, HELIOZ_HOME: tmp }, encoding: 'utf8' })
const d = JSON.parse(readFileSync(path.join(tmp, 'queue', 'dilemmas', `DF-${kind}.json`), 'utf8'))
const ok = r.status === 2 && d.decided_by === null && d.status === 'asked'
all = all && ok; det.push(`${kind}: ${ok}`)
@@ -151,8 +151,8 @@ async function main() {
const allOk = results.length === 6 && results.every(r => r.ok)
if (allOk) {
const head = (() => { try { return execFileSync('git', ['-C', HOME, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim() } catch { return null } })()
writeFileSync(path.join(HOME, '.conveyor', 'state', 'READY.json'), JSON.stringify({
written_by: 'conveyor-probes', probes: results.map(r => r.name), head, at: now(),
writeFileSync(path.join(HOME, '.helioz', 'state', 'READY.json'), JSON.stringify({
written_by: 'helioz-probes', probes: results.map(r => r.name), head, at: now(),
}, null, 2) + '\n')
console.log('READY.json записан — конвейер готов принимать чужую работу (--adopt)')
return 0
+33
View File
@@ -0,0 +1,33 @@
#!/bin/bash
# ЗАПУСК КОНВЕЙЕРА ОДНОЙ СТРОКОЙ: приборы зелёные → heartbeat → отбивка → что дальше.
set -u
SELF="$(cd "$(dirname "$0")" && pwd)"
HOME_DIR="$(dirname "$SELF")"
cd "$HOME_DIR"
echo "== Проверка приборов (selftests) =="
fail=0
for t in "node scripts/helioz-gate.mjs --selftest" \
"node scripts/helioz-zeus.mjs --selftest" \
"node scripts/helioz-exec.mjs --selftest" \
"node scripts/helioz-council.mjs --selftest" \
"bash scripts/helioz-watchdog.sh --selftest"; do
if $t >/dev/null 2>&1; then echo " ok $t"; else echo " FAIL $t"; fail=1; fi
done
[ "$fail" -eq 0 ] || { echo "приборы красные — запуск запрещён (fail-closed)"; exit 2; }
node scripts/helioz-gate.mjs --beat "start.sh"
node scripts/helioz-zeus.mjs send --text "🚀 Конвейер запущен. Очередь: $(ls queue/tasks/*.task.md 2>/dev/null | wc -l | tr -d ' ') задач. «стоп» — заморозить, «пуск» — продолжить." >/dev/null 2>&1 || true
echo
echo "== Очередь =="
node scripts/helioz-gate.mjs --status || true
echo
if ! launchctl print "gui/$(id -u)/com.helioz.watchdog" >/dev/null 2>&1; then
echo "⚠️ Сторож не установлен. Один раз:"
echo " cp launchd/com.helioz.watchdog.plist ~/Library/LaunchAgents/ && launchctl bootstrap gui/\$(id -u) ~/Library/LaunchAgents/com.helioz.watchdog.plist"
fi
if [ ! -f .helioz/state/budget.json ]; then
echo "⚠️ Нет .helioz/state/budget.json — задай потолок: {\"started_at\":\"$(date -u +%FT%TZ)\",\"ceiling_usd\":N}"
fi
echo "Оркестратор поднимет сторож при протухшем heartbeat, либо вручную: сессия Claude Code в этой папке с промтом ORCHESTRATOR.md"
@@ -7,12 +7,12 @@
# --dry-run: печатает решение, ничего не запускает. --selftest: детерминированные пробы.
set -u
SELF="$(cd "$(dirname "$0")" && pwd)"
HOME_DIR="${CONVEYOR_HOME:-$(dirname "$SELF")}"
STATE="$HOME_DIR/.conveyor/state"
HOME_DIR="${HELIOZ_HOME:-$(dirname "$SELF")}"
STATE="$HOME_DIR/.helioz/state"
LOGS="$STATE/logs"
mkdir -p "$STATE" "$LOGS"
cfg() { node -e "const c=require('$HOME_DIR/config/conveyor.json');console.log(c.$1 ?? '')" 2>/dev/null; }
cfg() { node -e "const c=require('$HOME_DIR/config/helioz.json');console.log(c.$1 ?? '')" 2>/dev/null; }
decide() {
# → печатает START|SKIP:<причина>
@@ -25,41 +25,41 @@ decide() {
fi
# работа есть? незакрытые задачи в очереди (без маркера done)
local pending
pending=$(node "$SELF/conveyor-gate.mjs" --status --json 2>/dev/null | node -e 'let d="";process.stdin.on("data",c=>d+=c);process.stdin.on("end",()=>{try{const j=JSON.parse(d);console.log(j.tasks.filter(t=>t.state==="pending"||t.state==="running").length)}catch{console.log(0)}})' 2>/dev/null || echo 0)
pending=$(node "$SELF/helioz-gate.mjs" --status --json 2>/dev/null | node -e 'let d="";process.stdin.on("data",c=>d+=c);process.stdin.on("end",()=>{try{const j=JSON.parse(d);console.log(j.tasks.filter(t=>t.state==="pending"||t.state==="running").length)}catch{console.log(0)}})' 2>/dev/null || echo 0)
if [ "${pending:-0}" -eq 0 ]; then echo "SKIP:очередь без незакрытых задач"; return; fi
echo "START"
}
if [ "${1:-}" = "--selftest" ]; then
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
mkdir -p "$TMP/.conveyor/state" "$TMP/queue/tasks" "$TMP/config" "$TMP/scripts"
cp "$SELF/conveyor-gate.mjs" "$TMP/scripts/"
echo '{"watchdog_stale_min":15}' > "$TMP/config/conveyor.json"
mkdir -p "$TMP/.helioz/state" "$TMP/queue/tasks" "$TMP/config" "$TMP/scripts"
cp "$SELF/helioz-gate.mjs" "$TMP/scripts/"
echo '{"watchdog_stale_min":15}' > "$TMP/config/helioz.json"
# проба 1: STOP → SKIP
date > "$TMP/.conveyor/state/STOP"
out=$(CONVEYOR_HOME="$TMP" bash "$0" --dry-run)
date > "$TMP/.helioz/state/STOP"
out=$(HELIOZ_HOME="$TMP" bash "$0" --dry-run)
case "$out" in SKIP:STOP*) ;; *) echo "FAIL: при STOP получили '$out'"; exit 1;; esac
rm "$TMP/.conveyor/state/STOP"
rm "$TMP/.helioz/state/STOP"
# проба 2: свежий heartbeat → SKIP
node -e "require('fs').writeFileSync('$TMP/.conveyor/state/heartbeat.json',JSON.stringify({at:new Date().toISOString()}))"
out=$(CONVEYOR_HOME="$TMP" bash "$0" --dry-run)
node -e "require('fs').writeFileSync('$TMP/.helioz/state/heartbeat.json',JSON.stringify({at:new Date().toISOString()}))"
out=$(HELIOZ_HOME="$TMP" bash "$0" --dry-run)
case "$out" in SKIP:heartbeat*) ;; *) echo "FAIL: при свежем heartbeat получили '$out'"; exit 1;; esac
# проба 3: протухший heartbeat + незакрытая задача → START
node -e "require('fs').writeFileSync('$TMP/.conveyor/state/heartbeat.json',JSON.stringify({at:new Date(Date.now()-3600e3).toISOString()}))"
node -e "require('fs').writeFileSync('$TMP/.helioz/state/heartbeat.json',JSON.stringify({at:new Date(Date.now()-3600e3).toISOString()}))"
printf -- '---\nid: TW\npaths:\n - docs/w.md\ncheck_cmd: "true"\n---\n## Промт исполнителя\nx\n## Промт проверяющего\ny\n' > "$TMP/queue/tasks/TW.task.md"
out=$(CONVEYOR_HOME="$TMP" bash "$0" --dry-run)
out=$(HELIOZ_HOME="$TMP" bash "$0" --dry-run)
[ "$out" = "START" ] || { echo "FAIL: при протухшем heartbeat получили '$out'"; exit 1; }
# проба 4: протухший heartbeat, но очередь закрыта → SKIP
rm "$TMP/queue/tasks/TW.task.md"
out=$(CONVEYOR_HOME="$TMP" bash "$0" --dry-run)
out=$(HELIOZ_HOME="$TMP" bash "$0" --dry-run)
case "$out" in SKIP:очередь*) ;; *) echo "FAIL: при пустой очереди получили '$out'"; exit 1;; esac
echo "selftest ok — STOP молчит, свежий heartbeat молчит, протухший+работа стартует, без работы молчит"
exit 0
fi
# штатный прогон: связь с владельцем даже при мёртвом оркестраторе
node "$SELF/conveyor-zeus.mjs" poll --timeout 20 >> "$LOGS/watchdog.log" 2>&1 || true
node "$SELF/conveyor-zeus.mjs" flush >> "$LOGS/watchdog.log" 2>&1 || true
node "$SELF/helioz-zeus.mjs" poll --timeout 20 >> "$LOGS/watchdog.log" 2>&1 || true
node "$SELF/helioz-zeus.mjs" flush >> "$LOGS/watchdog.log" 2>&1 || true
DECISION="$(decide)"
if [ "${1:-}" = "--dry-run" ]; then echo "$DECISION"; exit 0; fi
@@ -76,5 +76,5 @@ if [ -z "$CMD" ]; then echo "$(date '+%F %T') watchdog: orchestrator_cmd пус
TS="$(date +%Y%m%d-%H%M%S)"
nohup bash -lc "$CMD" >> "$LOGS/orchestrator-$TS.log" 2>&1 &
echo $! > "$STATE/orchestrator.pid"
node "$SELF/conveyor-zeus.mjs" send --text "♻️ Оркестратор перезапущен сторожем (heartbeat протух). Продолжаю с хэндоффа, состояние цело." >> "$LOGS/watchdog.log" 2>&1 || true
node "$SELF/helioz-zeus.mjs" send --text "♻️ Оркестратор перезапущен сторожем (heartbeat протух). Продолжаю с хэндоффа, состояние цело." >> "$LOGS/watchdog.log" 2>&1 || true
echo "$(date '+%F %T') watchdog: запущен оркестратор pid $(cat "$STATE/orchestrator.pid")" >> "$LOGS/watchdog.log"
@@ -18,13 +18,13 @@ import { fileURLToPath } from 'node:url'
import path from 'node:path'
import os from 'node:os'
const HOME = process.env.CONVEYOR_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'conveyor.json'), 'utf8')) } catch { return {} } })()
const STATE = path.join(HOME, '.conveyor', 'state')
const HOME = process.env.HELIOZ_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const CFG = (() => { try { return JSON.parse(readFileSync(path.join(HOME, 'config', 'helioz.json'), 'utf8')) } catch { return {} } })()
const STATE = path.join(HOME, '.helioz', 'state')
const OUTBOX = path.join(STATE, 'outbox')
const DILEMMAS = path.join(HOME, 'queue', 'dilemmas')
const API = process.env.CONVEYOR_TG_API || 'https://api.telegram.org'
const SECRETS = process.env.CONVEYOR_TG_ENV || (CFG.secrets_env || '~/.secrets/olympuz-telegram.env').replace(/^~/, os.homedir())
const API = process.env.HELIOZ_TG_API || 'https://api.telegram.org'
const SECRETS = process.env.HELIOZ_TG_ENV || (CFG.secrets_env || '~/.secrets/olympuz-telegram.env').replace(/^~/, os.homedir())
const now = () => new Date().toISOString()
// --- секреты: читаются в момент вызова, не кэшируются в env, в вывод не попадают ------------------
@@ -237,10 +237,10 @@ async function cmdSelftest() {
const { createServer } = await import('node:http')
const { mkdtempSync } = await import('node:fs')
const { spawn } = await import('node:child_process')
const tmp = mkdtempSync(path.join(os.tmpdir(), 'conveyor-zeus-'))
const tmp = mkdtempSync(path.join(os.tmpdir(), 'helioz-zeus-'))
try {
mkdirSync(path.join(tmp, 'queue', 'dilemmas'), { recursive: true })
mkdirSync(path.join(tmp, '.conveyor', 'state'), { recursive: true })
mkdirSync(path.join(tmp, '.helioz', 'state'), { recursive: true })
writeFileSync(path.join(tmp, 'tg.env'), 'OLYMPUZ_TELEGRAM_TOKEN=TESTTOKEN123\nOLYMPUZ_TELEGRAM_CHAT=42\n')
// стаб-сервер Telegram
@@ -260,7 +260,7 @@ async function cmdSelftest() {
await new Promise(r => srv.listen(0, '127.0.0.1', r))
const port = srv.address().port
const self = fileURLToPath(import.meta.url)
const env = (api) => ({ ...process.env, CONVEYOR_HOME: tmp, CONVEYOR_TG_ENV: path.join(tmp, 'tg.env'), CONVEYOR_TG_API: api })
const env = (api) => ({ ...process.env, HELIOZ_HOME: tmp, HELIOZ_TG_ENV: path.join(tmp, 'tg.env'), HELIOZ_TG_API: api })
// spawn (не spawnSync): сервер-стаб живёт в этом же процессе, блокировать event loop нельзя
const run = (args, api = `http://127.0.0.1:${port}`) => new Promise(resolve => {
const p = spawn(process.execPath, [self, ...args], { env: env(api) })
@@ -281,7 +281,7 @@ async function cmdSelftest() {
// 3. Telegram мёртв → отбивка КОПИТСЯ (exit 0, конвейер не падает), затем flush дошлёт.
const r2 = await run(['send', '--text', 'офлайн-отбивка'], 'http://127.0.0.1:1')
eq(r2.status, 0, 'мёртвый Telegram не роняет конвейер')
const box = () => readdirSync(path.join(tmp, '.conveyor', 'state', 'outbox')).map(f => JSON.parse(readFileSync(path.join(tmp, '.conveyor', 'state', 'outbox', f), 'utf8')))
const box = () => readdirSync(path.join(tmp, '.helioz', 'state', 'outbox')).map(f => JSON.parse(readFileSync(path.join(tmp, '.helioz', 'state', 'outbox', f), 'utf8')))
ok(box().some(m => m.text === 'офлайн-отбивка' && !m.delivered_at), 'недоставленное лежит в outbox')
eq((await run(['flush'])).status, 0)
ok(box().every(m => m.delivered_at), 'flush дослал всё')
@@ -318,10 +318,10 @@ async function cmdSelftest() {
// 7. «стоп» из Telegram → STOP на диске; «пуск» → снят.
updates = [{ update_id: 4, message: { from: { id: 42 }, text: 'стоп' } }]
eq((await run(['poll'])).status, 0)
ok(existsSync(path.join(tmp, '.conveyor', 'state', 'STOP')), 'STOP поставлен')
ok(existsSync(path.join(tmp, '.helioz', 'state', 'STOP')), 'STOP поставлен')
updates = [{ update_id: 5, message: { from: { id: 42 }, text: 'пуск' } }]
eq((await run(['poll'])).status, 0)
ok(!existsSync(path.join(tmp, '.conveyor', 'state', 'STOP')), 'STOP снят')
ok(!existsSync(path.join(tmp, '.helioz', 'state', 'STOP')), 'STOP снят')
// 8. Тихие часы: пересечение полуночи.
ok(isQuietHours(new Date('2026-01-01T23:30:00'), { start: '23:00', end: '09:00' }))
@@ -350,7 +350,7 @@ async function main() {
if (cmd === 'ask') return cmdAsk(v.dilemma)
if (cmd === 'flush') return cmdFlush()
if (cmd === 'poll') return cmdPoll(Number(v.timeout) || 0)
console.log('conveyor-zeus: send --text|ask --dilemma|flush|poll [--timeout N] | --selftest')
console.log('helioz-zeus: send --text|ask --dilemma|flush|poll [--timeout N] | --selftest')
return 0
}
main().then(c => process.exit(c)).catch(e => { console.error(String(e && e.message || e)); process.exit(1) })
+1 -1
View File
@@ -5,7 +5,7 @@ import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
const HOME = process.env.CONVEYOR_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const HOME = process.env.HELIOZ_HOME || path.dirname(path.dirname(fileURLToPath(import.meta.url)))
const target = process.argv[2] || path.join(HOME, 'docs', 'LESSON-1.md')
let text