// Force strict mode and setup for ESM
"use strict";
import {
  msSinceLastInteraction
} from "./chunk-KW7NOTN6.js";
import {
  FILE_HISTORY_DIR,
  getSubagentsRootDir
} from "./chunk-QQOPXQYM.js";
import "./chunk-TWPJO254.js";
import "./chunk-H6XPXXMH.js";
import "./chunk-5M6IDOMF.js";
import "./chunk-UPUG4GXM.js";
import "./chunk-64LQLPL7.js";
import "./chunk-2LQTH543.js";
import "./chunk-KRXPRVGL.js";
import "./chunk-GNCIZTNJ.js";
import "./chunk-CVHIL5IG.js";
import "./chunk-IRH27ZC2.js";
import "./chunk-QHWCP53L.js";
import "./chunk-PONHVBRT.js";
import "./chunk-T26EAKDL.js";
import "./chunk-6PVPNMXU.js";
import "./chunk-CPBF7KYF.js";
import "./chunk-6QIGFD5W.js";
import "./chunk-XWWKIXVD.js";
import "./chunk-75GFAX4R.js";
import "./chunk-OKF7JF3R.js";
import "./chunk-JSD33JG6.js";
import "./chunk-S6LOFUVP.js";
import "./chunk-JCW2R7WC.js";
import "./chunk-2DN4J57Y.js";
import "./chunk-ZPJWUGCS.js";
import "./chunk-2LKVPASC.js";
import "./chunk-NAVJD2PQ.js";
import "./chunk-LW3RFMG7.js";
import "./chunk-W4MIWP6M.js";
import "./chunk-DGEIYUC3.js";
import "./chunk-MPHPFVKK.js";
import "./chunk-GLNBDYUX.js";
import "./chunk-DJ2GSRLV.js";
import "./chunk-6D2RWQMA.js";
import "./chunk-75MIQ3LV.js";
import "./chunk-2J3OJGTL.js";
import "./chunk-P3QQPMQA.js";
import "./chunk-RPLGZJV2.js";
import "./chunk-GLCZKT5V.js";
import "./chunk-DZLYR4U3.js";
import "./chunk-NKHOVMWF.js";
import "./chunk-VGC4I5JJ.js";
import "./chunk-SGFT55XI.js";
import "./chunk-Y4IHBGBP.js";
import "./chunk-Y6AXW2OG.js";
import "./chunk-2M3XQKPR.js";
import "./chunk-46UV252V.js";
import "./chunk-ZBVS26BY.js";
import "./chunk-WZRWHXFE.js";
import "./chunk-A3NDJ5SB.js";
import "./chunk-7XATOOE7.js";
import "./chunk-BGTQCTQW.js";
import "./chunk-W4RQUHY3.js";
import "./chunk-S7W2GKIO.js";
import {
  Storage,
  createDebugLogger
} from "./chunk-UHUSJ6X7.js";
import "./chunk-VOQXFAY5.js";
import "./chunk-75DOP5OR.js";
import "./chunk-DMTGGOSA.js";
import "./chunk-YQ3U5MUC.js";
import "./chunk-AMDSOFFV.js";
import "./chunk-QUGAUQGJ.js";
import {
  init_esbuild_shims
} from "./chunk-5O2XNYP6.js";
import {
  __name
} from "./chunk-J2S4EL5Y.js";

// packages/cli/src/utils/housekeeping/scheduler.ts
init_esbuild_shims();
import { stat as stat3 } from "node:fs/promises";
import { createHash } from "node:crypto";
import { join as join2 } from "node:path";

