import {
  listTrackedWUStampIds
} from "./chunk-LV47RFNJ.js";
import {
  WU_EVENT_TYPE,
  withMicroWorktree
} from "./chunk-2GXVIN57.js";
import {
  createGitForPath
} from "./chunk-2UFQ3A3C.js";
import {
  normalizeToDateString,
  parseYAML,
  stringifyYAML,
  todayISO
} from "./chunk-NRIZR3A7.js";
import {
  createWuPaths
} from "./chunk-6HO4GWJE.js";
import {
  CONSISTENCY_MESSAGES,
  CONSISTENCY_TYPES,
  LOG_PREFIX,
  LUMENFLOW_PATHS,
  REMOTES,
  STRING_LITERALS,
  YAML_OPTIONS,
  toKebab
} from "./chunk-DWMLTXKQ.js";
import {
  WU_STATUS
} from "./chunk-V6OJGLBA.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../core/dist/wu-consistency-detector.js
import { readFile, readdir, access } from "fs/promises";
import { constants } from "fs";
import path from "path";
var UNKNOWN_WU_STATUS = "unknown";
function readOptionalStringField(value, fieldName) {
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
    return void 0;
  }
  const fieldValue = Reflect.get(value, fieldName);
  return typeof fieldValue === "string" ? fieldValue : void 0;
}
function parseWUConsistencyDoc(content) {
  const parsed = parseYAML(content);
  return {
    status: readOptionalStringField(parsed, "status"),
    lane: readOptionalStringField(parsed, "lane"),
    title: readOptionalStringField(parsed, "title"),
    worktree_path: readOptionalStringField(parsed, "worktree_path")
  };
}
async function checkWUConsistency(id, projectRoot = process.cwd(), options = {}) {
  const errors = [];
  const paths = createWuPaths({ projectRoot });
  const wuPath = path.join(projectRoot, paths.WU(id));
  const stampPath = path.join(projectRoot, paths.STAMP(id));
  const backlogPath = path.join(projectRoot, paths.BACKLOG());
  const statusPath = path.join(projectRoot, paths.STATUS());
  try {
    await access(wuPath, constants.R_OK);
  } catch {
    return { valid: true, errors: [], stats: { wuExists: false } };
  }
  const wuContent = await readFile(wuPath, { encoding: "utf-8" });
  const wuDoc = parseWUConsistencyDoc(wuContent);
  const yamlStatus = wuDoc.status || UNKNOWN_WU_STATUS;
  const lane = wuDoc.lane || "";
  const title = wuDoc.title || "";
  const worktreePathFromYaml = wuDoc.worktree_path || "";
  let hasStampFile;
  try {
    await access(stampPath, constants.R_OK);
    hasStampFile = true;
  } catch {
    hasStampFile = false;
  }
  const trackedStampIds = options.trackedStampIds ?? await listTrackedWUStampIds({ projectRoot, stampsDir: paths.STAMPS_DIR() });
  const hasStamp = hasStampFile && (trackedStampIds === null || trackedStampIds.has(id));
  let backlogContent;
  try {
    backlogContent = await readFile(backlogPath, { encoding: "utf-8" });
  } catch {
    backlogContent = "";
  }
  const { inDone: backlogInDone, inProgress: backlogInProgress } = parseBacklogSections(backlogContent, id);
  let statusContent;
  try {
    statusContent = await readFile(statusPath, { encoding: "utf-8" });
  } catch {
    statusContent = "";
  }
  const { inProgress: statusInProgress } = parseStatusSections(statusContent, id);
  const normalizedId = id.toUpperCase();
  const hasWorktree = options.activeWorktreeIds !== void 0 ? options.activeWorktreeIds !== null && options.activeWorktreeIds.has(normalizedId) : await checkWorktreeExists(id, projectRoot);
  const worktreePathExists = await checkWorktreePathExists(worktreePathFromYaml);
  if (yamlStatus === WU_STATUS.DONE && statusInProgress) {
    errors.push({
      type: CONSISTENCY_TYPES.YAML_DONE_STATUS_IN_PROGRESS,
      wuId: id,
      description: `WU ${id} has status '${WU_STATUS.DONE}' in YAML but still appears in status.md In Progress section`,
      repairAction: "Remove from status.md In Progress section",
      canAutoRepair: true
    });
  }
  if (backlogInDone && backlogInProgress) {
    errors.push({
      type: CONSISTENCY_TYPES.BACKLOG_DUAL_SECTION,
      wuId: id,
      description: `WU ${id} appears in both Done and In Progress sections of backlog.md`,
      repairAction: "Remove from In Progress section (Done wins)",
      canAutoRepair: true
    });
  }
  if (yamlStatus === WU_STATUS.DONE && !hasStamp) {
    errors.push({
      type: CONSISTENCY_TYPES.YAML_DONE_NO_STAMP,
      wuId: id,
      title,
      description: `WU ${id} has status '${WU_STATUS.DONE}' but no stamp file exists`,
      repairAction: "Create stamp file",
      canAutoRepair: true
    });
  }
  if (yamlStatus === WU_STATUS.DONE && hasWorktree) {
    errors.push({
      type: CONSISTENCY_TYPES.ORPHAN_WORKTREE_DONE,
      wuId: id,
      lane,
      description: `WU ${id} has status '${WU_STATUS.DONE}' but still has an associated worktree`,
      repairAction: "Remove orphan worktree and lane branch",
      canAutoRepair: true
    });
  }
  if (hasStamp && yamlStatus !== WU_STATUS.DONE) {
    errors.push({
      type: CONSISTENCY_TYPES.STAMP_EXISTS_YAML_NOT_DONE,
      wuId: id,
      title,
      description: `WU ${id} has stamp file but YAML status is '${yamlStatus}' (not done)`,
      repairAction: "Update YAML to done+locked+completed",
      canAutoRepair: true
    });
  }
  if (worktreePathFromYaml && !worktreePathExists && (yamlStatus === WU_STATUS.IN_PROGRESS || yamlStatus === WU_STATUS.BLOCKED)) {
    errors.push({
      type: CONSISTENCY_TYPES.MISSING_WORKTREE_CLAIMED,
      wuId: id,
      title,
      description: CONSISTENCY_MESSAGES.MISSING_WORKTREE_CLAIMED(id, yamlStatus, worktreePathFromYaml),
      repairAction: CONSISTENCY_MESSAGES.MISSING_WORKTREE_CLAIMED_REPAIR,
      canAutoRepair: false
    });
  }
  return {
    valid: errors.length === 0,
    errors,
    stats: {
      yamlStatus,
      hasStamp,
      backlogInDone,
      backlogInProgress,
      statusInProgress,
      hasWorktree,
      worktreePathExists
    }
  };
}
async function checkAllWUConsistency(projectRoot = process.cwd()) {
  const paths = createWuPaths({ projectRoot });
  const wuDir = path.join(projectRoot, paths.WU_DIR());
  try {
    await access(wuDir, constants.R_OK);
  } catch {
    return { valid: true, errors: [], checked: 0 };
  }
  const allErrors = [];
  const wuFiles = (await readdir(wuDir)).filter((f) => /^WU-\d+\.yaml$/.test(f));
  const trackedStampIds = await listTrackedWUStampIds({
    projectRoot,
    stampsDir: paths.STAMPS_DIR()
  });
  const activeWorktreeIds = await listActiveWorktreeIds(projectRoot);
  for (const file of wuFiles) {
    const id = file.replace(".yaml", "");
    const report = await checkWUConsistency(id, projectRoot, {
      trackedStampIds,
      activeWorktreeIds
    });
    allErrors.push(...report.errors);
  }
  return {
    valid: allErrors.length === 0,
    errors: allErrors,
    checked: wuFiles.length
  };
}
async function checkLaneForOrphanDoneWU(lane, excludeId, projectRoot = process.cwd()) {
  const paths = createWuPaths({ projectRoot });
  const wuDir = path.join(projectRoot, paths.WU_DIR());
  const trackedStampIds = await listTrackedWUStampIds({
    projectRoot,
    stampsDir: paths.STAMPS_DIR()
  });
  try {
    await access(wuDir, constants.R_OK);
  } catch {
    return { valid: true, orphans: [] };
  }
  const orphans = [];
  const wuFiles = (await readdir(wuDir)).filter((f) => /^WU-\d+\.yaml$/.test(f));
  for (const file of wuFiles) {
    const id = file.replace(".yaml", "");
    if (id === excludeId)
      continue;
    const wuPath = path.join(wuDir, file);
    let wuContent;
    try {
      wuContent = await readFile(wuPath, { encoding: "utf-8" });
    } catch {
      continue;
    }
    let wuDoc;
    try {
      wuDoc = parseYAML(wuContent);
    } catch {
      continue;
    }
    if (wuDoc?.lane === lane && wuDoc?.status === WU_STATUS.DONE) {
      const report = await checkWUConsistency(id, projectRoot, { trackedStampIds });
      if (!report.valid) {
        orphans.push({ id, errors: report.errors });
      }
    }
  }
  return {
    valid: orphans.length === 0,
    orphans: orphans.map((o) => o.id),
    reports: orphans
  };
}
function parseBacklogSections(content, id) {
  const lines = content.split(/\r?\n/);
  let inDone = false;
  let inProgress = false;
  let currentSection = null;
  const exactPattern = `(wu/${id}.yaml)`;
  for (const line of lines) {
    if (line.trim() === "## \u2705 Done") {
      currentSection = WU_STATUS.DONE;
      continue;
    }
    if (line.trim() === "## \u{1F527} In progress") {
      currentSection = WU_STATUS.IN_PROGRESS;
      continue;
    }
    if (line.trim().startsWith("## ")) {
      currentSection = null;
      continue;
    }
    if (line.includes(exactPattern)) {
      if (currentSection === WU_STATUS.DONE)
        inDone = true;
      if (currentSection === WU_STATUS.IN_PROGRESS)
        inProgress = true;
    }
  }
  return { inDone, inProgress };
}
function parseStatusSections(content, id) {
  const lines = content.split(/\r?\n/);
  let inProgress = false;
  let currentSection = null;
  const exactPattern = `(wu/${id}.yaml)`;
  for (const line of lines) {
    if (line.trim() === "## In Progress") {
      currentSection = WU_STATUS.IN_PROGRESS;
      continue;
    }
    if (line.trim().startsWith("## ")) {
      currentSection = null;
      continue;
    }
    if (currentSection === WU_STATUS.IN_PROGRESS && line.includes(exactPattern)) {
      inProgress = true;
    }
  }
  return { inProgress };
}
async function checkWorktreeExists(id, projectRoot) {
  try {
    const git = createGitForPath(projectRoot);
    const output = await git.worktreeList();
    const pattern = new RegExp(`${id.toLowerCase()}(?![0-9])`, "i");
    return pattern.test(output);
  } catch {
    return false;
  }
}
async function listActiveWorktreeIds(projectRoot) {
  try {
    const git = createGitForPath(projectRoot);
    const output = await git.worktreeList();
    const matches = output.match(/\bwu-\d+\b/gi) ?? [];
    const ids = /* @__PURE__ */ new Set();
    for (const match of matches) {
      ids.add(match.toUpperCase());
    }
    return ids;
  } catch {
    return null;
  }
}
async function checkWorktreePathExists(worktreePath) {
  if (!worktreePath) {
    return false;
  }
  try {
    await access(worktreePath, constants.R_OK);
    return true;
  } catch {
    return false;
  }
}

