import path from 'node:path'; import { mkdir, readFile, writeFile } from 'node:fs/promises'; import { createProjectConversationState, normalizeProjectConversationState, type ProjectConversationState, } from '../../shared/project-conversations'; export const PROJECT_CONVERSATIONS_PATH = '.niancode/conversations.json'; function statePath(projectPath: string): string { return path.join(projectPath, PROJECT_CONVERSATIONS_PATH); } export async function readProjectConversationState(projectPath: string): Promise { try { const raw = JSON.parse(await readFile(statePath(projectPath), 'utf8')) as unknown; return normalizeProjectConversationState(raw); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return createProjectConversationState(); throw error; } } export async function writeProjectConversationState( projectPath: string, value: unknown, ): Promise { const state = normalizeProjectConversationState(value); await mkdir(path.dirname(statePath(projectPath)), { recursive: true }); await writeFile(statePath(projectPath), `${JSON.stringify(state, null, 2)}\n`, 'utf8'); return state; }