// storage/agent-squad-store.ts — SPEC-551: Persist squad config and run history per project
import { join } from 'node:path';
import { readJson, writeJson, projectDataDir } from './base-store.js';
import { withFileLock } from './file-mutex.js';
function squadConfigPath(projectId) {
    return join(projectDataDir(projectId), 'squad-config.json');
}
function squadRunsPath(projectId) {
    return join(projectDataDir(projectId), 'squad-runs.json');
}
const DEFAULT_CONFIG = {
    projectId: '',
    overrides: [],
    updatedAt: new Date().toISOString(),
};
export async function getSquadConfig(projectId) {
    const config = await readJson(squadConfigPath(projectId), {
        ...DEFAULT_CONFIG,
        projectId,
    });
    return config;
}
export async function setAgentEnabled(projectId, agentId, enabled) {
    const filePath = squadConfigPath(projectId);
    return withFileLock(filePath, async () => {
        const config = await readJson(filePath, {
            ...DEFAULT_CONFIG,
            projectId,
        });
        const idx = config.overrides.findIndex((o) => o.agentId === agentId);
        if (idx >= 0) {
            config.overrides[idx] = { agentId, enabled };
        }
        else {
            config.overrides.push({ agentId, enabled });
        }
        config.updatedAt = new Date().toISOString();
        await writeJson(filePath, config);
        return config;
    });
}
export async function getSquadRuns(projectId) {
    return readJson(squadRunsPath(projectId), []);
}
export async function getSpecRunHistory(projectId, specId) {
    const all = await getSquadRuns(projectId);
    return all.find((h) => h.specId === specId);
}
export async function appendSquadRun(projectId, specId, record) {
    const filePath = squadRunsPath(projectId);
    await withFileLock(filePath, async () => {
        const all = await readJson(filePath, []);
        const existing = all.find((h) => h.specId === specId);
        if (existing) {
            existing.runs.push(record);
        }
        else {
            all.push({ specId, runs: [record] });
        }
        await writeJson(filePath, all);
    });
}
//# sourceMappingURL=agent-squad-store.js.map