import {
  integrateClaudeCode
} from "./chunk-5GTOXFYR.js";
import {
  generateSessionStartRecoveryScript
} from "./chunk-EA3IVO64.js";
import {
  CANONICAL_BOOTSTRAP_COMMAND,
  DEFAULT_PROJECT_NAME,
  WORKSPACE_FILENAME,
  getDefaultWorkspaceConfig
} from "./chunk-WOCTQ5MS.js";
import {
  createDirectory,
  createExecutableScript,
  createFile,
  loadTemplate,
  processTemplate
} from "./chunk-HEVS5YLD.js";
import {
  AGENTS_MD_TEMPLATE,
  AIDER_CONF_TEMPLATE,
  BACKLOG_TEMPLATE,
  CLAUDE_MD_TEMPLATE,
  CLAUDE_SETTINGS_TEMPLATE,
  CLINE_RULES_TEMPLATE,
  CURSOR_RULES_TEMPLATE,
  DEFAULT_LANE_DEFINITIONS,
  FRAMEWORK_HINT_TEMPLATE,
  FRAMEWORK_OVERLAY_TEMPLATE,
  GATE_STUB_SCRIPTS,
  GITIGNORE_TEMPLATE,
  LANE_LIFECYCLE_STATUS,
  LUMENFLOW_GATES_SKILL_TEMPLATE,
  MCP_JSON_TEMPLATE,
  PRETTIERIGNORE_TEMPLATE,
  PRE_COMMIT_TEMPLATE,
  REQUIRED_GITIGNORE_EXCLUSIONS,
  SAFE_GIT_TEMPLATE,
  SCRIPT_ARG_OVERRIDES,
  STATUS_TEMPLATE,
  WINDSURF_RULES_TEMPLATE,
  WORKTREE_DISCIPLINE_SKILL_TEMPLATE,
  WU_LIFECYCLE_SKILL_TEMPLATE,
  WU_TEMPLATE_YAML,
  buildInitLaneLifecycleMessage
} from "./chunk-67XVPMRY.js";
import {
  getPublicManifest
} from "./chunk-KY4PGL5V.js";
import {
  SCAFFOLDED_ONBOARDING_TEMPLATE_PATHS
} from "./chunk-FBKAPTJ2.js";
import {
  isInWorktree,
  isMainBranch
} from "./chunk-E3REJTAJ.js";
import {
  runDoctorForInit
} from "./chunk-ZF747T3O.js";
import {
  WU_OPTIONS,
  createWUParser,
  runCLI
} from "./chunk-2GXVIN57.js";
import {
  CLAUDE_HOOKS,
  ENV_VARS
} from "./chunk-DWMLTXKQ.js";
import {
  GATE_PRESETS,
  GIT_DIRECTORY_NAME,
  LUMENFLOW_CLIENT_IDS,
  WORKSPACE_V2_KEYS,
  getDefaultConfig,
  getDocsLayoutPreset
} from "./chunk-V6OJGLBA.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// src/init.ts
import * as fs2 from "fs";
import * as path2 from "path";
import * as yaml from "yaml";
import { execFileSync as execFileSync2 } from "child_process";

// src/init-detection.ts
import * as fs from "fs";
import * as path from "path";
import { execFileSync } from "child_process";
var DEFAULT_CLIENT_CLAUDE = LUMENFLOW_CLIENT_IDS.CLAUDE_CODE;
function detectIDEEnvironment() {
  if (process.env[ENV_VARS.CLAUDE_PROJECT_DIR] || process.env[ENV_VARS.CLAUDE_CODE]) {
    return "claude";
  }
  const cursorVars = Object.keys(process.env).filter((key) => key.startsWith("CURSOR_"));
  if (cursorVars.length > 0) {
    return "cursor";
  }
  const windsurfVars = Object.keys(process.env).filter((key) => key.startsWith("WINDSURF_"));
  if (windsurfVars.length > 0) {
    return "windsurf";
  }
  const vscodeVars = Object.keys(process.env).filter((key) => key.startsWith("VSCODE_"));
  if (vscodeVars.length > 0) {
    return "vscode";
  }
  return void 0;
}
function getCommandVersion(command, args) {
  try {
    const output = execFileSync(command, args, {
      encoding: "utf-8",
      stdio: ["pipe", "pipe", "pipe"]
    }).trim();
    return output;
  } catch {
    return "not found";
  }
}
function parseVersion(versionStr) {
  const match = /(\d+)\.(\d+)(?:\.(\d+))?/.exec(versionStr);
  if (!match) {
    return [0, 0, 0];
  }
  return [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3] || "0", 10)];
}
function compareVersions(actual, required) {
  const actualParts = parseVersion(actual);
  const requiredParts = parseVersion(required);
  for (let i = 0; i < 3; i++) {
    if (actualParts[i] > requiredParts[i]) {
      return true;
    }
    if (actualParts[i] < requiredParts[i]) {
      return false;
    }
  }
  return true;
}
function checkPrerequisites() {
  const nodeVersion = getCommandVersion("node", ["--version"]);
  const pnpmVersion = getCommandVersion("pnpm", ["--version"]);
  const gitVersion = getCommandVersion("git", ["--version"]);
  const requiredNode = "22.0.0";
  const requiredPnpm = "9.0.0";
  const requiredGit = "2.0.0";
  const nodeOk = nodeVersion !== "not found" && compareVersions(nodeVersion, requiredNode);
  const pnpmOk = pnpmVersion !== "not found" && compareVersions(pnpmVersion, requiredPnpm);
  const gitOk = gitVersion !== "not found" && compareVersions(gitVersion, requiredGit);
  return {
    node: {
      passed: nodeOk,
      version: nodeVersion,
      required: `>=${requiredNode}`,
      message: nodeOk ? void 0 : `Node.js ${requiredNode}+ required`
    },
    pnpm: {
      passed: pnpmOk,
      version: pnpmVersion,
      required: `>=${requiredPnpm}`,
      message: pnpmOk ? void 0 : `pnpm ${requiredPnpm}+ required`
    },
    git: {
      passed: gitOk,
      version: gitVersion,
      required: `>=${requiredGit}`,
      message: gitOk ? void 0 : `Git ${requiredGit}+ required`
    }
  };
}
function getDocsPath(structure) {
  return getDocsLayoutPreset(structure);
}
function detectDocsStructure(targetDir) {
  const docsDir = path.join(targetDir, "docs");
  if (!fs.existsSync(docsDir)) {
    return "simple";
  }
  const entries = fs.readdirSync(docsDir);
  const hasNumberedDir = entries.some((entry) => /^\d{2}-/.test(entry));
  if (hasNumberedDir) {
    return "arc42";
  }
  return "simple";
}
function detectDefaultClient() {
  if (process.env[ENV_VARS.CLAUDE_PROJECT_DIR] || process.env[ENV_VARS.CLAUDE_CODE]) {
    return DEFAULT_CLIENT_CLAUDE;
  }
  return "none";
}
function isGitRepo(targetDir) {
  try {
    execFileSync("git", ["rev-parse", "--git-dir"], {
      cwd: targetDir,
      stdio: "pipe"
    });
    return true;
  } catch {
    return false;
  }
}
function hasGitCommits(targetDir) {
  try {
    execFileSync("git", ["rev-parse", "HEAD"], {
      cwd: targetDir,
      stdio: "pipe"
    });
    return true;
  } catch {
    return false;
  }
}
function hasOriginRemote(targetDir) {
  try {
    const result = execFileSync("git", ["remote", "get-url", "origin"], {
      cwd: targetDir,
      encoding: "utf-8",
      stdio: "pipe"
    });
    return result.trim().length > 0;
  } catch {
    return false;
  }
}
function detectGitStateConfig(targetDir) {
  if (!isGitRepo(targetDir)) {
    return { requireRemote: false };
  }
  if (!hasOriginRemote(targetDir)) {
    return { requireRemote: false };
  }
  return null;
}

