// src/lib/claudeMdTemplate.ts
import {
  readdirSync,
  readFileSync,
  statSync
} from "node:fs";
import { createRequire } from "node:module";
import PATH from "node:path";
var require2 = createRequire(import.meta.url);
var packageRoot = PATH.dirname(require2.resolve("@xylabs/toolchain/package.json"));
var templatesDir = PATH.resolve(packageRoot, "templates", "claude");
function applyPackageManager(content, pm) {
  const xyCommand = pm === "npm" ? "npm exec -- xy" : pm === "bun" ? "bun run xy" : `${pm} xy`;
  const addCommand = pm === "npm" ? "npm install" : pm === "bun" ? "bun add" : `${pm} add`;
  return content.replaceAll("yarn xy", () => xyCommand).replaceAll("pnpm xy", () => xyCommand).replaceAll("yarn add", () => addCommand).replaceAll("pnpm add", () => addCommand);
}
var XYLABS_COMMANDS_PREFIX = "xy-";
var LEGACY_COMMANDS_PREFIX = "xylabs-";
var claudeCommandTemplates = () => {
  const commandsDir = PATH.resolve(templatesDir, "commands");
  const files = readdirSync(commandsDir).filter((f) => f.startsWith(XYLABS_COMMANDS_PREFIX) && f.endsWith(".md"));
  const result = {};
  for (const file of files) {
    result[file] = readFileSync(PATH.resolve(commandsDir, file), "utf8");
  }
  return result;
};

// src/pm/workspaces.ts
import { existsSync, readFileSync as readFileSync2 } from "node:fs";
import PATH2 from "node:path";
import { globSync } from "glob";
function readJsonFile(path) {
  if (!existsSync(path)) return void 0;
  try {
    return JSON.parse(readFileSync2(path, "utf8"));
  } catch {
    return void 0;
  }
}
function readRootPackageJson(cwd = process.cwd()) {
  return readJsonFile(PATH2.resolve(cwd, "package.json"));
}
function detectPackageManagerFromPackageJson(cwd = process.cwd()) {
  const packageManager = readRootPackageJson(cwd)?.packageManager;
  if (!(packageManager != null && packageManager.length > 0)) return void 0;
  return packageManager.split("@", 1)[0];
}

// src/pm/detectPackageManager.ts
import { existsSync as existsSync2 } from "node:fs";
var knownPackageManagers = /* @__PURE__ */ new Set(["bun", "npm", "pnpm", "yarn"]);
function detectPackageManager() {
  const packageManager = detectPackageManagerFromPackageJson();
  if (packageManager != null && packageManager.length > 0 && knownPackageManagers.has(packageManager)) {
    return packageManager;
  }
  if (existsSync2("pnpm-lock.yaml") || existsSync2("pnpm-workspace.yaml")) return "pnpm";
  if (existsSync2("bun.lock") || existsSync2("bun.lockb")) return "bun";
  if (existsSync2("yarn.lock") || existsSync2(".yarnrc.yml")) return "yarn";
  if (existsSync2("package-lock.json") || existsSync2("npm-shrinkwrap.json")) return "npm";
  return "yarn";
}

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var jsonMode = false;
var originalStdoutWrite;
var envelopeEmitted = false;
var currentCommand = "unknown";
var startTime = 0;
function isJsonMode() {
  return jsonMode;
}
function setCurrentCommand(name) {
  currentCommand = name;
  startTime = performance.now();
  envelopeEmitted = false;
}
function emitJson(envelope) {
  if (envelopeEmitted) return;
  envelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (originalStdoutWrite) {
    originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance2.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance2.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

// src/actions/claude-commands.ts
import {
  existsSync as existsSync3,
  mkdirSync,
  readdirSync as readdirSync2,
  readFileSync as readFileSync3,
  unlinkSync,
  writeFileSync
} from "node:fs";
import PATH3 from "node:path";
import chalk from "chalk";
var syncCommandFiles = (commandsDir) => {
  const pm = detectPackageManager();
  const rawTemplates = claudeCommandTemplates();
  const templates = {};
  for (const [name, content] of Object.entries(rawTemplates)) {
    templates[name] = applyPackageManager(content, pm);
  }
  const templateNames = new Set(Object.keys(templates));
  let updated = 0;
  let created = 0;
  for (const [filename, content] of Object.entries(templates)) {
    const targetPath = PATH3.resolve(commandsDir, filename);
    const existing = existsSync3(targetPath) ? readFileSync3(targetPath, "utf8") : void 0;
    if (existing === content) continue;
    writeFileSync(targetPath, content, "utf8");
    if (existing != null && existing.length > 0) {
      updated++;
    } else {
      created++;
    }
  }
  return {
    created,
    templateNames,
    updated
  };
};
var removeStaleCommands = (commandsDir, templateNames) => {
  const existingCommands = readdirSync2(commandsDir).filter((f) => f.startsWith(XYLABS_COMMANDS_PREFIX) && f.endsWith(".md"));
  let removed = 0;
  for (const file of existingCommands) {
    if (!templateNames.has(file)) {
      unlinkSync(PATH3.resolve(commandsDir, file));
      removed++;
    }
  }
  return removed;
};
var removeLegacyCommands = (commandsDir) => {
  const legacyFiles = readdirSync2(commandsDir).filter((f) => f.startsWith(LEGACY_COMMANDS_PREFIX) && f.endsWith(".md"));
  for (const file of legacyFiles) {
    unlinkSync(PATH3.resolve(commandsDir, file));
  }
  return legacyFiles.length;
};
var logCommandsResult = (created, updated, removed) => {
  if (created || updated || removed) {
    const parts = [
      created ? `${created} created` : "",
      updated ? `${updated} updated` : "",
      removed ? `${removed} removed` : ""
    ].filter(Boolean);
    console.log(chalk.green(`.claude/commands/${XYLABS_COMMANDS_PREFIX}*.md: ${parts.join(", ")}`));
  } else {
    console.log(chalk.gray(`.claude/commands/${XYLABS_COMMANDS_PREFIX}*.md: already up to date`));
  }
};
var claudeCommands = () => {
  const cwd = INIT_CWD();
  const commandsDir = PATH3.resolve(cwd, ".claude", "commands");
  mkdirSync(commandsDir, { recursive: true });
  const legacy = removeLegacyCommands(commandsDir);
  const {
    created,
    templateNames,
    updated
  } = syncCommandFiles(commandsDir);
  const removed = removeStaleCommands(commandsDir, templateNames);
  logCommandsResult(created, updated, removed + legacy);
  return 0;
};

// src/xy/common/claude/commandsCommand.ts
var commandsCommand = {
  command: "commands",
  describe: "Sync XY Labs standard Claude slash commands to .claude/commands/",
  handler: async (argv) => {
    if (Boolean(argv.verbose)) console.log("Claude Commands");
    await withEnvelope("claude commands", () => claudeCommands());
  }
};
export {
  commandsCommand
};
//# sourceMappingURL=commandsCommand.mjs.map
