import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
export async function writeThreadSuiteAuditArtifacts(cwd, synthesis) {
    const actions = [];
    const jsonTargets = [
        { path: ".threadwell/project-map.json", value: synthesis.projectMap },
        { path: ".threadwell/retrieval-routes.json", value: synthesis.retrievalRoutes },
    ];
    for (const target of jsonTargets) {
        await writeText(cwd, target.path, `${JSON.stringify(target.value, null, 2)}\n`);
        actions.push({ path: target.path, action: "written" });
    }
    await writeText(cwd, ".threadwell/risk-register.md", renderRiskRegister(synthesis));
    actions.push({ path: ".threadwell/risk-register.md", action: "written" });
    await writeText(cwd, ".threadwell/agent-policy.md", renderAgentPolicy(synthesis));
    actions.push({ path: ".threadwell/agent-policy.md", action: "written" });
    return actions;
}
export function buildThreadSuiteSelfValidationPrompt(synthesis) {
    return [
        "Validate these generated ThreadSuite project-intelligence artifacts.",
        "Use only the provided JSON. Do not assume unstated project facts.",
        'Return strict JSON: {"status":"pass|warn|fail","summary":"string","findings":["string"]}.',
        "Mark warn/fail for generic, uncited, contradictory, or unsupported claims.",
        JSON.stringify({
            projectPurpose: synthesis.projectPurpose,
            projectMap: synthesis.projectMap,
            retrievalRoutes: synthesis.retrievalRoutes,
            riskRegister: synthesis.riskRegister,
            agentPolicy: synthesis.agentPolicy,
        }, null, 2),
    ].join("\n\n");
}
export function parseThreadSuiteSelfValidation(raw) {
    const start = raw.indexOf("{");
    const end = raw.lastIndexOf("}");
    if (start < 0 || end <= start)
        return { status: "warn", summary: "Self-validation did not return JSON.", findings: [] };
    try {
        const parsed = JSON.parse(raw.slice(start, end + 1));
        return {
            status: parsed.status === "pass" || parsed.status === "fail" ? parsed.status : "warn",
            summary: typeof parsed.summary === "string" && parsed.summary.trim() ? parsed.summary.trim() : "No summary.",
            findings: Array.isArray(parsed.findings)
                ? parsed.findings.flatMap((item) => (typeof item === "string" && item.trim() ? [item.trim()] : []))
                : [],
        };
    }
    catch {
        return { status: "warn", summary: "Self-validation JSON was malformed.", findings: [] };
    }
}
async function writeText(cwd, relativePath, content) {
    const absolutePath = join(cwd, relativePath);
    await mkdir(dirname(absolutePath), { recursive: true });
    await writeFile(absolutePath, content, "utf-8");
}
function renderRiskRegister(synthesis) {
    return [
        "# ThreadSuite Risk Register",
        "",
        "Generated by ThreadSuite from cited evidence. Treat inferred items as review-required.",
        "",
        "## Risks and debt",
        ...formatRiskItems(synthesis.riskRegister.items),
        "",
        "## Open questions",
        ...formatOpenQuestions(synthesis.riskRegister.openQuestions),
        "",
    ].join("\n");
}
function renderAgentPolicy(synthesis) {
    return [
        "# ThreadSuite Agent Policy",
        "",
        "Generated from project evidence. Prefer these repo-specific rules before broad exploration.",
        "",
        "## Safe commands",
        ...formatList(synthesis.agentPolicy.safeCommands),
        "",
        "## Expensive commands",
        ...formatList(synthesis.agentPolicy.expensiveCommands),
        "",
        "## Validation expectations",
        ...formatList(synthesis.agentPolicy.validationExpectations),
        "",
        "## Conventions",
        ...formatList(synthesis.agentPolicy.conventions),
        "",
    ].join("\n");
}
function formatRiskItems(items) {
    if (items.length === 0)
        return ["- No cited risks were synthesized."];
    return items.map((item) => `- [${item.severity}/${item.confidence}] ${item.title}: ${item.reason}${item.evidence.length > 0 ? ` (evidence: ${item.evidence.join(", ")})` : ""}`);
}
function formatOpenQuestions(items) {
    if (items.length === 0)
        return ["- No open questions were synthesized."];
    return items.map((item) => `- ${item.question}: ${item.whyItMatters}`);
}
function formatList(items) {
    return items.length > 0 ? items.map((item) => `- ${item}`) : ["- None synthesized."];
}
//# sourceMappingURL=audit-artifacts.js.map