152 lines
9.2 KiB
JavaScript
152 lines
9.2 KiB
JavaScript
#!/usr/bin/env node
|
|
// Передача дознанных технических уроков в существующий Koiz, без съемки материалов дел.
|
|
import { readFileSync, realpathSync, mkdirSync, statSync, existsSync, writeFileSync, renameSync } from 'node:fs'
|
|
import path from 'node:path'
|
|
import os from 'node:os'
|
|
import { createHash } from 'node:crypto'
|
|
import { spawnSync } from 'node:child_process'
|
|
import { parseArgs } from 'node:util'
|
|
import { pathToFileURL } from 'node:url'
|
|
|
|
const { values, positionals } = parseArgs({ allowPositionals: true, options: {
|
|
'koiz-root': { type: 'string' }, 'code-root': { type: 'string' }, db: { type: 'string' },
|
|
} })
|
|
|
|
// A directory lock survives a killed process and blocks every retry. The
|
|
// bootstrap acquires a kernel lock, then execs this same process. The fd is
|
|
// inherited across exec and released by the kernel on any process death.
|
|
const lockPidMarker = 'THEMIZ_IMPORT_LOCK_PID'
|
|
const lockDb = path.resolve(values.db || process.env.KOIZ_DB || path.join(os.homedir(), '.claude/koiz/lessons.jsonl'))
|
|
if (process.env[lockPidMarker] !== String(process.pid)) {
|
|
const bootstrap = `
|
|
import fcntl, os, sys
|
|
lock_path, node, *args = sys.argv[1:]
|
|
try:
|
|
fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
os.set_inheritable(fd, True)
|
|
env = os.environ.copy()
|
|
env[${JSON.stringify(lockPidMarker)}] = str(os.getpid())
|
|
os.execve(node, [node, *args], env)
|
|
except (BlockingIOError, OSError):
|
|
print('{"status":"failed","message":"Передача не завершена: импорт Koiz уже выполняется."}', file=sys.stderr)
|
|
raise SystemExit(1)
|
|
`
|
|
try {
|
|
mkdirSync(path.dirname(lockDb), { recursive: true })
|
|
const child = spawnSync('python3', ['-c', bootstrap, `${lockDb}.themiz-import.flock`, process.execPath, ...process.argv.slice(1)], {
|
|
stdio: 'inherit',
|
|
})
|
|
if (child.error || child.status === null) throw new Error('lock bootstrap failed')
|
|
process.exit(child.status)
|
|
} catch {
|
|
console.error(JSON.stringify({ status: 'failed', message: 'Передача не завершена: не удалось получить lock импорта Koiz.' }))
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
try {
|
|
if (positionals.length !== 1 || !values['koiz-root'] || !values['code-root']) {
|
|
throw new Error('нужны PACKET.json --koiz-root ROOT --code-root ROOT [--db FILE]')
|
|
}
|
|
const koizRoot = realpathSync(values['koiz-root'])
|
|
const codeRoot = realpathSync(values['code-root'])
|
|
const db = lockDb
|
|
const raw = readFileSync(positionals[0], 'utf8')
|
|
const packetSha = createHash('sha256').update(raw).digest('hex')
|
|
const packet = JSON.parse(raw)
|
|
const exact = (object, fields) => object && !Array.isArray(object)
|
|
&& Object.keys(object).every(key => fields.includes(key))
|
|
if (!exact(packet, ['id', 'lessons']) || !/^[a-z0-9-]{1,100}$/.test(packet.id || '')
|
|
|| !Array.isArray(packet.lessons) || !packet.lessons.length) {
|
|
throw new Error('неверный пакет технических уроков')
|
|
}
|
|
const koiz = await import(pathToFileURL(path.join(koizRoot, 'scripts/koiz.mjs')).href)
|
|
const { redact, fp } = await import(pathToFileURL(path.join(koizRoot, 'scripts/koiz-lib.mjs')).href)
|
|
const fields = ['what', 'why', 'fix', 'class', 'repro', 'pin', 'pin_ref']
|
|
const lessons = packet.lessons.map(lesson => {
|
|
if (!exact(lesson, fields) || fields.some(key => typeof lesson[key] !== 'string' || !lesson[key].trim())) {
|
|
throw new Error('урок требует причину, починку, воспроизведение и существующий механизм')
|
|
}
|
|
if (!['hook', 'deny', 'прибор', 'тест'].includes(lesson.pin)
|
|
|| !/^[a-z0-9-]{1,100}$/.test(lesson.class)) throw new Error('неверный класс или закрепление')
|
|
for (const key of ['what', 'why', 'fix', 'repro']) {
|
|
const text = lesson[key]
|
|
if (text.length > 4000 || redact(text) !== text || /(?:cases|00_intake|02_hearings)[\\/]|[\w.+-]+@[\w.-]+\.[a-z]{2,}/i.test(text)) {
|
|
throw new Error('пакет содержит недопустимый текст; нужен обезличенный технический урок')
|
|
}
|
|
}
|
|
// Механизм берется из исходного кода, а не из частного отчета или первички.
|
|
if (!/^(?:scripts\/|tests\/|AGENTS\.md$)/.test(lesson.pin_ref)) throw new Error('механизм должен быть в scripts, tests или AGENTS.md')
|
|
const mechanism = realpathSync(path.resolve(codeRoot, lesson.pin_ref))
|
|
const relative = path.relative(codeRoot, mechanism)
|
|
if (!statSync(mechanism).isFile() || relative.startsWith('..') || path.isAbsolute(relative)
|
|
|| !/^(?:scripts\/|tests\/|AGENTS\.md$)/.test(relative)) throw new Error('механизм вышел из корня кода')
|
|
return { ...lesson, pin_ref: mechanism, project: 'themiz', origin: 'проверенный технический разбор',
|
|
session: `themiz-koiz:${packet.id}` }
|
|
})
|
|
// Квитанция завершения нужна для окна add/hit → cause → pin. Одного seen
|
|
// недостаточно: процесс мог оборваться после hit, но до закрепления.
|
|
const receiptDir = path.join(path.dirname(db), '.themiz-import-receipts')
|
|
const receiptFile = path.join(receiptDir, createHash('sha256').update(`${db}\0${packet.id}`).digest('hex') + '.json')
|
|
const receipt = existsSync(receiptFile) ? JSON.parse(readFileSync(receiptFile, 'utf8'))
|
|
: { sha256: packetSha, done: {} }
|
|
if (receipt.sha256 !== packetSha) throw new Error('ранее переданный пакет изменен')
|
|
const saveReceipt = () => {
|
|
mkdirSync(receiptDir, { recursive: true })
|
|
const temp = `${receiptFile}.${process.pid}.tmp`
|
|
writeFileSync(temp, JSON.stringify(receipt), { mode: 0o600 })
|
|
renameSync(temp, receiptFile)
|
|
}
|
|
const before = koiz.state(db)
|
|
const known = new Set([...before.L.values()].map(lesson => lesson.fp))
|
|
const keys = lessons.map(lesson => fp(`${lesson.what.trim()} ${lesson.why.trim()}`))
|
|
if (new Set(keys).size !== keys.length) throw new Error('один урок повторен внутри пакета')
|
|
for (const lesson of lessons) {
|
|
const key = fp(`${lesson.what.trim()} ${lesson.why.trim()}`)
|
|
const twin = [...before.L.values()].find(item => item.fp === key)
|
|
if (twin?.closed && !before.seen.has(`${key}|${lesson.session}`)) {
|
|
throw new Error('новый пакет ссылается на закрытый урок; требуется разбор истории')
|
|
}
|
|
}
|
|
const newKeys = new Set(lessons.map(lesson => fp(`${lesson.what.trim()} ${lesson.why.trim()}`))
|
|
.filter(key => !known.has(key)))
|
|
const stats = koiz.stats({ db })
|
|
// Не схлопываем чужую базу побочным эффектом импорта.
|
|
// Бюджет меряет ЗНАНИЕ, а не машинное сырьё (решение владельца 21.09.2026):
|
|
// 340 сырых записей держали чужой потолок и запирали передачу уроков из дома.
|
|
const busy = (stats.knowledge ?? stats.active) + stats.rules + newKeys.size
|
|
if (busy > stats.budget) throw new Error('бюджет Koiz требует отдельного разбора')
|
|
saveReceipt()
|
|
const records = lessons.map(lesson => {
|
|
const key = fp(`${lesson.what.trim()} ${lesson.why.trim()}`)
|
|
if (receipt.done[key]) {
|
|
const current = koiz.state(db).L.get(receipt.done[key])
|
|
if (!current) throw new Error('квитанция расходится с журналом Koiz')
|
|
return { id: current.id, op: 'seen', class: current.class,
|
|
pin: current.pin, closed: Boolean(current.closed) }
|
|
}
|
|
const result = koiz.addLesson(lesson, db)
|
|
const current = koiz.state(db).L.get(result.id)
|
|
if (!current) throw new Error('урок отсутствует в Koiz')
|
|
if (current.closed) throw new Error('урок закрыт в Koiz; требуется разбор истории')
|
|
if (current.why !== lesson.why || current.fix !== lesson.fix) {
|
|
koiz.causeLesson(result.id, lesson.why, lesson.fix, db)
|
|
}
|
|
if (current.pin !== lesson.pin || current.pin_ref !== lesson.pin_ref) {
|
|
koiz.pinLesson(result.id, lesson.pin, lesson.pin_ref, db)
|
|
}
|
|
receipt.done[key] = result.id
|
|
saveReceipt()
|
|
return { id: result.id, op: result.op, class: lesson.class, pin: lesson.pin }
|
|
})
|
|
koiz.writeGraph({ db, dir: path.join(path.dirname(db), 'graphify-out') })
|
|
console.log(JSON.stringify({ packet: packet.id,
|
|
sha256: packetSha, records }, null, 2))
|
|
} catch (error) {
|
|
// Сырые ошибки стороннего модуля могут включать входной текст и частные пути.
|
|
console.error(JSON.stringify({ status: 'failed', error_type: error.name,
|
|
message: 'Передача не завершена. Проверьте пакет, пути и доступность базы; повтор того же пакета идемпотентен.' }))
|
|
process.exitCode = 1
|
|
}
|