// 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_RULES_PREFIX = "xylabs-";
var XYLABS_COMMANDS_PREFIX = "xy-";
var LEGACY_COMMANDS_PREFIX = "xylabs-";
var XYLABS_SKILLS_PREFIX = "xylabs-";
var claudeMdRuleTemplates = () => {
  const rulesDir = PATH.resolve(templatesDir, "rules");
  const files = readdirSync(rulesDir).filter((f) => f.startsWith(XYLABS_RULES_PREFIX) && f.endsWith(".md"));
  const result = {};
  for (const file of files) {
    result[file] = readFileSync(PATH.resolve(rulesDir, file), "utf8");
  }
  return result;
};
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;
};
var claudeSkillTemplates = () => {
  const skillsDir = PATH.resolve(templatesDir, "skills");
  const dirs = readdirSync(skillsDir).filter(
    (f) => f.startsWith(XYLABS_SKILLS_PREFIX) && statSync(PATH.resolve(skillsDir, f)).isDirectory()
  );
  const result = {};
  for (const dir of dirs) {
    const dirPath = PATH.resolve(skillsDir, dir);
    const files = readdirSync(dirPath, { recursive: true, encoding: "utf8" });
    result[dir] = {};
    for (const file of files) {
      if (statSync(PATH.resolve(dirPath, file)).isFile()) {
        result[dir][file] = readFileSync(PATH.resolve(dirPath, file), "utf8");
      }
    }
  }
  return result;
};
var claudeMdLocalTemplate = () => readFileSync(PATH.resolve(templatesDir, "CLAUDE-local.md"), "utf8");

// src/lib/crossSpawn.ts
import crossSpawn from "cross-spawn";
function spawnSync(command, args, options) {
  return crossSpawn.sync(command, args, options);
}

// 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/actions/claude-rules.ts
import {
  existsSync as existsSync4,
  mkdirSync as mkdirSync2,
  readdirSync as readdirSync3,
  readFileSync as readFileSync4,
  unlinkSync as unlinkSync2,
  writeFileSync as writeFileSync2
} from "node:fs";
import PATH4 from "node:path";
import chalk2 from "chalk";
var syncRuleFiles = (rulesDir) => {
  const pm = detectPackageManager();
  const rawTemplates = claudeMdRuleTemplates();
  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 = PATH4.resolve(rulesDir, filename);
    const existing = existsSync4(targetPath) ? readFileSync4(targetPath, "utf8") : void 0;
    if (existing === content) continue;
    writeFileSync2(targetPath, content, "utf8");
    if (existing != null && existing.length > 0) {
      updated++;
    } else {
      created++;
    }
  }
  return {
    created,
    templateNames,
    updated
  };
};
var removeStaleRules = (rulesDir, templateNames) => {
  const existingRules = readdirSync3(rulesDir).filter((f) => f.startsWith(XYLABS_RULES_PREFIX) && f.endsWith(".md"));
  let removed = 0;
  for (const file of existingRules) {
    if (!templateNames.has(file)) {
      unlinkSync2(PATH4.resolve(rulesDir, file));
      removed++;
    }
  }
  return removed;
};
var logRulesResult = (created, updated, removed) => {
  if (created || updated || removed) {
    const parts = [
      created ? `${created} created` : "",
      updated ? `${updated} updated` : "",
      removed ? `${removed} removed` : ""
    ].filter(Boolean);
    console.log(chalk2.green(`.claude/rules/${XYLABS_RULES_PREFIX}*.md: ${parts.join(", ")}`));
  } else {
    console.log(chalk2.gray(`.claude/rules/${XYLABS_RULES_PREFIX}*.md: already up to date`));
  }
};
var ensureProjectClaudeMd = (cwd, force) => {
  const projectPath = PATH4.resolve(cwd, "CLAUDE.md");
  if (!existsSync4(projectPath) || (force ?? false)) {
    if ((force ?? false) && existsSync4(projectPath)) {
      console.log(chalk2.yellow("Regenerating CLAUDE.md"));
    }
    console.log(chalk2.green("Generating CLAUDE.md via claude /init..."));
    const result = spawnSync("claude", ["-p", "/init", "--allowedTools", "Read", "Write", "Glob", "Grep"], {
      cwd,
      stdio: "inherit"
    });
    if (result.status !== 0) {
      console.error(chalk2.red("claude /init failed \u2014 is Claude Code installed?"));
      return 1;
    }
  } else {
    console.log(chalk2.gray("CLAUDE.md already exists (skipped, use --force to regenerate)"));
  }
  return 0;
};
var ensureLocalClaudeMd = (cwd) => {
  const localPath = PATH4.resolve(cwd, "CLAUDE.local.md");
  if (existsSync4(localPath)) {
    console.log(chalk2.gray("CLAUDE.local.md already exists (skipped)"));
  } else {
    writeFileSync2(localPath, claudeMdLocalTemplate(), "utf8");
    console.log(chalk2.green("Generated CLAUDE.local.md"));
  }
};
var claudeRules = ({ force } = {}) => {
  const cwd = INIT_CWD();
  const rulesDir = PATH4.resolve(cwd, ".claude", "rules");
  mkdirSync2(rulesDir, { recursive: true });
  const {
    created,
    templateNames,
    updated
  } = syncRuleFiles(rulesDir);
  const removed = removeStaleRules(rulesDir, templateNames);
  logRulesResult(created, updated, removed);
  const claudeMdResult = ensureProjectClaudeMd(cwd, force);
  ensureLocalClaudeMd(cwd);
  return claudeMdResult ?? 0;
};