// packages/cli/src/utils/housekeeping/cleanup.ts
init_esbuild_shims();
import { readdir, stat, rm, rmdir } from "node:fs/promises";
import { join } from "node:path";
var debugLogger = createDebugLogger("HOUSEKEEPING");
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
var MS_PER_HOUR = 60 * 60 * 1e3;
var SWEEP_CONCURRENCY = 20;
function getCutoffDate(cleanupPeriodDays) {
  const periodMs = cleanupPeriodDays > 0 ? cleanupPeriodDays * MS_PER_DAY : MS_PER_HOUR;
  return new Date(Date.now() - periodMs);
}
__name(getCutoffDate, "getCutoffDate");
async function sweepOldSessionDirs(root, opts) {
  const result = { removed: 0, errors: 0 };
  const excludes = opts.excludeSessionIds ?? /* @__PURE__ */ new Set();
  let entries;
  try {
    entries = await readdir(root, { withFileTypes: true });
  } catch (e) {
    if (isENOENT(e)) return result;
    debugLogger.error("readdir failed", e);
    return result;
  }
  const sessionDirs = entries.filter((e) => e.isDirectory() && !excludes.has(e.name)).map((e) => join(root, e.name));
  for (let i = 0; i < sessionDirs.length; i += SWEEP_CONCURRENCY) {
    const batch = sessionDirs.slice(i, i + SWEEP_CONCURRENCY);
    await Promise.all(
      batch.map(async (dir) => {
        try {
          const s = await stat(dir);
          if (s.mtime < opts.cutoffDate) {
            await rm(dir, { recursive: true, force: true });
            result.removed++;
          }
        } catch (err) {
          result.errors++;
          debugLogger.error(`failed to sweep ${dir}`, err);
        }
      })
    );
  }
  if (opts.removeEmptyRoot !== false) {
    await rmdir(root).catch(() => {
    });
  }
  return result;
}
__name(sweepOldSessionDirs, "sweepOldSessionDirs");
async function cleanupOldFileHistoryBackups(opts) {
  return sweepOldSessionDirs(
    join(Storage.getGlobalQwenDir(), FILE_HISTORY_DIR),
    opts
  );
}
__name(cleanupOldFileHistoryBackups, "cleanupOldFileHistoryBackups");
async function cleanupOldSubagentTranscripts(opts) {
  return sweepOldSessionDirs(opts.subagentsRoot, {
    ...opts,
    removeEmptyRoot: false
  });
}
__name(cleanupOldSubagentTranscripts, "cleanupOldSubagentTranscripts");
function isENOENT(e) {
  return e?.code === "ENOENT";
}
__name(isENOENT, "isENOENT");