// ../core/dist/wu-consistency-file-repairs.js
import path2 from "path";
import { existsSync, mkdirSync, writeFileSync, readFileSync, constants as constants2 } from "fs";
import { access as access2 } from "fs/promises";
async function createStampInWorktree(id, title, worktreePath, projectRoot) {
  const paths = createWuPaths({ projectRoot });
  const stampsDir = path2.join(worktreePath, paths.STAMPS_DIR());
  const stampRelPath = paths.STAMP(id);
  const stampAbsPath = path2.join(worktreePath, stampRelPath);
  if (!existsSync(stampsDir)) {
    mkdirSync(stampsDir, { recursive: true });
  }
  if (existsSync(stampAbsPath)) {
    return [];
  }
  const body = `WU ${id} \u2014 ${title}
Completed: ${todayISO()}
`;
  writeFileSync(stampAbsPath, body, { encoding: "utf-8" });
  return [stampRelPath];
}
async function updateYamlToDoneInWorktree(id, worktreePath, projectRoot) {
  const paths = createWuPaths({ projectRoot });
  const wuRelPath = paths.WU(id);
  const wuSrcPath = path2.join(projectRoot, wuRelPath);
  const wuDestPath = path2.join(worktreePath, wuRelPath);
  const wuReadPath = existsSync(wuDestPath) ? wuDestPath : wuSrcPath;
  const content = readFileSync(wuReadPath, { encoding: "utf-8" });
  const wuDoc = parseYAML(content);
  if (!wuDoc) {
    throw createError(ErrorCodes.YAML_PARSE_ERROR, `Failed to parse WU YAML: ${wuReadPath}`);
  }
  wuDoc.status = WU_STATUS.DONE;
  wuDoc.locked = true;
  const existingCompletedAt = wuDoc.completed_at;
  const completionTimestamp = typeof existingCompletedAt === "string" ? existingCompletedAt : existingCompletedAt instanceof Date ? existingCompletedAt.toISOString() : (/* @__PURE__ */ new Date()).toISOString();
  wuDoc.completed_at = completionTimestamp;
  wuDoc.completed = normalizeToDateString(wuDoc.completed ?? completionTimestamp) ?? completionTimestamp.slice(0, 10);
  const wuDir = path2.dirname(wuDestPath);
  if (!existsSync(wuDir)) {
    mkdirSync(wuDir, { recursive: true });
  }
  const updatedContent = stringifyYAML(wuDoc, { lineWidth: YAML_OPTIONS.LINE_WIDTH });
  writeFileSync(wuDestPath, updatedContent, { encoding: "utf-8" });
  const eventFiles = appendReconciliationEventsInWorktree({
    id,
    lane: wuDoc.lane,
    title: wuDoc.title,
    projectRoot,
    worktreePath
  });
  return [wuRelPath, ...eventFiles];
}
function deriveStatusFromEvents(eventsContent, wuId) {
  let status;
  const lines = eventsContent.split(/\r?\n/);
  for (const line of lines) {
    if (!line.trim())
      continue;
    try {
      const event = JSON.parse(line);
      if (event.wuId !== wuId || !event.type)
        continue;
      switch (event.type) {
        case WU_EVENT_TYPE.CLAIM:
        case WU_EVENT_TYPE.CREATE:
          status = WU_STATUS.IN_PROGRESS;
          break;
        case WU_EVENT_TYPE.RELEASE:
          status = WU_STATUS.READY;
          break;
        case WU_EVENT_TYPE.COMPLETE:
          status = WU_STATUS.DONE;
          break;
        case WU_EVENT_TYPE.BLOCK:
          status = WU_STATUS.BLOCKED;
          break;
        case WU_EVENT_TYPE.UNBLOCK:
          status = WU_STATUS.IN_PROGRESS;
          break;
      }
    } catch {
    }
  }
  return status;
}
function appendReconciliationEventsInWorktree({ id, lane, title, projectRoot, worktreePath }) {
  const eventsRelPath = LUMENFLOW_PATHS.WU_EVENTS;
  const eventsSrcPath = path2.join(projectRoot, eventsRelPath);
  const eventsDestPath = path2.join(worktreePath, eventsRelPath);
  const eventsReadPath = existsSync(eventsDestPath) ? eventsDestPath : eventsSrcPath;
  const existingContent = existsSync(eventsReadPath) ? readFileSync(eventsReadPath, { encoding: "utf-8" }) : "";
  const derivedStatus = deriveStatusFromEvents(existingContent, id);
  if (derivedStatus === WU_STATUS.DONE) {
    return [];
  }
  const now = (/* @__PURE__ */ new Date()).toISOString();
  const appendEvents = [];
  if (derivedStatus !== WU_STATUS.IN_PROGRESS) {
    appendEvents.push({
      type: WU_EVENT_TYPE.CLAIM,
      wuId: id,
      lane: typeof lane === "string" && lane.trim().length > 0 ? lane : "Operations: Tooling",
      title: typeof title === "string" && title.trim().length > 0 ? title : `WU ${id}`,
      timestamp: now
    });
  }
  appendEvents.push({
    type: WU_EVENT_TYPE.COMPLETE,
    wuId: id,
    reason: "wu:repair consistency reconciliation for stamp/yaml mismatch",
    timestamp: now
  });
  const destDir = path2.dirname(eventsDestPath);
  if (!existsSync(destDir)) {
    mkdirSync(destDir, { recursive: true });
  }
  const suffix = appendEvents.map((event) => JSON.stringify(event)).join(STRING_LITERALS.NEWLINE);
  const normalizedExisting = existingContent ? existingContent.endsWith(STRING_LITERALS.NEWLINE) ? existingContent : `${existingContent}${STRING_LITERALS.NEWLINE}` : "";
  writeFileSync(eventsDestPath, `${normalizedExisting}${suffix}${STRING_LITERALS.NEWLINE}`, {
    encoding: "utf-8"
  });
  return [eventsRelPath];
}
async function removeWUFromSectionInWorktree(relFilePath, id, sectionHeading, worktreePath, projectRoot) {
  const srcPath = path2.join(projectRoot, relFilePath);
  const destPath = path2.join(worktreePath, relFilePath);
  if (!existsSync(srcPath)) {
    return [];
  }
  const content = readFileSync(srcPath, { encoding: "utf-8" });
  const lines = content.split(/\r?\n/);
  let inTargetSection = false;
  let nextSectionIdx = -1;
  let sectionStartIdx = -1;
  const normalizedHeading = sectionHeading.toLowerCase().trim();
  for (let i = 0; i < lines.length; i++) {
    const currentLine = lines[i] ?? "";
    const normalizedLine = currentLine.toLowerCase().trim();
    if (normalizedLine === normalizedHeading || normalizedLine.startsWith(normalizedHeading)) {
      inTargetSection = true;
      sectionStartIdx = i;
      continue;
    }
    if (inTargetSection && currentLine.trim().startsWith("## ")) {
      nextSectionIdx = i;
      break;
    }
  }
  if (sectionStartIdx === -1)
    return [];
  const endIdx = nextSectionIdx === -1 ? lines.length : nextSectionIdx;
  const newLines = [];
  let modified = false;
  for (let i = 0; i < lines.length; i++) {
    const currentLine = lines[i] ?? "";
    if (i > sectionStartIdx && i < endIdx && currentLine.includes(id)) {
      modified = true;
      continue;
    }
    newLines.push(currentLine);
  }
  if (!modified)
    return [];
  const destDir = path2.dirname(destPath);
  if (!existsSync(destDir)) {
    mkdirSync(destDir, { recursive: true });
  }
  writeFileSync(destPath, newLines.join(STRING_LITERALS.NEWLINE), { encoding: "utf-8" });
  return [relFilePath];
}
async function removeOrphanWorktree(id, lane, projectRoot) {
  const laneKebab = toKebab(lane);
  const worktreeName = `${laneKebab}-${id.toLowerCase()}`;
  const worktreePath = path2.join(projectRoot, "worktrees", worktreeName);
  const cwd = process.cwd();
  if (cwd.startsWith(worktreePath)) {
    return { skipped: true, reason: "Cannot delete worktree while inside it" };
  }
  try {
    await access2(worktreePath, constants2.R_OK);
    try {
      const gitWorktree = createGitForPath(worktreePath);
      const status = await gitWorktree.getStatus();
      if (status.trim().length > 0) {
        return { skipped: true, reason: "Worktree has uncommitted changes" };
      }
    } catch {
    }
  } catch {
  }
  const paths = createWuPaths({ projectRoot });
  const stampPath = path2.join(projectRoot, paths.STAMP(id));
  try {
    await access2(stampPath, constants2.R_OK);
  } catch {
    return { skipped: true, reason: "WU marked done but no stamp - possible rollback state" };
  }
  const git = createGitForPath(projectRoot);
  try {
    await access2(worktreePath, constants2.R_OK);
    await git.worktreeRemove(worktreePath, { force: true });
  } catch {
  }
  const branchName = `lane/${laneKebab}/${id.toLowerCase()}`;
  try {
    await git.deleteBranch(branchName, { force: true });
  } catch {
  }
  try {
    await git.raw(["push", REMOTES.ORIGIN, "--delete", branchName]);
  } catch {
  }
  return { success: true };
}

