// engine/session-safeguard/precompaction-drain.ts — SPEC-587
// Runs when PreCompaction fires: drains learnings buffer, autopushes commits,
// writes session-context.md — all before context compaction completes.
import { flushBuffer } from './learnings-buffer.js';
import { safeAutopush } from './autopush.js';
/**
 * Regenerate session-context.md (best-effort, resolves projectId automatically).
 * Returns true when successfully written.
 */
async function writeSessionContext(projectPath) {
    try {
        const { generateSessionContext } = await import('../session-context-generator.js');
        const { resolveProjectIdOrAutoDetect } = await import('../../tools/resolve-project-id.js');
        const resolved = await resolveProjectIdOrAutoDetect({ projectPath });
        if (!resolved.ok) {
            return false;
        }
        await generateSessionContext(projectPath, resolved.projectId);
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Drain learnings buffer to MEMORY.md fragments, autopush unpushed commits,
 * and write session-context.md — all before context compaction completes.
 *
 * Every operation is best-effort: a failure in one step does not prevent
 * the others from running. The drain report captures all outcomes.
 */
export async function runPrecompactionDrain(projectPath, options = {}) {
    const { dryRun = false, autopushBranches } = options;
    // 1. Drain learnings buffer to MEMORY.md fragments
    let learningsFlushed = 0;
    if (!dryRun) {
        learningsFlushed = await flushBuffer(projectPath).catch(() => 0);
    }
    // 2. Autopush unpushed commits (best-effort)
    let autopushResult;
    if (!dryRun) {
        const result = await safeAutopush(projectPath, autopushBranches).catch((err) => {
            const msg = err instanceof Error ? err.message : String(err);
            return { pushed: false, reason: msg };
        });
        autopushResult = result.pushed
            ? { pushed: true, ref: result.ref, commitsPushed: result.commitsPushed }
            : { pushed: false, reason: result.reason };
    }
    else {
        autopushResult = { pushed: false, reason: 'dry-run' };
    }
    // 3. Write session-context.md
    let sessionContextWritten = false;
    if (!dryRun) {
        sessionContextWritten = await writeSessionContext(projectPath);
    }
    // Build human summary
    const parts = [];
    if (learningsFlushed > 0) {
        parts.push(`${String(learningsFlushed)} learning(s) flushed to MEMORY.md`);
    }
    if (autopushResult.pushed) {
        parts.push(`autopush: ${String(autopushResult.commitsPushed)} commit(s) pushed to ${autopushResult.ref}`);
    }
    else {
        parts.push(`autopush skipped (${autopushResult.reason})`);
    }
    if (sessionContextWritten) {
        parts.push('session-context.md written');
    }
    const humanSummary = parts.length > 0
        ? `PreCompaction drain: ${parts.join('; ')}`
        : 'PreCompaction drain: nothing to do';
    return {
        learningsFlushed,
        sessionContextWritten,
        autopushResult,
        humanSummary,
    };
}
//# sourceMappingURL=precompaction-drain.js.map