// packages/cli/src/utils/housekeeping/throttledOnce.ts
init_esbuild_shims();
import { mkdir, open, stat as stat2, unlink, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
var debugLogger2 = createDebugLogger("HOUSEKEEPING");
var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
var STALE_LOCK_MS = 60 * 60 * 1e3;
async function runThrottledOnce(opts, task) {
  const minIntervalMs = opts.minIntervalMs ?? ONE_DAY_MS;
  const staleLockMs = opts.staleLockMs ?? STALE_LOCK_MS;
  await mkdir(dirname(opts.lockPath), { recursive: true, mode: 448 }).catch(
    () => {
    }
  );
  if (await markerIsFresh(opts.markerPath, minIntervalMs, opts.name)) {
    return false;
  }
  let acquired = await tryAcquire(opts.lockPath);
  if (!acquired) {
    try {
      const s = await stat2(opts.lockPath);
      if (Date.now() - s.mtimeMs > staleLockMs) {
        await unlink(opts.lockPath).catch(() => {
        });
        acquired = await tryAcquire(opts.lockPath);
      }
    } catch {
      acquired = await tryAcquire(opts.lockPath);
    }
    if (!acquired) {
      debugLogger2.debug(`${opts.name}: skipping, lock held`);
      return false;
    }
  }
  try {
    if (await markerIsFresh(opts.markerPath, minIntervalMs, opts.name)) {
      return false;
    }
    let taskCompleted = false;
    try {
      await task();
      taskCompleted = true;
    } finally {
      if (taskCompleted) {
        try {
          await writeFile(opts.markerPath, (/* @__PURE__ */ new Date()).toISOString());
        } catch (err) {
          debugLogger2.debug(
            `${opts.name}: marker write failed (cleanup succeeded)`,
            err
          );
        }
      }
    }
    return taskCompleted;
  } finally {
    await unlink(opts.lockPath).catch(() => {
      debugLogger2.debug(`${opts.name}: lock unlink failed (harmless)`);
    });
  }
}
__name(runThrottledOnce, "runThrottledOnce");
async function markerIsFresh(markerPath, minIntervalMs, name) {
  try {
    const s = await stat2(markerPath);
    const age = Date.now() - s.mtimeMs;
    if (age < minIntervalMs) {
      debugLogger2.debug(`${name}: skipping, ran ${age}ms ago`);
      return true;
    }
  } catch {
  }
  return false;
}
__name(markerIsFresh, "markerIsFresh");
async function tryAcquire(lockPath) {
  try {
    const fh = await open(lockPath, "wx");
    await fh.close();
    return true;
  } catch (e) {
    if (e?.code === "EEXIST") {
      return false;
    }
    throw e;
  }
}
__name(tryAcquire, "tryAcquire");

// packages/cli/src/utils/housekeeping/scheduler.ts
var debugLogger3 = createDebugLogger("HOUSEKEEPING");
var STARTUP_DELAY_MS = 10 * 60 * 1e3;
var RECURRING_INTERVAL_MS = 24 * 60 * 60 * 1e3;
var RECENT_INTERACTION_MS = 60 * 1e3;
var CATCHUP_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1e3;
var STARTUP_DELAY_CATCHUP_MS = 60 * 1e3;
var FILE_HISTORY_MARKER = ".file-history-cleanup";
var SUBAGENT_MARKER = ".subagent-cleanup";
var started = false;
function startBackgroundHousekeeping(config, settings) {
  if (started) return;
  started = true;
  void scheduleFirstPass(config, settings).catch((err) => {
    started = false;
    debugLogger3.error(
      "scheduleFirstPass failed; chain will retry on next start",
      err
    );
  });
}
__name(startBackgroundHousekeeping, "startBackgroundHousekeeping");
async function scheduleFirstPass(config, settings) {
  const markerPath = join2(Storage.getGlobalQwenDir(), FILE_HISTORY_MARKER);
  const delay = await needsCatchUp(markerPath) ? STARTUP_DELAY_CATCHUP_MS : STARTUP_DELAY_MS;
  debugLogger3.debug(`first pass in ${delay / 1e3}s`);
  setTimeout(() => scheduleNextPass(config, settings), delay).unref();
}
__name(scheduleFirstPass, "scheduleFirstPass");
async function needsCatchUp(markerPath) {
  try {
    const s = await stat3(markerPath);
    return Date.now() - s.mtimeMs > CATCHUP_THRESHOLD_MS;
  } catch {
    return true;
  }
}
__name(needsCatchUp, "needsCatchUp");
function getSubagentMarkerPath(qwenDir, projectDir) {
  const projectKey = createHash("sha256").update(projectDir).digest("hex").slice(0, 16);
  return join2(qwenDir, `${SUBAGENT_MARKER}-${projectKey}`);
}
__name(getSubagentMarkerPath, "getSubagentMarkerPath");
async function runPass(config, settings) {
  if (msSinceLastInteraction() < RECENT_INTERACTION_MS) {
    debugLogger3.debug("user active, deferring 10 min");
    setTimeout(
      () => scheduleNextPass(config, settings),
      STARTUP_DELAY_MS
    ).unref();
    return;
  }
  try {
    await runHousekeeping(config, settings);
  } catch (err) {
    debugLogger3.error("housekeeping pass failed; will retry next cycle", err);
  }
  setTimeout(
    () => scheduleNextPass(config, settings),
    RECURRING_INTERVAL_MS
  ).unref();
}
__name(runPass, "runPass");
function scheduleNextPass(config, settings) {
  void runPass(config, settings).catch((err) => {
    debugLogger3.error("runPass rejected unexpectedly", err);
  });
}
__name(scheduleNextPass, "scheduleNextPass");
async function runHousekeeping(config, settings) {
  const days = settings.merged.general?.cleanupPeriodDays ?? 30;
  const cutoff = getCutoffDate(days);
  const currentSessionId = config.getSessionId();
  const qwenDir = Storage.getGlobalQwenDir();
  await runThrottledOnce(
    {
      name: "file-history-cleanup",
      markerPath: join2(qwenDir, FILE_HISTORY_MARKER),
      lockPath: join2(qwenDir, FILE_HISTORY_MARKER + ".lock")
    },
    async () => {
      const r = await cleanupOldFileHistoryBackups({
        cutoffDate: cutoff,
        excludeSessionIds: /* @__PURE__ */ new Set([currentSessionId])
      });
      debugLogger3.debug(
        `file-history: removed=${r.removed} errors=${r.errors}`
      );
    }
  );
  const projectDir = config.storage?.getProjectDir?.();
  if (projectDir) {
    const markerPath = getSubagentMarkerPath(qwenDir, projectDir);
    await runThrottledOnce(
      {
        name: "subagent-cleanup",
        markerPath,
        lockPath: markerPath + ".lock"
      },
      async () => {
        const r = await cleanupOldSubagentTranscripts({
          cutoffDate: cutoff,
          excludeSessionIds: /* @__PURE__ */ new Set([currentSessionId]),
          subagentsRoot: getSubagentsRootDir(projectDir)
        });
        debugLogger3.debug(`subagents: removed=${r.removed} errors=${r.errors}`);
      }
    );
  }
}
__name(runHousekeeping, "runHousekeeping");
function _resetForTesting() {
  started = false;
}
__name(_resetForTesting, "_resetForTesting");
var _needsCatchUpForTesting = needsCatchUp;
var _runHousekeepingForTesting = runHousekeeping;
var _runPassForTesting = runPass;
var _FILE_HISTORY_MARKER_FOR_TESTING = FILE_HISTORY_MARKER;
var _getSubagentMarkerPathForTesting = getSubagentMarkerPath;
export {
  _FILE_HISTORY_MARKER_FOR_TESTING,
  _getSubagentMarkerPathForTesting,
  _needsCatchUpForTesting,
  _resetForTesting,
  _runHousekeepingForTesting,
  _runPassForTesting,
  startBackgroundHousekeeping
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
