/** 본 작업을 제출하기 전에 CLI 자체 저장소 초기화만 직렬화한다. * 설명 문서: /docs/specs/cli-runtime-initialization.md (v1.1.0) */ const fs = require('fs'); const path = require('path'); const os = require('os'); const { spawn } = require('child_process'); const { createHash } = require('crypto'); const files = require('./protected-file-write'); const { acquireStoreWriteLock } = require('../db/store-write-lock'); const { normalizeExecutableName } = require('../config/cli-paths'); const { quoteShellArgument } = require('../config/claude-execution-config'); const processHelper = require('./process-helper'); const { environmentValue, selectedDatabase } = require('./opencode-database-path'); const defaultDatabaseName = name => /^opencode(?:-[a-zA-Z0-9._-]+)?\.db$/.test(name); function error(code, message) { return Object.assign(new Error(message), { code }); } function check(signal, deadline, isCancelled = () => false) { signal?.throwIfAborted(); if (isCancelled()) throw new Error('CLI initialization cancelled'); if (Date.now() >= deadline) throw error('CLI_INITIALIZATION_TIMEOUT', 'CLI database initialization timed out before submitting the task'); } function wait(signal, ms) { return new Promise((resolve, reject) => { const done = () => { signal?.removeEventListener('abort', abort); resolve(); }; const timer = setTimeout(done, ms); const abort = () => { clearTimeout(timer); signal?.removeEventListener('abort', abort); reject(signal.reason || new Error('CLI initialization cancelled')); }; signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort(); }); } function initialize(command, env, cwd, signal, timeoutMs, isCancelled) { // debug config는 사용자 설정/플러그인을 로드할 수 있다. DB 질의만 실행하며 프롬프트와 // 사용자 CLI 인자는 전달하지 않는다. stdout은 고정 응답 검증에만 쓰고 오류 원문은 노출하지 않는다. let args = ['db', "SELECT 1 AS bada_ready, file AS bada_database FROM pragma_database_list WHERE name = 'main'", '--format', 'json']; if (process.platform === 'win32' && !/\.exe$/i.test(command)) { args = ['-NoLogo', '-NoProfile', '-Command', '& ' + [command, ...args].map(arg => quoteShellArgument(arg, true)).join(' ')]; command = 'powershell.exe'; } return new Promise((resolve, reject) => { let child, timer, cancellation, failure, stdout = '', bytes = 0, settled = false; const kill = () => { if (!child?.pid) return; try { if (process.platform !== 'win32') process.kill(-child.pid, 'SIGKILL'); else processHelper.killProcessTree(child.pid, true); } catch (e) { if (e.code !== 'ESRCH') { try { child.kill('SIGKILL'); } catch {} } } }; const finish = () => { if (settled) return; settled = true; clearTimeout(timer); clearInterval(cancellation); signal?.removeEventListener('abort', abort); process.removeListener('exit', kill); let database; if (!failure) { try { const result = JSON.parse(stdout); if (!Array.isArray(result) || result.length !== 1 || result[0]?.bada_ready !== 1) throw new Error('Invalid readiness result'); database = result[0].bada_database; if (typeof database !== 'string' || !path.isAbsolute(database)) throw new Error('Invalid readiness database'); } catch { failure = error('CLI_INITIALIZATION_FAILED', 'CLI database readiness response was invalid; task was not submitted'); } } if (failure) reject(failure); else resolve(database); }; const stop = reason => { failure ||= reason; kill(); }; const abort = () => stop(signal.reason || new Error('CLI initialization cancelled')); try { child = spawn(command, args, { env, cwd, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32', windowsHide: true }); process.once('exit', kill); // 한글 경로의 UTF-8 문자가 여러 수신 chunk로 갈라져도 같은 문자열로 복원한다. child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); const consume = (data, output) => { bytes += Buffer.byteLength(data); if (bytes > 64 * 1024) stop(error('CLI_INITIALIZATION_OUTPUT_LIMIT', 'CLI initialization output exceeded the limit; task was not submitted')); else if (output) stdout += data; }; child.stdout.on('data', data => consume(data, true)); child.stderr.on('data', data => consume(data, false)); child.once('error', () => { failure ||= error('CLI_INITIALIZATION_SPAWN_FAILED', 'Unable to start CLI database initialization; task was not submitted'); }); // 종료된 부모가 남긴 소유 자식의 pipe까지 정리한 뒤 close에서 잠금을 해제한다. child.once('exit', (code, exitSignal) => { if (code !== 0 || exitSignal) failure ||= error('CLI_INITIALIZATION_FAILED', 'CLI database initialization failed; task was not submitted'); kill(); }); child.once('close', finish); timer = setTimeout(() => stop(error('CLI_INITIALIZATION_TIMEOUT', 'CLI database initialization timed out; task was not submitted')), timeoutMs); cancellation = setInterval(() => { if (isCancelled()) stop(new Error('CLI initialization cancelled')); }, 50); signal?.addEventListener('abort', abort, { once: true }); if (signal?.aborted) abort(); } catch { failure = error('CLI_INITIALIZATION_SPAWN_FAILED', 'Unable to start CLI database initialization; task was not submitted'); kill(); finish(); } }); } function runtimeHash(command, cwd, env, selectedFile) { const envValue = name => environmentValue(env, name); const names = process.platform === 'win32' && !path.extname(command) ? (envValue('PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';').map(ext => command + ext.toLowerCase()) : [command]; const directories = /[\\/]/.test(command) ? [cwd] : (envValue('PATH') || '').split(path.delimiter); for (const directory of directories) for (const name of names) { const candidate = path.resolve(cwd, directory, name); try { const actual = fs.realpathSync(candidate), stat = fs.statSync(actual); if (!stat.isFile()) continue; const identity = [actual, stat.dev, stat.ino, stat.size, stat.mtimeMs, envValue('OPENCODE_DISABLE_CHANNEL_DB') || '']; // 기본 DB의 기존 준비 기록은 보존한다. 명시적 DB는 정규 경로까지 식별한다. if (selectedFile) identity.push(selectedFile); return createHash('sha256').update(JSON.stringify(identity)).digest('hex'); } catch (e) { if (!['ENOENT', 'ENOTDIR'].includes(e.code)) throw e; } } throw error('CLI_INITIALIZATION_SPAWN_FAILED', 'OpenCode executable was not found; task was not submitted'); } function databaseIdentity(file) { const stat = fs.lstatSync(file); if (!stat.isFile() || stat.isSymbolicLink()) throw error('CLI_INITIALIZATION_UNSAFE_PATH', 'CLI database must be a regular file'); return [stat.dev, stat.ino, stat.birthtimeMs]; } async function ensureCliRuntimeReady({ command, env = process.env, cwd = process.cwd(), signal, timeoutMs = 15000, isCancelled = () => false }) { signal?.throwIfAborted(); // CodeAgent 및 다른 CLI에 OpenCode의 DB 명령을 추정 적용하지 않는다. if (normalizeExecutableName(command) !== 'opencode') return; // DB 준비도 외부 실행이다. 엄격 모드에서 준비 명령만 무격리로 먼저 실행하지 않는다. require('../security/host-launch').assertHostPathSupported('uncontained-task'); if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw new Error('Invalid CLI initialization timeout'); const deadline = Date.now() + timeoutMs; const home = environmentValue(env, 'HOME') || environmentValue(env, 'USERPROFILE') || os.homedir(); const dataDirectory = path.resolve(cwd, environmentValue(env, 'XDG_DATA_HOME') || path.join(home, '.local', 'share'), 'opencode'); const selected = selectedDatabase(dataDirectory, environmentValue(env, 'OPENCODE_DB')); // :memory:는 CLI 프로세스마다 별개다. 폐기될 준비 프로세스의 DB를 준비 완료로 기록하지 않는다. if (selected.kind === 'memory') { check(signal, deadline, isCancelled); return; } const selectedName = selected.kind === 'custom' ? path.basename(selected.file) : null; if (selectedName?.toLowerCase().startsWith('.bada-')) throw error('CLI_INITIALIZATION_UNSAFE_PATH', 'CLI database conflicts with wrapper metadata; task was not submitted'); check(signal, deadline, isCancelled); const directory = files.directory(selectedName ? path.dirname(selected.file) : dataDirectory); const selectedFile = selectedName ? path.join(directory, selectedName) : null; const markerName = selectedName ? '.bada-runtime-ready-' + createHash('sha256').update(selectedName).digest('hex') + '.json' : '.bada-runtime-ready.json'; const validDatabaseName = name => selectedName ? name === selectedName : defaultDatabaseName(name); // HOME/XDG가 달라도 같은 DB 부모에서는 같은 잠금으로 준비한다. 기존 기본 DB 잠금과도 협력한다. const lockTarget = path.join(directory, '.bada-runtime-initialization'); const hash = runtimeHash(command, cwd, env, selectedFile); let release; while (!release) { check(signal, deadline, isCancelled); try { release = acquireStoreWriteLock(lockTarget); } catch (e) { if (e.code !== 'KNOWLEDGE_STORE_BUSY') throw e; // 잠금 소유자 종료를 임의 추정해 삭제하지 않는다. 취소/기한은 대기 중에도 적용한다. await wait(signal, Math.min(50, Math.max(1, deadline - Date.now()))); } } try { check(signal, deadline, isCancelled); const markerFile = path.join(directory, markerName); let marker, markerExists = false; try { if (fs.lstatSync(markerFile).size > 4096) throw new Error('Oversized readiness metadata'); marker = JSON.parse(files.readRegular(markerFile).toString('utf8')); markerExists = true; } catch (e) { if (e.code !== 'ENOENT') throw error('CLI_INITIALIZATION_METADATA_INVALID', 'CLI readiness metadata is unreadable; task was not submitted'); } if (markerExists) { if (!marker || marker.version !== 1 || typeof marker.database !== 'string' || !validDatabaseName(marker.database) || typeof marker.runtimeHash !== 'string' || !/^[a-f0-9]{64}$/.test(marker.runtimeHash) || !Array.isArray(marker.identity) || marker.identity.length !== 3 || !marker.identity.every(Number.isFinite)) throw error('CLI_INITIALIZATION_METADATA_INVALID', 'CLI readiness metadata is invalid; task was not submitted'); try { if (marker.runtimeHash === hash && JSON.stringify(databaseIdentity(path.join(directory, marker.database))) === JSON.stringify(marker.identity)) return; } catch (e) { if (e.code !== 'ENOENT') throw e; } } // 이미 준비한 DB에 매번 별도 CLI를 띄우면 본 작업의 DB 사용과 초기화 질의가 다시 // 겹칠 수 있다. 실행 파일과 실제 DB 파일의 신원이 같을 때만 준비 결과를 재사용한다. for (const name of fs.readdirSync(directory)) if (validDatabaseName(name)) databaseIdentity(path.join(directory, name)); const database = await initialize(command, env, cwd, signal, Math.max(1, deadline - Date.now()), isCancelled); check(signal, deadline, isCancelled); if (fs.realpathSync(path.dirname(database)) !== fs.realpathSync(directory) || !validDatabaseName(path.basename(database))) throw error('CLI_INITIALIZATION_UNSAFE_PATH', 'CLI initialized an unexpected database; task was not submitted'); const identity = databaseIdentity(database); files.writeProtected(directory, [markerName], JSON.stringify({ version: 1, runtimeHash: hash, database: path.basename(database), identity }), { replace: true, allowHidden: true }); } finally { release(); } } module.exports = { ensureCliRuntimeReady };