// ../core/dist/wu-inconsistency-repairer.js
var FILE_REPAIR_STRATEGIES = {
  [CONSISTENCY_TYPES.YAML_DONE_NO_STAMP]: async (error, worktreePath, projectRoot) => {
    const files = await createStampInWorktree(error.wuId, error.title || `WU ${error.wuId}`, worktreePath, projectRoot);
    return { success: true, files };
  },
  [CONSISTENCY_TYPES.YAML_DONE_STATUS_IN_PROGRESS]: async (error, worktreePath, projectRoot) => {
    const paths = createWuPaths({ projectRoot });
    const files = await removeWUFromSectionInWorktree(paths.STATUS(), error.wuId, "## In Progress", worktreePath, projectRoot);
    return { success: true, files };
  },
  [CONSISTENCY_TYPES.BACKLOG_DUAL_SECTION]: async (error, worktreePath, projectRoot) => {
    const paths = createWuPaths({ projectRoot });
    const files = await removeWUFromSectionInWorktree(paths.BACKLOG(), error.wuId, "## \u{1F527} In progress", worktreePath, projectRoot);
    return { success: true, files };
  },
  [CONSISTENCY_TYPES.STAMP_EXISTS_YAML_NOT_DONE]: async (error, worktreePath, projectRoot) => {
    const files = await updateYamlToDoneInWorktree(error.wuId, worktreePath, projectRoot);
    return { success: true, files };
  }
};
var GIT_REPAIR_STRATEGIES = {
  [CONSISTENCY_TYPES.ORPHAN_WORKTREE_DONE]: async (error, projectRoot) => {
    if (!error.lane) {
      return { skipped: true, reason: "Missing lane metadata for orphan worktree cleanup" };
    }
    return await removeOrphanWorktree(error.wuId, error.lane, projectRoot);
  }
};
function categorizeErrors(errors) {
  const fileRepairs = [];
  const gitOnlyRepairs = [];
  const nonRepairable = [];
  for (const error of errors) {
    if (!error.canAutoRepair) {
      nonRepairable.push(error);
      continue;
    }
    if (error.type in GIT_REPAIR_STRATEGIES) {
      gitOnlyRepairs.push(error);
    } else {
      fileRepairs.push(error);
    }
  }
  return { fileRepairs, gitOnlyRepairs, nonRepairable };
}
async function repairSingleErrorInWorktree(error, worktreePath, projectRoot) {
  const strategy = FILE_REPAIR_STRATEGIES[error.type];
  if (!strategy) {
    return { skipped: true, reason: `Unknown error type: ${error.type}` };
  }
  return strategy(error, worktreePath, projectRoot);
}
async function repairGitOnlyError(error, projectRoot) {
  const strategy = GIT_REPAIR_STRATEGIES[error.type];
  if (!strategy) {
    return { skipped: true, reason: `Unknown git-only error type: ${error.type}` };
  }
  return strategy(error, projectRoot);
}
async function repairWUInconsistency(report, options = {}) {
  const { dryRun = false, projectRoot } = options;
  const isInsideMicroWorktree = projectRoot !== void 0;
  const effectiveProjectRoot = projectRoot ?? process.cwd();
  if (report.valid) {
    return { repaired: 0, skipped: 0, failed: 0 };
  }
  const { fileRepairs, gitOnlyRepairs, nonRepairable } = categorizeErrors(report.errors);
  let repaired = 0;
  let skipped = nonRepairable.length;
  let failed = 0;
  if (dryRun) {
    return {
      repaired: fileRepairs.length + gitOnlyRepairs.length,
      skipped,
      failed: 0
    };
  }
  if (fileRepairs.length > 0) {
    if (isInsideMicroWorktree) {
      for (const error of fileRepairs) {
        try {
          const result = await repairSingleErrorInWorktree(error, effectiveProjectRoot, effectiveProjectRoot);
          if (result.success && result.files) {
            repaired++;
          } else if (result.skipped) {
            skipped++;
            if (result.reason) {
              console.warn(`${LOG_PREFIX.REPAIR} Skipped ${error.type}: ${result.reason}`);
            }
          } else {
            failed++;
          }
        } catch (err) {
          const errMessage = err instanceof Error ? err.message : String(err);
          console.error(`${LOG_PREFIX.REPAIR} Failed to repair ${error.type}: ${errMessage}`);
          failed++;
        }
      }
    } else {
      try {
        const batchId = `batch-${fileRepairs.map((e) => e.wuId).join("-")}`.slice(0, 50);
        await withMicroWorktree({
          operation: "wu-repair",
          id: batchId,
          logPrefix: LOG_PREFIX.REPAIR,
          execute: async ({ worktreePath }) => {
            const filesModified = [];
            for (const error of fileRepairs) {
              try {
                const result = await repairSingleErrorInWorktree(error, worktreePath, worktreePath);
                if (result.success && result.files) {
                  filesModified.push(...result.files);
                  repaired++;
                } else if (result.skipped) {
                  skipped++;
                  if (result.reason) {
                    console.warn(`${LOG_PREFIX.REPAIR} Skipped ${error.type}: ${result.reason}`);
                  }
                } else {
                  failed++;
                }
              } catch (err) {
                const errMessage = err instanceof Error ? err.message : String(err);
                console.error(`${LOG_PREFIX.REPAIR} Failed to repair ${error.type}: ${errMessage}`);
                failed++;
              }
            }
            const uniqueFiles = [...new Set(filesModified)];
            return {
              commitMessage: `fix: repair ${repaired} WU inconsistencies`,
              files: uniqueFiles
            };
          }
        });
      } catch (err) {
        const errMessage = err instanceof Error ? err.message : String(err);
        console.error(`${LOG_PREFIX.REPAIR} Micro-worktree operation failed: ${errMessage}`);
        failed += fileRepairs.length - repaired;
      }
    }
  }
  for (const error of gitOnlyRepairs) {
    try {
      const result = await repairGitOnlyError(error, effectiveProjectRoot);
      if (result.success) {
        repaired++;
      } else if (result.skipped) {
        skipped++;
        if (result.reason) {
          console.warn(`${LOG_PREFIX.REPAIR} Skipped ${error.type}: ${result.reason}`);
        }
      } else {
        failed++;
      }
    } catch (err) {
      const errMessage = err instanceof Error ? err.message : String(err);
      console.error(`${LOG_PREFIX.REPAIR} Failed to repair ${error.type}: ${errMessage}`);
      failed++;
    }
  }
  return { repaired, skipped, failed };
}

export {
  checkWUConsistency,
  checkAllWUConsistency,
  checkLaneForOrphanDoneWU,
  repairWUInconsistency
};