// src/actions/claude-settings.ts
import {
  existsSync as existsSync5,
  mkdirSync as mkdirSync3,
  writeFileSync as writeFileSync3
} from "node:fs";
import PATH5 from "node:path";
import { createInterface } from "node:readline";
import chalk3 from "chalk";
var DENY_LIST = [
  "Bash(git push --force *)",
  "Bash(git reset --hard *)",
  "Bash(rm -rf /*)"
];
var RESTRICTIVE_ALLOW = [
  "Bash(git *)",
  "Bash(yarn *)",
  "Bash(pnpm *)",
  "Bash(npx *)",
  "Bash(ls *)",
  "Bash(mkdir *)",
  "Bash(cp *)",
  "Bash(mv *)",
  "Bash(rm *)",
  "Bash(cat *)",
  "Bash(head *)",
  "Bash(tail *)",
  "Bash(echo *)",
  "Bash(pwd)",
  "Bash(which *)",
  "Bash(grep *)",
  "Bash(find *)",
  "Bash(wc *)",
  "Bash(npm view *)",
  "Bash(gh *)",
  "Read",
  "Edit",
  "Write",
  "Glob",
  "Grep",
  "Skill"
];
var PERMISSIVE_ALLOW = [
  ...RESTRICTIVE_ALLOW,
  "Bash(node *)",
  "Bash(python3 *)",
  "Bash(claude *)",
  "Bash(sed *)",
  "Bash(xargs *)",
  "Bash(tee *)"
];
function buildSettings(level) {
  return {
    permissions: {
      allow: level === "restrictive" ? RESTRICTIVE_ALLOW : PERMISSIVE_ALLOW,
      deny: DENY_LIST
    }
  };
}
function askConfirmation(question) {
  const rl = createInterface({ input: process.stdin, output: process.stdout });
  return new Promise((resolve) => {
    rl.question(question, (answer) => {
      rl.close();
      resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
    });
  });
}
async function claudeSettings({ level = "permissive" } = {}) {
  const cwd = INIT_CWD();
  const claudeDir = PATH5.resolve(cwd, ".claude");
  const settingsPath = PATH5.resolve(claudeDir, "settings.local.json");
  mkdirSync3(claudeDir, { recursive: true });
  if (existsSync5(settingsPath)) {
    const confirmed = await askConfirmation(
      chalk3.yellow(`${settingsPath} already exists. Replace it? (y/N) `)
    );
    if (!confirmed) {
      console.log(chalk3.gray("Skipped \u2014 existing settings.local.json preserved"));
      return 0;
    }
  }
  const settings = buildSettings(level);
  writeFileSync3(settingsPath, `${JSON.stringify(settings, null, 2)}
`, "utf8");
  console.log(chalk3.green(`Generated .claude/settings.local.json (${level})`));
  return 0;
}