// src/init.ts
var INIT_OPTIONS = {
  full: {
    name: "full",
    flags: "--full",
    description: "Add docs + agent onboarding + task scaffolding (default: true)"
  },
  minimal: {
    name: "minimal",
    flags: "--minimal",
    description: "Skip agent onboarding docs (only core files)"
  },
  framework: {
    name: "framework",
    flags: "--framework <name>",
    description: "Add framework hint + overlay docs"
  },
  // WU-1171: --client is the new primary flag (wu:spawn vocabulary)
  client: {
    name: "client",
    flags: "--client <type>",
    description: "Client type (claude, cursor, windsurf, codex, all, none)"
  },
  // WU-1171: --vendor kept as backward-compatible alias
  vendor: {
    name: "vendor",
    flags: "--vendor <type>",
    description: "Alias for --client (deprecated)"
  },
  // WU-1171: --merge mode for safe insertion into existing files
  merge: {
    name: "merge",
    flags: "--merge",
    description: "Merge LumenFlow config into existing files using bounded markers"
  },
  preset: {
    name: "preset",
    flags: "--preset <preset>",
    description: "Gate preset for config (node, python, go, rust, dotnet)"
  },
  bootstrapDomain: {
    name: "bootstrapDomain",
    flags: "--bootstrap-domain <domain>",
    description: "Bootstrap domain: software-delivery, infra, or custom"
  },
  skipBootstrap: {
    name: "skipBootstrap",
    flags: "--skip-bootstrap",
    description: "Skip workspace bootstrap-all flow (workspace.yaml + pack install)"
  },
  skipBootstrapPackInstall: {
    name: "skipBootstrapPackInstall",
    flags: "--skip-bootstrap-pack-install",
    description: "Skip registry pack install during bootstrap"
  },
  force: WU_OPTIONS.force
};
function parseBootstrapDomain(rawDomain) {
  if (!rawDomain) {
    return BOOTSTRAP_DEFAULT_DOMAIN;
  }
  if (BOOTSTRAP_VALID_DOMAINS.has(rawDomain)) {
    return rawDomain;
  }
  const validDomains = Array.from(BOOTSTRAP_VALID_DOMAINS).join(", ");
  throw createError(
    ErrorCodes.INVALID_ARGUMENT,
    `${BOOTSTRAP_ERROR_PREFIX} Invalid --bootstrap-domain "${rawDomain}". Valid values: ${validDomains}`
  );
}
function parseInitOptions() {
  const opts = createWUParser({
    name: "lumenflow-init",
    description: "Initialize LumenFlow in a project\n\nSubcommands:\n  lumenflow commands         List all available CLI commands\n  lumenflow cloud connect    Configure cloud control-plane access",
    options: Object.values(INIT_OPTIONS)
  });
  const clientValue = opts.client || opts.vendor;
  const fullMode = opts.minimal ? false : opts.full ?? true;
  const bootstrapDomain = parseBootstrapDomain(opts.bootstrapDomain);
  return {
    force: opts.force ?? false,
    full: fullMode,
    merge: opts.merge ?? false,
    framework: opts.framework,
    client: clientValue,
    vendor: clientValue,
    preset: opts.preset,
    bootstrapDomain,
    skipBootstrap: Boolean(opts.skipBootstrap),
    skipBootstrapPackInstall: Boolean(opts.skipBootstrapPackInstall)
  };
}
var DEFAULT_CLIENT_CLAUDE2 = LUMENFLOW_CLIENT_IDS.CLAUDE_CODE;
var BOOTSTRAP_DEFAULT_DOMAIN = "software-delivery";
var BOOTSTRAP_INFRA_DOMAIN = "infra";
var BOOTSTRAP_CUSTOM_DOMAIN = "custom";
var BOOTSTRAP_VALID_DOMAINS = /* @__PURE__ */ new Set([
  BOOTSTRAP_DEFAULT_DOMAIN,
  BOOTSTRAP_INFRA_DOMAIN,
  BOOTSTRAP_CUSTOM_DOMAIN
]);
var BOOTSTRAP_SKIP_REASON_FLAG = "--skip-bootstrap";
var BOOTSTRAP_SKIP_REASON_EXISTING_WORKSPACE = `${WORKSPACE_FILENAME} already exists`;
var BOOTSTRAP_ERROR_PREFIX = "[lumenflow bootstrap]";
var INIT_SUBCOMMANDS = {
  COMMANDS: "commands",
  CLOUD: "cloud"
};
var LEGACY_SUBCOMMANDS = {
  ONBOARD: "onboard",
  WORKSPACE_INIT_COLON: "workspace:init",
  WORKSPACE_INIT_DASH: "workspace-init"
};
var CLOUD_SUBCOMMANDS = {
  CONNECT: "connect"
};
var CLOUD_CONNECT_BIN = "cloud-connect";
var INIT_ERROR_PREFIX = "[lumenflow init]";
var INIT_CLOUD_CONNECT_HELP = "Usage: lumenflow cloud connect --endpoint <url> --org-id <id> --project-id <id> [--token-env <name>]";
var LEGACY_SUBCOMMAND_ERROR_PREFIX = `${INIT_ERROR_PREFIX} Legacy onboarding subcommand`;
var LEGACY_SUBCOMMAND_GUIDANCE = `Use "${CANONICAL_BOOTSTRAP_COMMAND}" for bootstrap-all onboarding`;
var LEGACY_SUBCOMMAND_HELP_HINT = `Run "${CANONICAL_BOOTSTRAP_COMMAND} --help" for supported options`;
var CONFIG_FILE_NAME = WORKSPACE_FILENAME;
var SOFTWARE_DELIVERY_KEY = WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY;
var SOFTWARE_DELIVERY_CONFIG_KEYS = {
  AGENTS: "agents",
  CLIENTS: "clients",
  ENFORCEMENT: "enforcement"
};
var FRAMEWORK_HINT_FILE = ".lumenflow.framework.yaml";
var LUMENFLOW_DIR = ".lumenflow";
var LUMENFLOW_AGENTS_DIR = `${LUMENFLOW_DIR}/agents`;
var CLAUDE_DIR = ".claude";
var CLAUDE_AGENTS_DIR = path2.join(CLAUDE_DIR, "agents");
async function checkBranchGuard(targetDir, result) {
  result.warnings = result.warnings ?? [];
  const gitDir = path2.join(targetDir, GIT_DIRECTORY_NAME);
  if (!fs2.existsSync(gitDir)) {
    return;
  }
  if (isInWorktree({ cwd: targetDir })) {
    return;
  }
  try {
    const onMain = await isMainBranch();
    if (onMain) {
      result.warnings.push(
        "Running init on main branch in main checkout. Consider using a worktree for changes to tracked files."
      );
    }
  } catch {
  }
}
function detectProjectTooling(targetDir) {
  const packageJsonPath = path2.join(targetDir, "package.json");
  if (!fs2.existsSync(packageJsonPath)) {
    return { hasTurbo: false };
  }
  try {
    const content = fs2.readFileSync(packageJsonPath, "utf-8");
    const pkg = JSON.parse(content);
    const deps = pkg.dependencies ?? {};
    const devDeps = pkg.devDependencies ?? {};
    const allDeps = { ...deps, ...devDeps };
    let testRunner;
    if ("vitest" in allDeps) {
      testRunner = "vitest";
    } else if ("jest" in allDeps) {
      testRunner = "jest";
    } else if ("mocha" in allDeps) {
      testRunner = "mocha";
    }
    const hasTurbo = "turbo" in allDeps;
    let packageManager;
    const pkgManager = pkg.packageManager;
    if (pkgManager?.startsWith("pnpm")) {
      packageManager = "pnpm";
    } else if (pkgManager?.startsWith("yarn")) {
      packageManager = "yarn";
    } else if (pkgManager?.startsWith("bun")) {
      packageManager = "bun";
    } else if (pkgManager?.startsWith("npm")) {
      packageManager = "npm";
    }
    return { testRunner, hasTurbo, packageManager };
  } catch {
    return { hasTurbo: false };
  }
}
function asRecord(value) {
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
}
function mergeConfigDefaults(defaults, existing) {
  const merged = { ...defaults };
  for (const [key, existingValue] of Object.entries(existing)) {
    const defaultValue = merged[key];
    const existingRecord = asRecord(existingValue);
    const defaultRecord = asRecord(defaultValue);
    if (defaultRecord && existingRecord) {
      merged[key] = mergeConfigDefaults(defaultRecord, existingRecord);
      continue;
    }
    merged[key] = existingValue;
  }
  return merged;
}
function toWorkspaceId(value) {
  return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
}
function loadWorkspaceDocument(targetDir) {
  const workspacePath = path2.join(targetDir, CONFIG_FILE_NAME);
  if (!fs2.existsSync(workspacePath)) {
    const projectName = resolveBootstrapProjectName(targetDir);
    const projectId = toWorkspaceId(projectName);
    const workspace2 = {
      ...getDefaultWorkspaceConfig(),
      id: projectId,
      name: projectName,
      memory_namespace: projectId,
      event_namespace: projectId
    };
    return { exists: false, workspace: workspace2 };
  }
  const content = fs2.readFileSync(workspacePath, "utf-8");
  const workspace = asRecord(yaml.parse(content));
  if (!workspace) {
    throw createError(
      ErrorCodes.WORKSPACE_MALFORMED,
      `${INIT_ERROR_PREFIX} ${CONFIG_FILE_NAME} exists but is not a valid YAML object. Fix ${CONFIG_FILE_NAME} and re-run init.`
    );
  }
  return { exists: true, workspace };
}
function upsertWorkspaceSoftwareDelivery(targetDir, softwareDeliveryConfig, result) {
  const workspacePath = path2.join(targetDir, CONFIG_FILE_NAME);
  const { exists, workspace } = loadWorkspaceDocument(targetDir);
  const existingSoftwareDelivery = asRecord(workspace[SOFTWARE_DELIVERY_KEY]) ?? {};
  workspace[SOFTWARE_DELIVERY_KEY] = mergeConfigDefaults(
    softwareDeliveryConfig,
    existingSoftwareDelivery
  );
  fs2.writeFileSync(workspacePath, yaml.stringify(workspace), "utf-8");
  if (exists) {
    result.overwritten = result.overwritten ?? [];
    if (!result.overwritten.includes(CONFIG_FILE_NAME)) {
      result.overwritten.push(CONFIG_FILE_NAME);
    }
    return;
  }
  result.created.push(CONFIG_FILE_NAME);
}
function buildSoftwareDeliveryConfig(gatePreset, gitConfigOverride, client, docsPaths, targetDir) {
  const config = getDefaultConfig();
  config.directories.agentsDir = LUMENFLOW_AGENTS_DIR;
  if (docsPaths) {
    config.directories.wuDir = `${docsPaths.tasks}/wu`;
    config.directories.initiativesDir = `${docsPaths.tasks}/initiatives`;
    config.directories.backlogPath = `${docsPaths.tasks}/backlog.md`;
    config.directories.statusPath = `${docsPaths.tasks}/status.md`;
    config.directories.plansDir = `${docsPaths.operations}/plans`;
    config.directories.onboardingDir = docsPaths.onboarding;
    config.directories.completeGuidePath = docsPaths.completeGuidePath;
    config.directories.quickRefPath = docsPaths.quickRefPath;
    config.directories.startingPromptPath = docsPaths.startingPromptPath;
    config.directories.governancePath = docsPaths.governancePath;
  }
  if (gatePreset && GATE_PRESETS[gatePreset]) {
    const presetConfig = GATE_PRESETS[gatePreset];
    config.gates.execution = {
      preset: gatePreset,
      ...presetConfig
    };
  }
  config.lanes = {
    lifecycle: {
      status: LANE_LIFECYCLE_STATUS.UNCONFIGURED
    }
  };
  if (gitConfigOverride) {
    config.git = {
      requireRemote: gitConfigOverride.requireRemote
    };
  }
  if (targetDir) {
    const tooling = detectProjectTooling(targetDir);
    if (tooling.testRunner) {
      config.test_runner = tooling.testRunner;
    } else {
      config.test_runner = "jest";
    }
    const pm = tooling.packageManager ?? "pnpm";
    const commands = {};
    if (tooling.hasTurbo) {
      commands.test_full = `${pm} turbo run test`;
    } else {
      commands.test_full = `${pm} test`;
    }
    if (tooling.testRunner === "vitest") {
      commands.test_incremental = `${pm} vitest run --changed origin/main`;
    } else if (tooling.testRunner === "jest") {
      commands.test_incremental = `${pm} jest --onlyChanged`;
    } else {
      commands.test_incremental = `${pm} test`;
    }
    config.gates.commands = {
      ...config.gates.commands,
      ...commands
    };
  }
  if (client === "claude") {
    config.agents = {
      clients: {
        [DEFAULT_CLIENT_CLAUDE2]: {
          enforcement: {
            hooks: true,
            block_outside_worktree: true,
            require_wu_for_edits: true,
            warn_on_stop_without_wu_done: true
          }
        }
      }
    };
  }
  return config;
}
function getCurrentDate() {
  return (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
}
function normalizeFrameworkName(framework) {
  const name = framework.trim();
  const slug = name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+/, "").replace(/-+$/, "");
  if (!slug) {
    throw createError(ErrorCodes.INVALID_ARGUMENT, `Invalid framework name: "${framework}"`);
  }
  return { name, slug };
}
function resolveClientType(client, vendor, defaultClient) {
  if (client) {
    return client;
  }
  if (vendor) {
    return vendor;
  }
  return defaultClient === DEFAULT_CLIENT_CLAUDE2 ? "claude" : "none";
}
function getFileMode(options) {
  if (options.force) {
    return "force";
  }
  if (options.merge) {
    return "merge";
  }
  return "skip";
}
var CLIENT_INTEGRATIONS = {
  [LUMENFLOW_CLIENT_IDS.CLAUDE_CODE]: {
    run: (projectDir, enforcement) => integrateClaudeCode(projectDir, { enforcement })
  }
  // When new clients gain enforcement: add adapter entry here.
};
async function runClientIntegrations(targetDir, result) {
  const integrationFiles = [];
  const configPath = path2.join(targetDir, CONFIG_FILE_NAME);
  if (!fs2.existsSync(configPath)) return integrationFiles;
  let softwareDeliveryConfig;
  try {
    const content = fs2.readFileSync(configPath, "utf-8");
    const workspaceConfig = asRecord(yaml.parse(content));
    softwareDeliveryConfig = workspaceConfig ? asRecord(workspaceConfig[SOFTWARE_DELIVERY_KEY]) : null;
  } catch {
    return integrationFiles;
  }
  if (!softwareDeliveryConfig) return integrationFiles;
  const agents = asRecord(softwareDeliveryConfig[SOFTWARE_DELIVERY_CONFIG_KEYS.AGENTS]);
  const clients = asRecord(agents?.[SOFTWARE_DELIVERY_CONFIG_KEYS.CLIENTS]);
  if (!clients) return integrationFiles;
  for (const [clientKey, unsafeClientConfig] of Object.entries(clients)) {
    const clientConfig = asRecord(unsafeClientConfig);
    if (!clientConfig) {
      continue;
    }
    const enforcement = asRecord(
      clientConfig[SOFTWARE_DELIVERY_CONFIG_KEYS.ENFORCEMENT]
    );
    if (!enforcement?.hooks) continue;
    const integration = CLIENT_INTEGRATIONS[clientKey];
    if (!integration) continue;
    const createdFiles = await integration.run(targetDir, enforcement);
    integrationFiles.push(...createdFiles);
  }
  result.created.push(...integrationFiles);
  result.integrationFiles = integrationFiles;
  return integrationFiles;
}
function createInitialCommitIfNeeded(targetDir) {
  if (!isGitRepo(targetDir) || hasGitCommits(targetDir)) {
    return false;
  }
  try {
    execFileSync2("git", ["add", "."], { cwd: targetDir, stdio: "pipe" });
    execFileSync2("git", ["commit", "-m", "chore: initialize LumenFlow project"], {
      cwd: targetDir,
      stdio: "pipe"
    });
    return true;
  } catch {
    return false;
  }
}
function renameMasterToMainIfNeeded(targetDir) {
  if (!isGitRepo(targetDir)) {
    return false;
  }
  try {
    const currentBranch = execFileSync2("git", ["branch", "--show-current"], {
      cwd: targetDir,
      encoding: "utf-8",
      stdio: "pipe"
    }).trim();
    if (currentBranch !== "master") {
      return false;
    }
    execFileSync2("git", ["branch", "-m", "master", "main"], {
      cwd: targetDir,
      stdio: "pipe"
    });
    return true;
  } catch {
    return false;
  }
}
async function scaffoldProject(targetDir, options) {
  const result = {
    created: [],
    skipped: [],
    merged: [],
    warnings: [],
    overwritten: []
  };
  await checkBranchGuard(targetDir, result);
  const defaultClient = options.defaultClient ?? detectDefaultClient();
  const client = resolveClientType(options.client, options.vendor, defaultClient);
  const fileMode = getFileMode(options);
  if (!fs2.existsSync(targetDir)) {
    fs2.mkdirSync(targetDir, { recursive: true });
  }
  const docsStructure = options.docsStructure ?? detectDocsStructure(targetDir);
  const docsPaths = getDocsPath(docsStructure);
  const gitConfigOverride = detectGitStateConfig(targetDir);
  const tokenDefaults = {
    DATE: getCurrentDate(),
    PROJECT_ROOT: "<project-root>",
    // WU-1309: Use portable placeholder
    QUICK_REF_LINK: docsPaths.quickRefLink,
    DOCS_OPERATIONS_PATH: docsPaths.operations,
    // WU-1309: For framework overlay
    DOCS_TASKS_PATH: docsPaths.tasks,
    DOCS_ONBOARDING_PATH: docsPaths.onboarding,
    DOCS_WU_DIR_PATH: `${docsPaths.tasks}/wu`,
    DOCS_TEMPLATES_DIR_PATH: `${docsPaths.tasks}/templates`,
    DOCS_BACKLOG_PATH: `${docsPaths.tasks}/backlog.md`,
    DOCS_STATUS_PATH: `${docsPaths.tasks}/status.md`
  };
  upsertWorkspaceSoftwareDelivery(
    targetDir,
    buildSoftwareDeliveryConfig(
      options.gatePreset,
      gitConfigOverride,
      client,
      docsPaths,
      targetDir
    ),
    result
  );
  try {
    const agentsTemplate = loadTemplate("core/AGENTS.md.template");
    await createFile(
      path2.join(targetDir, "AGENTS.md"),
      processTemplate(agentsTemplate, tokenDefaults),
      fileMode,
      result,
      targetDir
    );
  } catch {
    await createFile(
      path2.join(targetDir, "AGENTS.md"),
      processTemplate(AGENTS_MD_TEMPLATE, tokenDefaults),
      fileMode,
      result,
      targetDir
    );
  }
  await createFile(
    path2.join(targetDir, "LUMENFLOW.md"),
    processTemplate(loadTemplate("core/LUMENFLOW.md.template"), tokenDefaults),
    fileMode,
    result,
    targetDir
  );
  await createFile(
    path2.join(targetDir, LUMENFLOW_DIR, "constraints.md"),
    processTemplate(loadTemplate("core/.lumenflow/constraints.md.template"), tokenDefaults),
    fileMode,
    result,
    targetDir
  );
  await createDirectory(path2.join(targetDir, LUMENFLOW_AGENTS_DIR), result, targetDir);
  await createFile(
    path2.join(targetDir, LUMENFLOW_AGENTS_DIR, ".gitkeep"),
    "",
    options.force ? "force" : "skip",
    result,
    targetDir
  );
  await scaffoldGitignore(targetDir, options, result);
  await scaffoldPrettierignore(targetDir, options, result);
  await scaffoldSafetyScripts(targetDir, options, result);
  if (options.full) {
    await scaffoldFullDocs(targetDir, options, result, tokenDefaults);
  }
  if (options.framework) {
    await scaffoldFrameworkOverlay(targetDir, options, result, tokenDefaults);
  }
  await scaffoldClientFiles(targetDir, options, result, tokenDefaults, client);
  await injectPackageJsonScripts(targetDir, options, result);
  await runClientIntegrations(targetDir, result);
  const createdInitialCommit = createInitialCommitIfNeeded(targetDir);
  if (createdInitialCommit) {
    result.created.push("Initial git commit");
  }
  const renamedBranch = renameMasterToMainIfNeeded(targetDir);
  if (renamedBranch) {
    result.created.push("Renamed branch master -> main");
  }
  const uniqueParents = [
    ...new Set(DEFAULT_LANE_DEFINITIONS.map((lane) => lane.name.split(":")[0].trim()))
  ];
  console.log("");
  console.log(
    '  Lane naming format: "Parent: Sublane" (e.g., "Framework: Core", "Content: Documentation")'
  );
  console.log(`  Valid parent names: ${uniqueParents.join(", ")}`);
  return result;
}
var GITIGNORE_FILE_NAME = ".gitignore";
async function scaffoldGitignore(targetDir, options, result) {
  const gitignorePath = path2.join(targetDir, GITIGNORE_FILE_NAME);
  const fileMode = getFileMode(options);
  if ((fileMode === "merge" || fileMode === "skip") && fs2.existsSync(gitignorePath)) {
    const existingContent = fs2.readFileSync(gitignorePath, "utf-8");
    const linesToAdd = [];
    for (const { pattern, line } of REQUIRED_GITIGNORE_EXCLUSIONS) {
      if (!existingContent.includes(pattern)) {
        linesToAdd.push(line);
      }
    }
    if (linesToAdd.length > 0) {
      const separator = existingContent.endsWith("\n") ? "" : "\n";
      const lumenflowBlock = `${separator}
# LumenFlow (auto-added)
${linesToAdd.join("\n")}
`;
      fs2.writeFileSync(gitignorePath, existingContent + lumenflowBlock);
      result.merged = result.merged ?? [];
      result.merged.push(GITIGNORE_FILE_NAME);
    } else {
      result.skipped.push(GITIGNORE_FILE_NAME);
    }
    return;
  }
  await createFile(gitignorePath, GITIGNORE_TEMPLATE, fileMode, result, targetDir);
}
var PRETTIERIGNORE_FILE_NAME = ".prettierignore";
async function scaffoldPrettierignore(targetDir, options, result) {
  const prettierignorePath = path2.join(targetDir, PRETTIERIGNORE_FILE_NAME);
  const fileMode = getFileMode(options);
  await createFile(prettierignorePath, PRETTIERIGNORE_TEMPLATE, fileMode, result, targetDir);
}
function generateLumenflowScripts() {
  const scripts = {};
  const manifest = getPublicManifest();
  for (const cmd of manifest) {
    scripts[cmd.name] = SCRIPT_ARG_OVERRIDES[cmd.name] ?? cmd.binName;
  }
  return scripts;
}
var SCRIPTS_DIR = "scripts";
var SAFE_GIT_FILE = "safe-git";
var HUSKY_DIR = ".husky";
var PRE_COMMIT_FILE = "pre-commit";
var SAFE_GIT_TEMPLATE_PATH = "core/scripts/safe-git.template";
var PRE_COMMIT_TEMPLATE_PATH = "core/.husky/pre-commit.template";
async function scaffoldSafetyScripts(targetDir, options, result) {
  const fileMode = getFileMode(options);
  const safeGitPath = path2.join(targetDir, SCRIPTS_DIR, SAFE_GIT_FILE);
  try {
    const safeGitTemplate = loadTemplate(SAFE_GIT_TEMPLATE_PATH);
    await createExecutableScript(safeGitPath, safeGitTemplate, fileMode, result, targetDir);
  } catch {
    await createExecutableScript(safeGitPath, SAFE_GIT_TEMPLATE, fileMode, result, targetDir);
  }
  const preCommitPath = path2.join(targetDir, HUSKY_DIR, PRE_COMMIT_FILE);
  try {
    const preCommitTemplate = loadTemplate(PRE_COMMIT_TEMPLATE_PATH);
    await createExecutableScript(preCommitPath, preCommitTemplate, fileMode, result, targetDir);
  } catch {
    await createExecutableScript(preCommitPath, PRE_COMMIT_TEMPLATE, fileMode, result, targetDir);
  }
}
var PRETTIER_VERSION = "^3.8.0";
var PRETTIER_PACKAGE_NAME = "prettier";
var CLI_PACKAGE_VERSION = "^3.0.0";
var CLI_PACKAGE_NAME = "@lumenflow/cli";
async function injectPackageJsonScripts(targetDir, options, result) {
  const packageJsonPath = path2.join(targetDir, "package.json");
  let packageJson;
  if (fs2.existsSync(packageJsonPath)) {
    const content = fs2.readFileSync(packageJsonPath, "utf-8");
    packageJson = JSON.parse(content);
  } else {
    packageJson = {
      name: path2.basename(targetDir),
      version: "0.0.1",
      private: true
    };
  }
  if (!packageJson.scripts || typeof packageJson.scripts !== "object") {
    packageJson.scripts = {};
  }
  const scripts = packageJson.scripts;
  let modified = false;
  const lumenflowScripts = generateLumenflowScripts();
  for (const [scriptName, scriptCommand] of Object.entries(lumenflowScripts)) {
    if (options.force || !(scriptName in scripts)) {
      if (!(scriptName in scripts)) {
        scripts[scriptName] = scriptCommand;
        modified = true;
      }
    }
  }
  for (const [scriptName, scriptCommand] of Object.entries(GATE_STUB_SCRIPTS)) {
    if (options.force) {
      scripts[scriptName] = scriptCommand;
      modified = true;
    } else if (!(scriptName in scripts)) {
      scripts[scriptName] = scriptCommand;
      modified = true;
    }
  }
  if (!packageJson.devDependencies || typeof packageJson.devDependencies !== "object") {
    packageJson.devDependencies = {};
  }
  const devDeps = packageJson.devDependencies;
  if (options.force || !(CLI_PACKAGE_NAME in devDeps)) {
    if (options.force && CLI_PACKAGE_NAME in devDeps) {
      devDeps[CLI_PACKAGE_NAME] = CLI_PACKAGE_VERSION;
      modified = true;
    } else if (!(CLI_PACKAGE_NAME in devDeps)) {
      devDeps[CLI_PACKAGE_NAME] = CLI_PACKAGE_VERSION;
      modified = true;
    }
  }
  if (options.force || !(PRETTIER_PACKAGE_NAME in devDeps)) {
    if (!(PRETTIER_PACKAGE_NAME in devDeps)) {
      devDeps[PRETTIER_PACKAGE_NAME] = PRETTIER_VERSION;
      modified = true;
    }
  }
  if (modified) {
    fs2.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2) + "\n");
    result.created.push("package.json (scripts updated)");
  }
}
async function runPostScaffoldInstall(targetDir, options) {
  const packageJsonPath = path2.join(targetDir, "package.json");
  if (!fs2.existsSync(packageJsonPath)) {
    return { packageManager: "npm", command: "npm install", skipped: true };
  }
  let pm = "npm";
  try {
    const content = fs2.readFileSync(packageJsonPath, "utf-8");
    const pkg = JSON.parse(content);
    const pkgManager = pkg.packageManager;
    if (pkgManager?.startsWith("pnpm")) {
      pm = "pnpm";
    } else if (pkgManager?.startsWith("yarn")) {
      pm = "yarn";
    } else if (pkgManager?.startsWith("bun")) {
      pm = "bun";
    } else if (pkgManager?.startsWith("npm")) {
      pm = "npm";
    } else {
      if (fs2.existsSync(path2.join(targetDir, "pnpm-lock.yaml"))) {
        pm = "pnpm";
      } else if (fs2.existsSync(path2.join(targetDir, "yarn.lock"))) {
        pm = "yarn";
      } else if (fs2.existsSync(path2.join(targetDir, "bun.lockb")) || fs2.existsSync(path2.join(targetDir, "bun.lock"))) {
        pm = "bun";
      }
    }
  } catch {
  }
  const command = `${pm} install`;
  if (options?.dryRun) {
    return { packageManager: pm, command, skipped: false };
  }
  try {
    console.log(`
[lumenflow init] Installing dependencies (${command})...`);
    execFileSync2(pm, ["install"], {
      cwd: targetDir,
      stdio: "inherit"
    });
    console.log("[lumenflow init] \u2713 Dependencies installed");
    return { packageManager: pm, command, skipped: false };
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : String(err);
    console.warn(`[lumenflow init] \u26A0 ${command} failed: ${errorMessage}`);
    console.warn(`[lumenflow init] Run "${command}" manually to install dependencies.`);
    return { packageManager: pm, command, skipped: false, error: errorMessage };
  }
}
async function scaffoldFullDocs(targetDir, options, result, tokens) {
  const wuDir = path2.join(targetDir, tokens.DOCS_WU_DIR_PATH);
  const templatesDir = path2.join(targetDir, tokens.DOCS_TEMPLATES_DIR_PATH);
  await createDirectory(wuDir, result, targetDir);
  await createDirectory(templatesDir, result, targetDir);
  await createFile(path2.join(wuDir, ".gitkeep"), "", options.force, result, targetDir);
  await createFile(
    path2.join(targetDir, tokens.DOCS_BACKLOG_PATH),
    BACKLOG_TEMPLATE,
    options.force,
    result,
    targetDir
  );
  await createFile(
    path2.join(targetDir, tokens.DOCS_STATUS_PATH),
    STATUS_TEMPLATE,
    options.force,
    result,
    targetDir
  );
  await createFile(
    path2.join(templatesDir, "wu-template.yaml"),
    processTemplate(WU_TEMPLATE_YAML, tokens),
    options.force,
    result,
    targetDir
  );
  await scaffoldAgentOnboardingDocs(targetDir, options, result, tokens);
}
async function scaffoldAgentOnboardingDocs(targetDir, options, result, tokens) {
  const onboardingDir = path2.join(targetDir, tokens.DOCS_ONBOARDING_PATH);
  await createDirectory(onboardingDir, result, targetDir);
  for (const [outputFile, templatePath] of Object.entries(SCAFFOLDED_ONBOARDING_TEMPLATE_PATHS)) {
    await createFile(
      path2.join(onboardingDir, outputFile),
      processTemplate(loadTemplate(templatePath), tokens),
      options.force,
      result,
      targetDir
    );
  }
}
async function scaffoldClaudeSkills(targetDir, options, result, tokens) {
  const skillsDir = path2.join(targetDir, ".claude", "skills");
  const wuLifecycleDir = path2.join(skillsDir, "wu-lifecycle");
  await createDirectory(wuLifecycleDir, result, targetDir);
  await createFile(
    path2.join(wuLifecycleDir, "SKILL.md"),
    processTemplate(WU_LIFECYCLE_SKILL_TEMPLATE, tokens),
    options.force,
    result,
    targetDir
  );
  const worktreeDir = path2.join(skillsDir, "worktree-discipline");
  await createDirectory(worktreeDir, result, targetDir);
  await createFile(
    path2.join(worktreeDir, "SKILL.md"),
    processTemplate(WORKTREE_DISCIPLINE_SKILL_TEMPLATE, tokens),
    options.force,
    result,
    targetDir
  );
  const gatesDir = path2.join(skillsDir, "lumenflow-gates");
  await createDirectory(gatesDir, result, targetDir);
  await createFile(
    path2.join(gatesDir, "SKILL.md"),
    processTemplate(LUMENFLOW_GATES_SKILL_TEMPLATE, tokens),
    options.force,
    result,
    targetDir
  );
}
async function scaffoldFrameworkOverlay(targetDir, options, result, tokens) {
  if (!options.framework) {
    return;
  }
  const { name, slug } = normalizeFrameworkName(options.framework);
  const frameworkTokens = {
    ...tokens,
    FRAMEWORK_NAME: name,
    FRAMEWORK_SLUG: slug
  };
  await createFile(
    path2.join(targetDir, FRAMEWORK_HINT_FILE),
    processTemplate(FRAMEWORK_HINT_TEMPLATE, frameworkTokens),
    options.force,
    result,
    targetDir
  );
  const overlayDir = path2.join(targetDir, tokens.DOCS_OPERATIONS_PATH, "_frameworks", slug);
  await createDirectory(overlayDir, result, targetDir);
  await createFile(
    path2.join(overlayDir, "README.md"),
    processTemplate(FRAMEWORK_OVERLAY_TEMPLATE, frameworkTokens),
    options.force,
    result,
    targetDir
  );
}
async function scaffoldClientFiles(targetDir, options, result, tokens, client) {
  const fileMode = getFileMode(options);
  if (client === "claude" || client === "all") {
    await createFile(
      path2.join(targetDir, "CLAUDE.md"),
      processTemplate(CLAUDE_MD_TEMPLATE, tokens),
      fileMode,
      result,
      targetDir
    );
    await createDirectory(path2.join(targetDir, CLAUDE_AGENTS_DIR), result, targetDir);
    await createFile(
      path2.join(targetDir, CLAUDE_AGENTS_DIR, ".gitkeep"),
      "",
      options.force ? "force" : "skip",
      result,
      targetDir
    );
    let settingsContent;
    try {
      settingsContent = loadTemplate(CLAUDE_HOOKS.TEMPLATES.SETTINGS);
    } catch {
      settingsContent = CLAUDE_SETTINGS_TEMPLATE;
    }
    await createFile(
      path2.join(targetDir, CLAUDE_DIR, "settings.json"),
      settingsContent,
      options.force ? "force" : "skip",
      result,
      targetDir
    );
    let mcpJsonContent;
    try {
      mcpJsonContent = loadTemplate("core/.mcp.json.template");
    } catch {
      mcpJsonContent = MCP_JSON_TEMPLATE;
    }
    await createFile(
      path2.join(targetDir, ".mcp.json"),
      mcpJsonContent,
      fileMode,
      result,
      targetDir
    );
    const hooksDir = path2.join(targetDir, CLAUDE_DIR, "hooks");
    await createDirectory(hooksDir, result, targetDir);
    try {
      const preCompactScript = loadTemplate(CLAUDE_HOOKS.TEMPLATES.PRE_COMPACT);
      await createExecutableScript(
        path2.join(hooksDir, CLAUDE_HOOKS.SCRIPTS.PRE_COMPACT_CHECKPOINT),
        preCompactScript,
        options.force ? "force" : "skip",
        result,
        targetDir
      );
    } catch {
    }
    const sessionStartScript = generateSessionStartRecoveryScript();
    await createExecutableScript(
      path2.join(hooksDir, CLAUDE_HOOKS.SCRIPTS.SESSION_START_RECOVERY),
      sessionStartScript,
      options.force ? "force" : "skip",
      result,
      targetDir
    );
    await scaffoldClaudeSkills(targetDir, options, result, tokens);
    if (!options.full) {
      await scaffoldAgentOnboardingDocs(targetDir, options, result, tokens);
    }
  }
  if (client === "cursor" || client === "all") {
    const cursorRulesDir = path2.join(targetDir, ".cursor", "rules");
    await createDirectory(cursorRulesDir, result, targetDir);
    let cursorContent;
    try {
      cursorContent = loadTemplate("vendors/cursor/.cursor/rules/lumenflow.md.template");
    } catch {
      cursorContent = CURSOR_RULES_TEMPLATE;
    }
    await createFile(
      path2.join(cursorRulesDir, "lumenflow.md"),
      processTemplate(cursorContent, tokens),
      fileMode,
      result,
      targetDir
    );
  }
  if (client === "windsurf" || client === "all") {
    const windsurfRulesDir = path2.join(targetDir, ".windsurf", "rules");
    await createDirectory(windsurfRulesDir, result, targetDir);
    let windsurfContent;
    try {
      windsurfContent = loadTemplate("vendors/windsurf/.windsurf/rules/lumenflow.md.template");
    } catch {
      windsurfContent = WINDSURF_RULES_TEMPLATE;
    }
    await createFile(
      path2.join(windsurfRulesDir, "lumenflow.md"),
      processTemplate(windsurfContent, tokens),
      fileMode,
      result,
      targetDir
    );
  }
  if (client === "cline" || client === "all") {
    let clineContent;
    try {
      clineContent = loadTemplate("vendors/cline/.clinerules.template");
    } catch {
      clineContent = CLINE_RULES_TEMPLATE;
    }
    await createFile(
      path2.join(targetDir, ".clinerules"),
      processTemplate(clineContent, tokens),
      fileMode,
      result,
      targetDir
    );
  }
  if (client === "aider" || client === "all") {
    await createFile(
      path2.join(targetDir, ".aider.conf.yml"),
      AIDER_CONF_TEMPLATE,
      fileMode,
      result,
      targetDir
    );
  }
}
function resolveBootstrapProjectName(targetDir) {
  const basename2 = path2.basename(path2.resolve(targetDir)).trim();
  return basename2.length > 0 ? basename2 : DEFAULT_PROJECT_NAME;
}
async function runInitBootstrap(options) {
  if (options.skipBootstrap) {
    return {
      skipped: true,
      reason: BOOTSTRAP_SKIP_REASON_FLAG,
      workspaceGenerated: false,
      packInstalled: false
    };
  }
  const workspacePath = path2.join(options.targetDir, WORKSPACE_FILENAME);
  const hasExistingWorkspace = fs2.existsSync(workspacePath);
  if (hasExistingWorkspace && !options.force) {
    return {
      skipped: true,
      reason: BOOTSTRAP_SKIP_REASON_EXISTING_WORKSPACE,
      workspaceGenerated: false,
      packInstalled: false
    };
  }
  const onboardModule = await import("./onboard.js");
  const onboardResult = await onboardModule.runOnboard({
    targetDir: options.targetDir,
    nonInteractive: true,
    projectName: resolveBootstrapProjectName(options.targetDir),
    domain: options.bootstrapDomain,
    force: options.force,
    skipPackInstall: options.skipBootstrapPackInstall,
    skipDashboard: true,
    fetchFn: options.fetchFn ?? globalThis.fetch
  });
  if (!onboardResult.success) {
    const failureReason = onboardResult.errors.join("; ") || "unknown onboarding error";
    throw createError(ErrorCodes.ONBOARD_FAILED, `${BOOTSTRAP_ERROR_PREFIX} ${failureReason}`);
  }
  const packFailed = !options.skipBootstrapPackInstall && options.bootstrapDomain !== BOOTSTRAP_CUSTOM_DOMAIN && onboardResult.packInstalled !== true;
  const warning = packFailed ? `${BOOTSTRAP_ERROR_PREFIX} failed to install ${options.bootstrapDomain} pack with integrity metadata. Continuing without pack. Retry later with: pnpm pack:install --id ${options.bootstrapDomain}` : void 0;
  if (warning) {
    console.warn(`
\u26A0 ${warning}
`);
  }
  return {
    skipped: false,
    workspaceGenerated: onboardResult.workspaceGenerated === true,
    packInstalled: onboardResult.packInstalled === true,
    warning
  };
}
async function main() {
  const invokedBinary = path2.basename(process.argv[1] ?? "", ".js");
  const subcommand = process.argv[2];
  if (invokedBinary === CLOUD_CONNECT_BIN) {
    const { runCloudConnectCli } = await import("./onboard.js");
    await runCloudConnectCli();
    return;
  }
  if (subcommand === INIT_SUBCOMMANDS.COMMANDS) {
    const { main: commandsMain } = await import("./commands.js");
    process.argv.splice(2, 1);
    await commandsMain();
    return;
  }
  if (subcommand === LEGACY_SUBCOMMANDS.ONBOARD || subcommand === LEGACY_SUBCOMMANDS.WORKSPACE_INIT_COLON || subcommand === LEGACY_SUBCOMMANDS.WORKSPACE_INIT_DASH) {
    throw createError(
      ErrorCodes.DEPRECATED_API,
      `${LEGACY_SUBCOMMAND_ERROR_PREFIX} "${subcommand}". ${LEGACY_SUBCOMMAND_GUIDANCE}. ${LEGACY_SUBCOMMAND_HELP_HINT}.`
    );
  }
  if (subcommand === INIT_SUBCOMMANDS.CLOUD) {
    const cloudSubcommand = process.argv[3];
    if (cloudSubcommand !== CLOUD_SUBCOMMANDS.CONNECT) {
      throw createError(
        ErrorCodes.INVALID_ARGUMENT,
        `${INIT_ERROR_PREFIX} Unknown cloud subcommand "${cloudSubcommand ?? ""}". ${INIT_CLOUD_CONNECT_HELP}`
      );
    }
    const { runCloudConnectCli } = await import("./onboard.js");
    process.argv.splice(2, 2);
    await runCloudConnectCli();
    return;
  }
  const opts = parseInitOptions();
  const targetDir = process.cwd();
  console.log("[lumenflow init] Scaffolding LumenFlow project...");
  console.log(`  Mode: ${opts.full ? "full" : "minimal"}${opts.merge ? " (merge)" : ""}`);
  console.log(`  Framework: ${opts.framework ?? "none"}`);
  console.log(`  Client: ${opts.client ?? "auto"}`);
  console.log(`  Gate preset: ${opts.preset ?? "none (manual config)"}`);
  console.log(`  Bootstrap domain: ${opts.bootstrapDomain}`);
  console.log(
    `  Bootstrap pack install: ${opts.skipBootstrapPackInstall ? "skipped (--skip-bootstrap-pack-install)" : "required"}`
  );
  const bootstrapResult = await runInitBootstrap({
    targetDir,
    force: opts.force,
    bootstrapDomain: opts.bootstrapDomain,
    skipBootstrap: opts.skipBootstrap,
    skipBootstrapPackInstall: opts.skipBootstrapPackInstall
  });
  if (bootstrapResult.skipped) {
    console.log(`  Bootstrap: skipped (${bootstrapResult.reason})`);
  } else {
    console.log(
      `  Bootstrap: workspace=${bootstrapResult.workspaceGenerated ? "created" : "unchanged"}, pack=${bootstrapResult.packInstalled ? "installed" : "skipped"}`
    );
  }
  const result = await scaffoldProject(targetDir, {
    force: opts.force,
    full: opts.full,
    merge: opts.merge,
    client: opts.client,
    vendor: opts.vendor,
    // Backwards compatibility
    framework: opts.framework,
    gatePreset: opts.preset
  });
  if (result.created.length > 0) {
    console.log("\nCreated:");
    result.created.forEach((f) => console.log(`  + ${f}`));
  }
  if (result.merged && result.merged.length > 0) {
    console.log("\nMerged (LumenFlow block inserted/updated):");
    result.merged.forEach((f) => console.log(`  ~ ${f}`));
  }
  if (result.overwritten && result.overwritten.length > 0) {
    console.log("\nOverwritten (existing file replaced with --force):");
    result.overwritten.forEach((f) => console.log(`  ! ${f}`));
  }
  if (result.skipped.length > 0) {
    console.log("\nSkipped (already exists, use --force to overwrite or --merge to insert block):");
    result.skipped.forEach((f) => console.log(`  - ${f}`));
  }
  if (result.warnings && result.warnings.length > 0) {
    console.log("\nWarnings:");
    result.warnings.forEach((w) => console.log(`  \u26A0 ${w}`));
  }
  await runPostScaffoldInstall(targetDir);
  try {
    const doctorResult = await runDoctorForInit(targetDir);
    if (doctorResult.output) {
      console.log("");
      console.log(doctorResult.output);
    }
  } catch {
  }
  console.log("\n[lumenflow init] Done! Next steps:");
  console.log("  1. Review AGENTS.md and LUMENFLOW.md for workflow documentation");
  console.log(
    `  2. Review ${CONFIG_FILE_NAME} ${SOFTWARE_DELIVERY_KEY} settings for project defaults`
  );
  console.log("");
  console.log(`  ${buildInitLaneLifecycleMessage(LANE_LIFECYCLE_STATUS.UNCONFIGURED)}`);
  if (result.integrationFiles && result.integrationFiles.length > 0) {
    console.log(
      "  \u2713 Enforcement hooks installed -- regenerate with: pnpm lumenflow:integrate"
    );
  }
  console.log("");
  console.log("  For a product vision (multi-phase work):");
  console.log('     pnpm initiative:create --id INIT-001 --title "Project Name" \\');
  console.log('       --phase "Phase 1: MVP" --phase "Phase 2: Polish"');
  console.log("");
  console.log("  For a single WU:");
  console.log('     pnpm wu:create --lane <lane> --title "First WU" \\');
  console.log('       --description "Context: ... Problem: ... Solution: ..." \\');
  console.log('       --acceptance "Criterion 1" --code-paths "src/..." --exposure backend-only');
  console.log("");
  console.log("     # Or for rapid prototyping (minimal validation):");
  console.log('     pnpm wu:proto --lane <lane> --title "Quick experiment"');
  console.log("");
  console.log("  Full lifecycle: wu:create -> wu:claim -> wu:prep -> wu:done");
}
if (import.meta.main) {
  void runCLI(main, { showHeader: true });
}

export {
  detectIDEEnvironment,
  checkPrerequisites,
  getDocsPath,
  detectDocsStructure,
  parseInitOptions,
  renameMasterToMainIfNeeded,
  scaffoldProject,
  runPostScaffoldInstall,
  runInitBootstrap,
  main
};
