// tools/git/auto-complete-ops.ts — Auto-complete specs whose branches were merged
import { specStore } from '../../storage/index.js';
import { git } from './git-helpers.js';
/**
 * SPEC-176 / SPEC-399: Auto-mark specs as done when their git branch is merged.
 * Checks both "implementing" and "approved" specs. Matches by:
 *   1. Exact spec.gitBranch (set via MCP create-branch)
 *   2. Pattern: any merged branch containing /SPEC-{id}-/ or /SPEC-{id}$ (manual branches)
 * Falls back to 'main' if 'develop' does not exist.
 * Safe to call best-effort — caller should .catch(() => []).
 */
export async function autoCompleteSpecs(projectId, projectPath) {
    let mergedOut;
    try {
        const r = await git(projectPath, ['branch', '--merged', 'develop']);
        mergedOut = r.stdout;
    }
    catch {
        const r = await git(projectPath, ['branch', '--merged', 'main']);
        mergedOut = r.stdout;
    }
    const mergedList = mergedOut
        .split('\n')
        .map((b) => b.replace(/^\*?\s+/, '').trim())
        .filter(Boolean);
    const mergedSet = new Set(mergedList);
    function isMerged(specId, gitBranch) {
        if (gitBranch && mergedSet.has(gitBranch)) {
            return true;
        }
        const num = /SPEC-(\d+)/i.exec(specId)?.[1];
        if (!num) {
            return false;
        }
        const pat = new RegExp(`[/\\-]SPEC-${num}([/\\-]|$)`, 'i');
        return mergedList.some((b) => pat.test(b));
    }
    const specs = (await specStore.listSpecs(projectId)).filter((s) => (s.status === 'implementing' || s.status === 'approved') && isMerged(s.id, s.gitBranch));
    const completed = [];
    const blocked = [];
    for (const spec of specs) {
        const { handleUpdateStatus } = await import('../update-status/index.js');
        const input = {
            specId: spec.id,
            status: 'done',
            projectId,
            projectPath,
            trigger: 'git-merge',
            actor: 'system',
            reviewNotes: 'Auto-completed: branch merged',
        };
        const result = await handleUpdateStatus(input);
        if (result.isError) {
            const reason = result.content[0]?.type === 'text' ? result.content[0].text : 'gate blocked (no message)';
            blocked.push({ specId: spec.id, reason });
        }
        else {
            completed.push(spec.id);
        }
    }
    return { completed, blocked };
}
//# sourceMappingURL=auto-complete-ops.js.map