// src/actions/claude-skills.ts
import {
  existsSync as existsSync6,
  mkdirSync as mkdirSync4,
  readdirSync as readdirSync4,
  readFileSync as readFileSync5,
  rmSync,
  statSync as statSync2,
  writeFileSync as writeFileSync4
} from "node:fs";
import PATH6 from "node:path";
import chalk4 from "chalk";
function writeSkillFile(skillDir, filename, rawContent, pm) {
  const content = applyPackageManager(rawContent, pm);
  const targetPath = PATH6.resolve(skillDir, filename);
  mkdirSync4(PATH6.dirname(targetPath), { recursive: true });
  const existing = existsSync6(targetPath) ? readFileSync5(targetPath, "utf8") : void 0;
  if (existing === content) return "unchanged";
  writeFileSync4(targetPath, content, "utf8");
  return existing != null && existing.length > 0 ? "updated" : "created";
}
var syncSkillFiles = (skillsDir) => {
  const pm = detectPackageManager();
  const rawTemplates = claudeSkillTemplates();
  const templateNames = new Set(Object.keys(rawTemplates));
  let updated = 0;
  let created = 0;
  for (const [skillName, files] of Object.entries(rawTemplates)) {
    const skillDir = PATH6.resolve(skillsDir, skillName);
    mkdirSync4(skillDir, { recursive: true });
    for (const [filename, rawContent] of Object.entries(files)) {
      const result = writeSkillFile(skillDir, filename, rawContent, pm);
      if (result === "updated") {
        updated++;
      } else if (result === "created") {
        created++;
      }
    }
  }
  return {
    created,
    templateNames,
    updated
  };
};
var removeStaleSkills = (skillsDir, templateNames) => {
  const existingSkills = readdirSync4(skillsDir).filter(
    (f) => f.startsWith(XYLABS_SKILLS_PREFIX) && statSync2(PATH6.resolve(skillsDir, f)).isDirectory()
  );
  let removed = 0;
  for (const dir of existingSkills) {
    if (!templateNames.has(dir)) {
      rmSync(PATH6.resolve(skillsDir, dir), { recursive: true });
      removed++;
    }
  }
  return removed;
};
var logSkillsResult = (created, updated, removed) => {
  if (created || updated || removed) {
    const parts = [
      created ? `${created} created` : "",
      updated ? `${updated} updated` : "",
      removed ? `${removed} removed` : ""
    ].filter(Boolean);
    console.log(chalk4.green(`.claude/skills/${XYLABS_SKILLS_PREFIX}*/: ${parts.join(", ")}`));
  } else {
    console.log(chalk4.gray(`.claude/skills/${XYLABS_SKILLS_PREFIX}*/: already up to date`));
  }
};
var claudeSkills = () => {
  const cwd = INIT_CWD();
  const skillsDir = PATH6.resolve(cwd, ".claude", "skills");
  mkdirSync4(skillsDir, { recursive: true });
  const {
    created,
    templateNames,
    updated
  } = syncSkillFiles(skillsDir);
  const removed = removeStaleSkills(skillsDir, templateNames);
  logSkillsResult(created, updated, removed);
  return 0;
};

// src/xy/common/claude/initCommand.ts
var initCommand = {
  builder: (yargs) => {
    return yargs.option("force", {
      alias: "f",
      default: false,
      description: "Overwrite existing CLAUDE.md",
      type: "boolean"
    }).option("level", {
      choices: ["restrictive", "permissive"],
      default: "permissive",
      description: "Permission level for settings (restrictive omits node, python3, claude, sed, xargs, tee)",
      type: "string"
    });
  },
  command: "init",
  describe: "Initialize all Claude configuration (commands, rules, skills, settings)",
  handler: async (argv) => {
    if (Boolean(argv.verbose)) console.log("Claude Init");
    await withEnvelope("claude init", async () => {
      const commandsResult = claudeCommands();
      const rulesResult = claudeRules({ force: argv.force });
      const skillsResult = claudeSkills();
      const settingsResult = await claudeSettings({ level: argv.level });
      return commandsResult || rulesResult || skillsResult || settingsResult;
    });
  }
};
export {
  initCommand
};
//# sourceMappingURL=initCommand.mjs.map
