import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../core/dist/wu-statuses.js
var WU_STATUS = {
  // Unclaimed statuses (not yet entered state machine)
  // WU-1374: Legacy backlog status value
  TODO: "todo",
  READY: "ready",
  // Canonical unclaimed status
  BACKLOG: "backlog",
  // Legacy variant of ready
  // Active statuses (in state machine)
  IN_PROGRESS: "in_progress",
  BLOCKED: "blocked",
  // Terminal statuses (work finished, no further transitions)
  DONE: "done",
  // Canonical terminal status
  COMPLETED: "completed",
  // Legacy variant of done
  CANCELLED: "cancelled",
  ABANDONED: "abandoned",
  DEFERRED: "deferred",
  CLOSED: "closed",
  SUPERSEDED: "superseded"
};
var WU_STATUS_FALLBACK = {
  UNKNOWN: "unknown"
};
var WU_STATUS_SET = new Set(Object.values(WU_STATUS));
function isWUStatus(value) {
  return typeof value === "string" && WU_STATUS_SET.has(value);
}
function resolveWUStatus(value, fallback = WU_STATUS.READY) {
  return isWUStatus(value) ? value : fallback;
}
function getWUStatusDisplay(value) {
  return isWUStatus(value) ? value : WU_STATUS_FALLBACK.UNKNOWN;
}
var PROTECTED_WU_STATUSES = [
  WU_STATUS.IN_PROGRESS,
  WU_STATUS.BLOCKED
];
var PROGRESSABLE_WU_STATUSES = [WU_STATUS.IN_PROGRESS];
var WU_STATUS_GROUPS = {
  /** Statuses representing unclaimed work (not tracked in state store) */
  UNCLAIMED: [WU_STATUS.READY, WU_STATUS.TODO, WU_STATUS.BACKLOG],
  /** Terminal statuses (all map to 'done' in state store) */
  TERMINAL: [
    WU_STATUS.DONE,
    WU_STATUS.COMPLETED,
    WU_STATUS.CANCELLED,
    WU_STATUS.ABANDONED,
    WU_STATUS.DEFERRED,
    WU_STATUS.CLOSED,
    WU_STATUS.SUPERSEDED
  ]
};
var CLAIMED_MODES = {
  /** Standard worktree mode (isolated worktree per WU) */
  WORKTREE: "worktree",
  /** Branch-only mode (no worktree, direct branch work) */
  BRANCH_ONLY: "branch-only",
  /** Worktree PR mode (worktree with manual PR workflow) */
  WORKTREE_PR: "worktree-pr",
  /** Branch PR mode (no worktree, PR-based completion for cloud agents) */
  BRANCH_PR: "branch-pr"
};
var INCIDENT_SEVERITY = {
  BLOCKER: "blocker",
  MAJOR: "major",
  MINOR: "minor",
  INFO: "info"
};
var WU_TYPES = {
  DOCUMENTATION: "documentation",
  PROCESS: "process",
  FEATURE: "feature",
  TOOLING: "tooling",
  BUG: "bug"
};
var WU_EXPOSURE = {
  /** User-facing UI changes (pages, components, widgets) */
  UI: "ui",
  /** API endpoints that are called by UI or external clients */
  API: "api",
  /** Backend-only changes (no user visibility) */
  BACKEND_ONLY: "backend-only",
  /** Documentation changes only */
  DOCUMENTATION: "documentation"
};
var WU_EXPOSURE_VALUES = ["ui", "api", "backend-only", "documentation"];
var TEST_TYPES = {
  UNIT: "unit",
  E2E: "e2e",
  MANUAL: "manual",
  INTEGRATION: "integration"
};

// ../core/dist/config-contract.js
var WORKSPACE_CONFIG_BASENAME = "workspace";
var YAML_FILE_EXTENSION = "yaml";
var WORKSPACE_CONFIG_FILE_NAME = `${WORKSPACE_CONFIG_BASENAME}.${YAML_FILE_EXTENSION}`;
var GIT_DIRECTORY_NAME = ".git";
var GIT_WORKTREES_DIRECTORY_NAME = "worktrees";
var GIT_WORKTREES_SEGMENT = `${GIT_DIRECTORY_NAME}/${GIT_WORKTREES_DIRECTORY_NAME}`;
var GIT_WORKTREES_SENTINEL = `/${GIT_WORKTREES_SEGMENT}/`;
var WORKSPACE_V2_KEYS = {
  SOFTWARE_DELIVERY: "software_delivery",
  CONTROL_PLANE: "control_plane"
};
var WRITABLE_ROOT_KEYS = /* @__PURE__ */ new Set([
  "control_plane",
  "memory_namespace",
  "event_namespace"
]);
var MANAGED_ROOT_KEYS = {
  packs: "pack:install",
  lanes: "lane:edit",
  security: "security:set",
  id: "workspace-init",
  name: "workspace-init",
  policies: "policy:set"
};

// ../core/dist/docs-layout-presets.js
function buildDocsLayout(operations, tasks) {
  const frameworkRoot = `${operations}/_frameworks/lumenflow`;
  const onboarding = `${frameworkRoot}/agent/onboarding`;
  return {
    operations,
    tasks,
    onboarding,
    quickRefLink: `${onboarding}/quick-ref-commands.md`,
    completeGuidePath: `${frameworkRoot}/lumenflow-complete.md`,
    quickRefPath: `${onboarding}/quick-ref-commands.md`,
    startingPromptPath: `${onboarding}/starting-prompt.md`,
    sizingGuidePath: `${frameworkRoot}/wu-sizing-guide.md`,
    governancePath: `${operations}/governance/project-governance.md`
  };
}
var DOCS_ROOT = "docs";
var SIMPLE_TASKS_PATH = `${DOCS_ROOT}/tasks`;
var ARC42_OPERATIONS_PATH = [DOCS_ROOT, "04-operations"].join("/");
var ARC42_TASKS_PATH = [ARC42_OPERATIONS_PATH, "tasks"].join("/");
var DOCS_LAYOUT_PRESETS = {
  simple: buildDocsLayout(DOCS_ROOT, SIMPLE_TASKS_PATH),
  arc42: buildDocsLayout(ARC42_OPERATIONS_PATH, ARC42_TASKS_PATH)
};
var DEFAULT_DOCS_LAYOUT = "simple";
function getDocsLayoutPreset(layout) {
  return DOCS_LAYOUT_PRESETS[layout];
}

// ../core/dist/client-ids.js
var LUMENFLOW_CLIENT_IDS = {
  CLAUDE_CODE: "claude-code",
  CODEX_CLI: "codex-cli",
  CURSOR: "cursor",
  GEMINI_CLI: "gemini-cli",
  WINDSURF: "windsurf"
};

// ../core/dist/resolve-policy.js
import { z } from "zod";
var TestingMethodologySchema = z.enum(["tdd", "test-after", "none"]);
var ArchitectureMethodologySchema = z.enum(["hexagonal", "layered", "none"]);
var CoverageModeSchema = z.enum(["block", "warn", "off"]);
var MethodologyOverridesSchema = z.object({
  /** Override the default coverage threshold from the testing methodology */
  coverage_threshold: z.number().min(0).max(100).optional(),
  /** Override the default coverage mode from the testing methodology */
  coverage_mode: CoverageModeSchema.optional()
});
var WorkClassificationUiSchema = z.object({
  /**
   * Additional glob patterns for detecting UI work via code paths.
   * These extend the built-in defaults (CSS, SCSS, LESS, components, pages, etc.).
   * Uses minimatch glob syntax.
   */
  code_path_patterns: z.array(z.string()).optional(),
  /**
   * Additional lane parent hints for detecting UI work.
   * These extend the built-in defaults (Experience, Frontend, UI, Design).
   * Matched case-insensitively against the lane parent (part before the colon).
   */
  lane_hints: z.array(z.string()).optional()
});
var WorkClassificationConfigSchema = z.object({
  /** UI detection pattern overrides (extend defaults) */
  ui: WorkClassificationUiSchema.optional()
});
var MethodologyConfigSchema = z.object({
  /** Testing methodology (default: 'tdd') */
  testing: TestingMethodologySchema.default("tdd"),
  /** Architecture methodology (default: 'hexagonal') */
  architecture: ArchitectureMethodologySchema.default("hexagonal"),
  /** Optional overrides for template defaults */
  overrides: MethodologyOverridesSchema.optional(),
  /**
   * WU-1899: Work classification configuration.
   * Extends default signal patterns for UI/backend/docs/infra detection.
   * Custom patterns extend defaults, they do not replace them.
   */
  work_classification: WorkClassificationConfigSchema.optional()
});
var TESTING_TEMPLATE_DEFAULTS = {
  tdd: {
    coverage_threshold: 90,
    coverage_mode: "block",
    tests_required: true
  },
  "test-after": {
    coverage_threshold: 70,
    coverage_mode: "warn",
    tests_required: true
  },
  none: {
    coverage_threshold: 0,
    coverage_mode: "off",
    tests_required: false
  }
};
function resolvePolicy(config, options = {}) {
  const { rawConfig } = options;
  const methodology = MethodologyConfigSchema.parse(config.methodology ?? {});
  const templateDefaults = TESTING_TEMPLATE_DEFAULTS[methodology.testing];
  let coverage_threshold = templateDefaults.coverage_threshold;
  let coverage_mode = templateDefaults.coverage_mode;
  const tests_required = templateDefaults.tests_required;
  if (methodology.overrides?.coverage_threshold !== void 0) {
    coverage_threshold = methodology.overrides.coverage_threshold;
  }
  if (methodology.overrides?.coverage_mode !== void 0) {
    coverage_mode = methodology.overrides.coverage_mode;
  }
  const gates = config.gates;
  const gatesMinCoverageExplicit = rawConfig !== void 0 ? rawConfig.gates?.minCoverage !== void 0 : false;
  const gatesEnableCoverageExplicit = rawConfig !== void 0 ? rawConfig.gates?.enableCoverage !== void 0 : false;
  const methodologySpecified = config.methodology !== void 0;
  if (gatesMinCoverageExplicit || !methodologySpecified && rawConfig === void 0) {
    coverage_threshold = gates.minCoverage;
  }
  if (gatesEnableCoverageExplicit || !methodologySpecified && rawConfig === void 0) {
    if (gates?.enableCoverage === false) {
      coverage_mode = "off";
    }
  }
  return {
    testing: methodology.testing,
    architecture: methodology.architecture,
    coverage_threshold,
    coverage_mode,
    tests_required
  };
}
function getDefaultPolicy() {
  return {
    testing: "tdd",
    architecture: "hexagonal",
    coverage_threshold: 90,
    coverage_mode: "block",
    tests_required: true
  };
}

// ../core/dist/schemas/workspace-config.js
import { z as z2 } from "zod";
var WorkspaceControlPlanePolicyModeSchema = z2.enum([
  "authoritative",
  "tighten-only",
  "dev-override"
]);
var CONTROL_PLANE_AUTH_TOKEN_ENV_PATTERN = /^[A-Z][A-Z0-9_]*$/;
var WorkspaceControlPlaneAuthConfigSchema = z2.object({
  token_env: z2.string().regex(CONTROL_PLANE_AUTH_TOKEN_ENV_PATTERN, "Expected uppercase environment variable name")
}).strict();
var WorkspaceControlPlaneConfigSchema = z2.object({
  endpoint: z2.string().url(),
  org_id: z2.string().min(1),
  project_id: z2.string().min(1),
  sync_interval: z2.number().int().positive(),
  policy_mode: WorkspaceControlPlanePolicyModeSchema,
  auth: WorkspaceControlPlaneAuthConfigSchema
}).strict();
var WorkspaceSoftwareDeliverySchema = z2.record(z2.string(), z2.unknown());
var WorkspaceV2ExtensionsSchema = z2.object({
  [WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY]: WorkspaceSoftwareDeliverySchema,
  [WORKSPACE_V2_KEYS.CONTROL_PLANE]: WorkspaceControlPlaneConfigSchema.optional()
});

// ../core/dist/constants/duration-constants.js
var MS_PER_SECOND = 1e3;
var MS_PER_MINUTE = 60 * MS_PER_SECOND;
var MS_PER_HOUR = 60 * MS_PER_MINUTE;
var MS_PER_DAY = 24 * MS_PER_HOUR;
var DURATION_MS = Object.freeze({
  /** 7 days in milliseconds (signal cleanup TTL for read signals) */
  SEVEN_DAYS: 7 * MS_PER_DAY,
  /** 30 days in milliseconds (signal cleanup TTL for unread signals, checkpoint TTL) */
  THIRTY_DAYS: 30 * MS_PER_DAY,
  /** 90 days in milliseconds (event archival threshold) */
  NINETY_DAYS: 90 * MS_PER_DAY
});

// ../core/dist/gates-presets.js
var GATE_PRESETS = {
  node: {
    setup: "npm ci || npm install",
    format: "npx prettier --check .",
    lint: "npx eslint .",
    typecheck: "npx tsc --noEmit",
    test: "npm test"
  },
  python: {
    setup: 'pip install -e ".[dev]" || pip install -r requirements.txt',
    format: "ruff format --check .",
    lint: "ruff check .",
    typecheck: "mypy .",
    test: "pytest"
  },
  go: {
    format: 'gofmt -l . | grep -v "^$" && exit 1 || exit 0',
    lint: "golangci-lint run",
    typecheck: "go vet ./...",
    test: "go test ./..."
  },
  rust: {
    format: "cargo fmt --check",
    lint: "cargo clippy -- -D warnings",
    typecheck: "cargo check",
    test: "cargo test"
  },
  dotnet: {
    setup: "dotnet restore",
    format: "dotnet format --verify-no-changes",
    lint: "dotnet build --no-restore -warnaserror",
    test: "dotnet test --no-restore"
  },
  // WU-1118: Java/JVM, Ruby, and PHP presets
  java: {
    format: "mvn spotless:check || ./gradlew spotlessCheck",
    lint: "mvn checkstyle:check || ./gradlew checkstyleMain",
    typecheck: "mvn compile -DskipTests || ./gradlew compileJava",
    test: "mvn test || ./gradlew test"
  },
  ruby: {
    setup: "bundle install",
    format: "bundle exec rubocop --format simple --fail-level W",
    lint: "bundle exec rubocop",
    test: "bundle exec rspec"
  },
  php: {
    setup: "composer install",
    format: "vendor/bin/php-cs-fixer fix --dry-run --diff",
    lint: "vendor/bin/phpstan analyse",
    test: "vendor/bin/phpunit"
  }
};

// ../core/dist/object-guards.js
var VALUE_TYPE = {
  OBJECT: "object",
  STRING: "string",
  NUMBER: "number",
  BOOLEAN: "boolean"
};
function asRecord(value) {
  return value && typeof value === VALUE_TYPE.OBJECT && !Array.isArray(value) ? value : null;
}
function isString(value) {
  return typeof value === VALUE_TYPE.STRING;
}
function isNumber(value) {
  return typeof value === VALUE_TYPE.NUMBER;
}
function isBoolean(value) {
  return typeof value === VALUE_TYPE.BOOLEAN;
}

// ../core/dist/gates-config-internal.js
import * as fs from "fs";
import * as path from "path";
import * as yaml from "yaml";
var DEFAULT_POLICY = getDefaultPolicy();
var GATES_RUNTIME_DEFAULTS = {
  COMMAND_TIMEOUT_MS: 12e4,
  MAX_ESLINT_WARNINGS: 100,
  DEFAULT_MIN_COVERAGE: DEFAULT_POLICY.coverage_threshold,
  DEFAULT_ENABLE_COVERAGE: true,
  DEFAULT_PACKAGE_MANAGER: "pnpm",
  DEFAULT_TEST_RUNNER: "vitest"
};
var SOFTWARE_DELIVERY_KEY = WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY;
var SOFTWARE_DELIVERY_FIELDS = {
  GATES: "gates",
  METHODOLOGY: "methodology",
  PACKAGE_MANAGER: "package_manager",
  PACKAGE_MANAGER_CAMEL: "packageManager",
  TEST_RUNNER: "test_runner",
  TEST_RUNNER_CAMEL: "testRunner",
  BUILD_COMMAND: "build_command",
  BUILD_COMMAND_CAMEL: "buildCommand"
};
var GATES_FIELDS = {
  EXECUTION: "execution",
  LANE_HEALTH: "lane_health",
  LANE_HEALTH_CAMEL: "laneHealth",
  MIN_COVERAGE: "minCoverage",
  MIN_COVERAGE_SNAKE: "min_coverage",
  ENABLE_COVERAGE: "enableCoverage",
  ENABLE_COVERAGE_SNAKE: "enable_coverage",
  COMMANDS: "commands"
};
var GATES_COMMAND_FIELDS = {
  TEST_FULL: "test_full",
  TEST_DOCS_ONLY: "test_docs_only",
  TEST_INCREMENTAL: "test_incremental",
  LINT: "lint",
  TYPECHECK: "typecheck",
  FORMAT: "format"
};
function loadSoftwareDeliveryConfig(projectRoot) {
  const configPath = path.join(projectRoot, WORKSPACE_CONFIG_FILE_NAME);
  if (!fs.existsSync(configPath)) {
    return null;
  }
  try {
    const content = fs.readFileSync(configPath, "utf8");
    const data = asRecord(yaml.parse(content));
    if (!data) {
      return null;
    }
    return asRecord(data[SOFTWARE_DELIVERY_KEY]);
  } catch {
    return null;
  }
}
function getGatesSection(projectRoot) {
  const softwareDelivery = loadSoftwareDeliveryConfig(projectRoot);
  if (!softwareDelivery) {
    return null;
  }
  return asRecord(softwareDelivery[SOFTWARE_DELIVERY_FIELDS.GATES]);
}

// ../core/dist/gates-coverage.js
function readNumberField(source, primaryKey, secondaryKey) {
  const primary = source?.[primaryKey];
  if (isNumber(primary)) {
    return primary;
  }
  const secondary = source?.[secondaryKey];
  return isNumber(secondary) ? secondary : void 0;
}
function readBooleanField(source, primaryKey, secondaryKey) {
  const primary = source?.[primaryKey];
  if (isBoolean(primary)) {
    return primary;
  }
  const secondary = source?.[secondaryKey];
  return isBoolean(secondary) ? secondary : void 0;
}
function readGateMinCoverage(gatesRaw) {
  return readNumberField(gatesRaw, GATES_FIELDS.MIN_COVERAGE, GATES_FIELDS.MIN_COVERAGE_SNAKE);
}
function readGateEnableCoverage(gatesRaw) {
  return readBooleanField(gatesRaw, GATES_FIELDS.ENABLE_COVERAGE, GATES_FIELDS.ENABLE_COVERAGE_SNAKE);
}
function resolvePolicyFromConfig(rawConfig) {
  const methodologyRaw = asRecord(rawConfig[SOFTWARE_DELIVERY_FIELDS.METHODOLOGY]) ?? void 0;
  const gatesRaw = asRecord(rawConfig[SOFTWARE_DELIVERY_FIELDS.GATES]) ?? void 0;
  const minCoverage = readGateMinCoverage(gatesRaw);
  const enableCoverage = readGateEnableCoverage(gatesRaw);
  const methodology = MethodologyConfigSchema.parse(methodologyRaw ?? {});
  const minimalConfig = {
    methodology: methodologyRaw,
    // Pass raw methodology for explicit detection
    gates: {
      minCoverage,
      enableCoverage
    }
  };
  return resolvePolicy({
    methodology,
    gates: {
      // Default gates values from schema
      maxEslintWarnings: GATES_RUNTIME_DEFAULTS.MAX_ESLINT_WARNINGS,
      enableCoverage: enableCoverage ?? GATES_RUNTIME_DEFAULTS.DEFAULT_ENABLE_COVERAGE,
      minCoverage: minCoverage ?? GATES_RUNTIME_DEFAULTS.DEFAULT_MIN_COVERAGE,
      enableSafetyCriticalTests: true,
      enableInvariants: true
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Minimal type for config
  }, {
    rawConfig: minimalConfig
  });
}
function resolveTestPolicy(projectRoot) {
  const rawConfig = loadSoftwareDeliveryConfig(projectRoot) ?? {};
  if (Object.keys(rawConfig).length === 0) {
    const defaultPolicy = getDefaultPolicy();
    return {
      threshold: defaultPolicy.coverage_threshold,
      mode: defaultPolicy.coverage_mode,
      tests_required: defaultPolicy.tests_required
    };
  }
  const policy = resolvePolicyFromConfig(rawConfig);
  return {
    threshold: policy.coverage_threshold,
    mode: policy.coverage_mode,
    tests_required: policy.tests_required
  };
}

// ../core/dist/package-manager-resolver.js
var SUPPORTED_PACKAGE_MANAGERS = ["pnpm", "npm", "yarn", "bun"];
var SUPPORTED_TEST_RUNNERS = ["vitest", "jest", "mocha"];
var DEFAULT_GATES_COMMANDS = {
  pnpm: {
    test_full: "pnpm turbo run test",
    test_docs_only: "",
    test_incremental: "pnpm vitest run --changed origin/main",
    lint: "pnpm lint",
    typecheck: "pnpm typecheck",
    format: "pnpm format:check"
  },
  npm: {
    test_full: "npm test",
    test_docs_only: "",
    test_incremental: "npm test -- --onlyChanged",
    lint: "npm run lint",
    typecheck: "npm run typecheck",
    format: "npm run format:check"
  },
  yarn: {
    test_full: "yarn test",
    test_docs_only: "",
    test_incremental: "yarn test --onlyChanged",
    lint: "yarn lint",
    typecheck: "yarn typecheck",
    format: "yarn format:check"
  },
  bun: {
    test_full: "bun test",
    test_docs_only: "",
    test_incremental: "bun test --changed",
    lint: "bun run lint",
    typecheck: "bun run typecheck",
    format: "bun run format:check"
  }
};
function resolvePackageManager(projectRoot) {
  const softwareDelivery = loadSoftwareDeliveryConfig(projectRoot);
  if (!softwareDelivery) {
    return GATES_RUNTIME_DEFAULTS.DEFAULT_PACKAGE_MANAGER;
  }
  const pm = softwareDelivery[SOFTWARE_DELIVERY_FIELDS.PACKAGE_MANAGER] ?? softwareDelivery[SOFTWARE_DELIVERY_FIELDS.PACKAGE_MANAGER_CAMEL];
  if (isString(pm) && SUPPORTED_PACKAGE_MANAGERS.includes(pm)) {
    return pm;
  }
  return GATES_RUNTIME_DEFAULTS.DEFAULT_PACKAGE_MANAGER;
}
function resolveTestRunner(projectRoot) {
  const softwareDelivery = loadSoftwareDeliveryConfig(projectRoot);
  if (!softwareDelivery) {
    return GATES_RUNTIME_DEFAULTS.DEFAULT_TEST_RUNNER;
  }
  const runner = softwareDelivery[SOFTWARE_DELIVERY_FIELDS.TEST_RUNNER] ?? softwareDelivery[SOFTWARE_DELIVERY_FIELDS.TEST_RUNNER_CAMEL];
  if (isString(runner) && SUPPORTED_TEST_RUNNERS.includes(runner)) {
    return runner;
  }
  return GATES_RUNTIME_DEFAULTS.DEFAULT_TEST_RUNNER;
}
function resolveGatesCommands(projectRoot) {
  const pm = resolvePackageManager(projectRoot);
  const defaults = DEFAULT_GATES_COMMANDS[pm];
  const gates = getGatesSection(projectRoot);
  if (!gates) {
    return defaults;
  }
  const commands = asRecord(gates[GATES_FIELDS.COMMANDS]);
  if (!commands) {
    return defaults;
  }
  return {
    test_full: commands[GATES_COMMAND_FIELDS.TEST_FULL] ?? defaults.test_full,
    test_docs_only: commands[GATES_COMMAND_FIELDS.TEST_DOCS_ONLY] ?? defaults.test_docs_only,
    test_incremental: commands[GATES_COMMAND_FIELDS.TEST_INCREMENTAL] ?? defaults.test_incremental,
    lint: commands[GATES_COMMAND_FIELDS.LINT] ?? defaults.lint,
    typecheck: commands[GATES_COMMAND_FIELDS.TYPECHECK] ?? defaults.typecheck,
    format: commands[GATES_COMMAND_FIELDS.FORMAT] ?? defaults.format
  };
}

// ../core/dist/gates-schemas.js
import { z as z3 } from "zod";
var GateCommandObjectSchema = z3.object({
  /** The shell command to execute */
  command: z3.string(),
  /** Whether to continue if this gate fails (default: false) */
  continueOnError: z3.boolean().optional(),
  /** Timeout in milliseconds */
  timeout: z3.number().int().positive().optional()
});
var GateCommandConfigSchema = z3.union([z3.string(), GateCommandObjectSchema]);
var GatesExecutionConfigSchema = z3.object({
  /** Preset to use for default commands (node, python, go, rust, dotnet) */
  preset: z3.string().optional(),
  /** Setup command (e.g., install dependencies) */
  setup: GateCommandConfigSchema.optional(),
  /** Format check command */
  format: GateCommandConfigSchema.optional(),
  /** Lint command */
  lint: GateCommandConfigSchema.optional(),
  /** Type check command */
  typecheck: GateCommandConfigSchema.optional(),
  /** Test command */
  test: GateCommandConfigSchema.optional(),
  /** Coverage configuration */
  coverage: z3.union([
    z3.string(),
    z3.object({
      command: z3.string(),
      threshold: z3.number().min(0).max(100).optional()
    })
  ]).optional()
});
var LaneHealthModeSchema = z3.enum(["warn", "error", "off"]);
var DEFAULT_LANE_HEALTH_MODE = "warn";

// ../core/dist/gates-config.js
var SOFTWARE_DELIVERY_KEY2 = WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY;
function loadLaneHealthConfig(projectRoot) {
  const gates = getGatesSection(projectRoot);
  if (!gates) {
    return DEFAULT_LANE_HEALTH_MODE;
  }
  try {
    const laneHealthConfig = gates[GATES_FIELDS.LANE_HEALTH] ?? gates[GATES_FIELDS.LANE_HEALTH_CAMEL];
    if (laneHealthConfig === void 0) {
      return DEFAULT_LANE_HEALTH_MODE;
    }
    const result = LaneHealthModeSchema.safeParse(laneHealthConfig);
    if (!result.success) {
      console.warn(`Warning: Invalid gates.lane_health value '${laneHealthConfig}', expected 'warn', 'error', or 'off'. Using default 'warn'.`);
      return DEFAULT_LANE_HEALTH_MODE;
    }
    return result.data;
  } catch (error) {
    console.warn(`Warning: Failed to parse ${WORKSPACE_CONFIG_FILE_NAME} ${SOFTWARE_DELIVERY_KEY2}.gates.lane_health:`, error instanceof Error ? error.message : String(error));
    return DEFAULT_LANE_HEALTH_MODE;
  }
}

// ../core/dist/lumenflow-config-schema.js
import { z as z13 } from "zod";

// ../core/dist/schemas/directories-config.js
import { z as z4 } from "zod";
var DEFAULT_LAYOUT = DOCS_LAYOUT_PRESETS.simple;
var EventArchivalConfigSchema = z4.object({
  /**
   * Archive events older than this duration in milliseconds (default: 90 days).
   * Completed WU events older than this are moved to monthly archive files.
   * Active WU events (in_progress/blocked/waiting) are never archived.
   */
  archiveAfter: z4.number().int().positive().default(DURATION_MS.NINETY_DAYS),
  /**
   * Whether to keep archive files (default: true).
   * When true, archived events are preserved in monthly archive files.
   * When false, archived events are deleted (not recommended for audit trails).
   */
  keepArchives: z4.boolean().default(true)
});
var DirectoriesSchema = z4.object({
  /** Working directory for web app (default: 'apps/web/') */
  appsWeb: z4.string().default("apps/web/"),
  /** Worktrees directory (default: 'worktrees/') */
  worktrees: z4.string().default("worktrees/"),
  /** AI assets directory (default: 'ai/') */
  ai: z4.string().default("ai/"),
  /** Claude configuration directory (default: '.claude/') */
  claude: z4.string().default(".claude/"),
  /** Documentation root (default: 'docs/') */
  docs: z4.string().default("docs/"),
  /** Packages directory (default: 'packages/') */
  packages: z4.string().default("packages/"),
  /** Tools directory (default: 'tools/') */
  tools: z4.string().default("tools/"),
  /** Memory bank directory (default: 'memory-bank/') */
  memoryBank: z4.string().default("memory-bank/"),
  /** WU YAML files directory (default: docs-layout simple preset + '/wu') */
  wuDir: z4.string().default(`${DEFAULT_LAYOUT.tasks}/wu`),
  /** Initiatives directory (default: docs-layout simple preset + '/initiatives') */
  initiativesDir: z4.string().default(`${DEFAULT_LAYOUT.tasks}/initiatives`),
  /** Backlog file path (default: docs-layout simple preset + '/backlog.md') */
  backlogPath: z4.string().default(`${DEFAULT_LAYOUT.tasks}/backlog.md`),
  /** Status file path (default: docs-layout simple preset + '/status.md') */
  statusPath: z4.string().default(`${DEFAULT_LAYOUT.tasks}/status.md`),
  /** Skills directory (default: '.claude/skills') */
  skillsDir: z4.string().default(".claude/skills"),
  /** Agents directory (default: '.claude/agents') */
  agentsDir: z4.string().default(".claude/agents"),
  /** Plans directory (default: docs-layout simple preset + '/plans') */
  plansDir: z4.string().default(`${DEFAULT_LAYOUT.operations}/plans`),
  /** Templates directory (default: '.lumenflow/templates') */
  templatesDir: z4.string().default(".lumenflow/templates"),
  /** Onboarding directory (default: docs-layout simple preset onboarding path) */
  onboardingDir: z4.string().default(DEFAULT_LAYOUT.onboarding),
  /** LumenFlow complete guide path (default: docs-layout simple preset complete guide path) */
  completeGuidePath: z4.string().default(DEFAULT_LAYOUT.completeGuidePath),
  /** Agent quick reference commands path (default: docs-layout simple preset quick-ref path) */
  quickRefPath: z4.string().default(DEFAULT_LAYOUT.quickRefPath),
  /** Agent starting prompt path (default: docs-layout simple preset starting prompt path) */
  startingPromptPath: z4.string().default(DEFAULT_LAYOUT.startingPromptPath),
  /** WU sizing guide path (default: docs-layout simple preset sizing guide path) */
  sizingGuidePath: z4.string().default(DEFAULT_LAYOUT.sizingGuidePath),
  /** Project governance document path (default: docs-layout simple preset governance path) */
  governancePath: z4.string().default(DEFAULT_LAYOUT.governancePath),
  /** Safe-git wrapper path relative to project root (default: 'scripts/safe-git') - WU-1654 */
  safeGitPath: z4.string().default("scripts/safe-git")
});
var StatePathsSchema = z4.object({
  /** Base state directory (default: '.lumenflow') */
  base: z4.string().default(".lumenflow"),
  /** State directory (default: '.lumenflow/state') */
  stateDir: z4.string().default(".lumenflow/state"),
  /** Archive directory (default: '.lumenflow/archive') */
  archiveDir: z4.string().default(".lumenflow/archive"),
  /** Stamps directory (default: '.lumenflow/stamps') */
  stampsDir: z4.string().default(".lumenflow/stamps"),
  /** Merge lock file (default: '.lumenflow/merge.lock') */
  mergeLock: z4.string().default(".lumenflow/merge.lock"),
  /** Telemetry directory (default: '.lumenflow/telemetry') */
  telemetry: z4.string().default(".lumenflow/telemetry"),
  /** Flow log file (default: '.lumenflow/flow.log') */
  flowLog: z4.string().default(".lumenflow/flow.log"),
  /** Sessions directory (default: '.lumenflow/sessions') */
  sessions: z4.string().default(".lumenflow/sessions"),
  /** Incidents directory (default: '.lumenflow/incidents') */
  incidents: z4.string().default(".lumenflow/incidents"),
  /** Commands log file (default: '.lumenflow/commands.log') */
  commandsLog: z4.string().default(".lumenflow/commands.log"),
  /**
   * WU-1207: Event archival configuration
   * Controls archival of old WU events to prevent unbounded growth.
   */
  eventArchival: EventArchivalConfigSchema.default(() => EventArchivalConfigSchema.parse({}))
});

// ../core/dist/schemas/git-config.js
import { z as z5 } from "zod";
var PushRetryConfigSchema = z5.object({
  /**
   * Enable push retry with rebase on non-fast-forward errors.
   * When true, failed pushes trigger automatic rebase and retry.
   * When false, the original error is thrown immediately.
   * @default true
   */
  enabled: z5.boolean().default(true),
  /**
   * Maximum number of retry attempts (including the initial attempt).
   * After this many failures, the operation fails with clear guidance.
   * @default 3
   */
  retries: z5.number().int().positive().default(3),
  /**
   * Minimum delay in milliseconds between retries.
   * Used as the base for exponential backoff.
   * @default 100
   */
  min_delay_ms: z5.number().int().nonnegative().default(100),
  /**
   * Maximum delay in milliseconds between retries.
   * Caps the exponential backoff to prevent excessive waits.
   * @default 1000
   */
  max_delay_ms: z5.number().int().positive().default(1e3),
  /**
   * Add randomization to retry delays (recommended for concurrent agents).
   * Helps prevent thundering herd when multiple agents retry simultaneously.
   * @default true
   */
  jitter: z5.boolean().default(true)
});
var GitConfigSchema = z5.object({
  /** Main branch name (default: 'main') */
  mainBranch: z5.string().default("main"),
  /** Default remote name (default: 'origin') */
  defaultRemote: z5.string().default("origin"),
  /** Lane branch prefix (default: 'lane/') */
  laneBranchPrefix: z5.string().default("lane/"),
  /** Temporary branch prefix (default: 'tmp/') */
  tempBranchPrefix: z5.string().default("tmp/"),
  /** Real git executable path (default: '/usr/bin/git') */
  realGitPath: z5.string().default("/usr/bin/git"),
  /** Maximum commits behind main before requiring rebase */
  maxBranchDrift: z5.number().int().positive().default(20),
  /** Warning threshold for branch drift */
  branchDriftWarning: z5.number().int().positive().default(15),
  /** Info threshold for branch drift */
  branchDriftInfo: z5.number().int().positive().default(10),
  /**
   * WU-1302: Require a remote repository for wu:create and wu:claim.
   * When true (default), operations fail if no remote 'origin' exists.
   * When false, operations can proceed locally without pushing.
   *
   * Use `git.requireRemote: false` for:
   * - Local-only development before remote is set up
   * - Air-gapped environments
   * - Testing/evaluation of LumenFlow
   *
   * @default true
   *
   * @example
   * ```yaml
   * git:
   *   requireRemote: false  # Allow offline/local mode
   * ```
   */
  requireRemote: z5.boolean().default(true),
  /**
   * Agent branch patterns to MERGE with the registry patterns.
   * These patterns are merged with patterns from lumenflow.dev/registry/agent-patterns.json.
   * Use this to add custom patterns that should work alongside the standard vendor patterns.
   * Protected branches (mainBranch + 'master') are NEVER bypassed.
   *
   * WU-1089: Changed default from ['agent/*'] to [] to allow registry to be used by default.
   *
   * @example
   * ```yaml
   * git:
   *   agentBranchPatterns:
   *     - 'my-custom-agent/*'
   *     - 'internal-tool/*'
   * ```
   */
  agentBranchPatterns: z5.array(z5.string()).default([]),
  /**
   * Agent branch patterns that REPLACE the registry patterns entirely.
   * When set, these patterns are used instead of fetching from the registry.
   * The agentBranchPatterns field is ignored when this is set.
   *
   * Use this for strict control over which agent patterns are allowed.
   *
   * @example
   * ```yaml
   * git:
   *   agentBranchPatternsOverride:
   *     - 'claude/*'
   *     - 'codex/*'
   * ```
   */
  agentBranchPatternsOverride: z5.array(z5.string()).optional(),
  /**
   * Disable fetching agent patterns from the registry (airgapped mode).
   * When true, only uses agentBranchPatterns from config or defaults to ['agent/*'].
   * Useful for environments without network access or strict security requirements.
   *
   * @default false
   *
   * @example
   * ```yaml
   * git:
   *   disableAgentPatternRegistry: true
   *   agentBranchPatterns:
   *     - 'claude/*'
   *     - 'cursor/*'
   * ```
   */
  disableAgentPatternRegistry: z5.boolean().default(false),
  /**
   * WU-1332: Push retry configuration for micro-worktree operations.
   * When push fails due to non-fast-forward (origin moved), automatically
   * rebase and retry with exponential backoff.
   *
   * @example
   * ```yaml
   * git:
   *   push_retry:
   *     enabled: true
   *     retries: 5        # Try 5 times total
   *     min_delay_ms: 200 # Start with 200ms delay
   *     max_delay_ms: 2000 # Cap at 2 second delay
   *     jitter: true      # Add randomization
   * ```
   */
  push_retry: PushRetryConfigSchema.default(() => PushRetryConfigSchema.parse({}))
});

// ../core/dist/schemas/wu-config.js
import { z as z6 } from "zod";
var WuBriefPolicyModeSchema = z6.enum(["off", "manual", "auto", "required"]);
var WuBriefConfigSchema = z6.object({
  /** Claim-time wu:brief policy mode (default: 'auto') */
  policyMode: WuBriefPolicyModeSchema.default("auto"),
  /**
   * Brief freshness threshold in minutes.
   * Set to 0 to disable freshness checks.
   */
  freshnessMinutes: z6.number().int().nonnegative().default(1440)
});
var WuConfigSchema = z6.object({
  /** WU ID pattern (regex string, default: '^WU-\\d+$') */
  idPattern: z6.string().default("^WU-\\d+$"),
  /** Minimum description length (default: 50) */
  minDescriptionLength: z6.number().int().nonnegative().default(50),
  /** Maximum commit subject length (default: 100) */
  maxCommitSubject: z6.number().int().positive().default(100),
  /** Default priority (default: 'P2') */
  defaultPriority: z6.string().default("P2"),
  /** Default status (default: 'ready') */
  defaultStatus: z6.string().default("ready"),
  /** Default type (default: 'feature') */
  defaultType: z6.string().default("feature"),
  /** wu:brief policy configuration */
  brief: WuBriefConfigSchema.default(() => WuBriefConfigSchema.parse({}))
});

// ../core/dist/schemas/gates-section-config.js
import { z as z7 } from "zod";

// ../core/dist/constants/gate-constants.js
var GATE_CONFIG = {
  /** Maximum execution time per gate step (ms) */
  TIMEOUT_MS: 18e4,
  /** Maximum file size allowed in commits (bytes) - 5MB */
  MAX_FILE_SIZE_BYTES: 5 * 1024 * 1024,
  /** Total number of gates (for progress display) */
  TOTAL_GATES: 14
};
var DEFAULT_MIN_COVERAGE = 90;
var DEFAULT_MAX_ESLINT_WARNINGS = 100;

// ../core/dist/schemas/gates-section-config.js
var GatesCommandsConfigSchema = z7.object({
  /**
   * Command to run full test suite.
   * Default: 'pnpm turbo run test'
   */
  test_full: z7.string().default("pnpm turbo run test"),
  /**
   * Command to run tests in docs-only mode.
   * Default: empty (skip tests in docs-only mode)
   */
  test_docs_only: z7.string().default(""),
  /**
   * Command to run incremental tests (changed files only).
   * Default: 'pnpm vitest run --changed origin/main'
   */
  test_incremental: z7.string().default("pnpm vitest run --changed origin/main"),
  /**
   * Command to run lint checks.
   * Default: 'pnpm lint'
   */
  lint: z7.string().optional(),
  /**
   * Command to run type checks.
   * Default: 'pnpm typecheck'
   */
  typecheck: z7.string().optional(),
  /**
   * Command to run format checks.
   * Default: 'pnpm format:check'
   */
  format: z7.string().optional()
});
var CoChangeSeveritySchema = z7.enum(["warn", "error", "off"]);
var CoChangeRuleConfigSchema = z7.object({
  name: z7.string().min(1),
  trigger_patterns: z7.array(z7.string().min(1)).min(1),
  require_patterns: z7.array(z7.string().min(1)).min(1),
  severity: CoChangeSeveritySchema.default("error")
});
var GatesConfigSchema = z7.object({
  /** Maximum ESLint warnings allowed (default: 100) */
  maxEslintWarnings: z7.number().int().nonnegative().default(DEFAULT_MAX_ESLINT_WARNINGS),
  /** Enable coverage gate (default: true) */
  enableCoverage: z7.boolean().default(true),
  /** Minimum coverage percentage (default: 90) */
  minCoverage: z7.number().min(0).max(100).default(DEFAULT_MIN_COVERAGE),
  /** Enable safety-critical tests (default: true) */
  enableSafetyCriticalTests: z7.boolean().default(true),
  /** Enable invariants check (default: true) */
  enableInvariants: z7.boolean().default(true),
  /**
   * WU-1067: Config-driven gates execution
   * Custom commands for each gate, with optional preset expansion.
   * When set, gates runner uses these instead of hardcoded commands.
   */
  execution: GatesExecutionConfigSchema.optional(),
  /**
   * WU-1356: Configurable gate commands
   * Replaces hard-coded turbo/vitest commands with user-configurable alternatives.
   * Enables LumenFlow to work with npm/yarn/bun, Nx/plain scripts, Jest/Mocha, etc.
   */
  commands: GatesCommandsConfigSchema.default(() => GatesCommandsConfigSchema.parse({})),
  /**
   * WU-1356: Ignore patterns for test runners
   * Patterns to ignore when detecting changed tests.
   * Default: ['.turbo'] for vitest (derived from test_runner if not specified)
   */
  ignore_patterns: z7.array(z7.string()).optional(),
  /**
   * WU-1191: Lane health gate mode
   * Controls how lane health check behaves during gates.
   * - 'warn': Log warning if issues found (default)
   * - 'error': Fail gates if issues found
   * - 'off': Skip lane health check
   */
  lane_health: z7.enum(["warn", "error", "off"]).default("warn"),
  /**
   * WU-2158: Generic co-change rule set.
   * Each rule enforces that when trigger_patterns match changed files,
   * at least one require_patterns file must also be changed.
   */
  co_change: z7.array(CoChangeRuleConfigSchema).default([])
});

// ../core/dist/schemas/memory-config.js
import { z as z8 } from "zod";
var ProgressSignalsConfigSchema = z8.object({
  /**
   * Enable mandatory progress signals in spawn prompts.
   * When true, spawn prompts show "Progress Signals (Required at Milestones)"
   * When false, spawn prompts show "Progress Signals (Optional)"
   * @default false
   */
  enabled: z8.boolean().default(false),
  /**
   * Send progress signals every N tool calls.
   * Set to 0 to disable frequency-based signals.
   * @default 0
   */
  frequency: z8.number().int().nonnegative().default(0),
  /**
   * Signal after each acceptance criterion is completed.
   * @default true
   */
  on_milestone: z8.boolean().default(true),
  /**
   * Signal when tests first pass.
   * @default true
   */
  on_tests_pass: z8.boolean().default(true),
  /**
   * Signal before running gates.
   * @default true
   */
  before_gates: z8.boolean().default(true),
  /**
   * Signal when work is blocked.
   * @default true
   */
  on_blocked: z8.boolean().default(true),
  /**
   * Automatically checkpoint memory at signal milestones.
   * @default false
   */
  auto_checkpoint: z8.boolean().default(false)
});
var SignalCleanupConfigSchema = z8.object({
  /**
   * TTL for read signals in milliseconds (default: 7 days).
   * Read signals older than this are removed during cleanup.
   */
  ttl: z8.number().int().positive().default(DURATION_MS.SEVEN_DAYS),
  /**
   * TTL for unread signals in milliseconds (default: 30 days).
   * Unread signals get a longer TTL to ensure important signals aren't missed.
   */
  unreadTtl: z8.number().int().positive().default(DURATION_MS.THIRTY_DAYS),
  /**
   * Maximum number of signals to retain (default: 500).
   * When exceeded, oldest signals are removed first (keeping newest).
   * Active WU signals are always retained regardless of this limit.
   */
  maxEntries: z8.number().int().positive().default(500)
});
var AutoCheckpointConfigSchema = z8.object({
  /**
   * Enable auto-checkpoint hooks.
   * When true (and hooks master switch is enabled), generates PostToolUse
   * and SubagentStop hooks that create checkpoints automatically.
   * @default false
   */
  enabled: z8.boolean().default(false),
  /**
   * Number of tool calls between automatic checkpoints.
   * The hook script tracks a per-WU counter and checkpoints
   * when the counter reaches this interval.
   * @default 30
   */
  interval_tool_calls: z8.number().int().positive().default(30)
});
var MemoryEnforcementConfigSchema = z8.object({
  /**
   * Auto-checkpoint configuration.
   * Controls automatic checkpointing via hooks.
   */
  auto_checkpoint: AutoCheckpointConfigSchema.default(() => AutoCheckpointConfigSchema.parse({})),
  /**
   * Checkpoint requirement for wu:done.
   * - 'off': No checkpoint check during wu:done
   * - 'warn': Warn if no checkpoints exist (default, fail-open)
   * - 'block': Block wu:done if no checkpoints exist
   * @default 'warn'
   */
  require_checkpoint_for_done: z8.enum(["off", "warn", "block"]).default("warn")
});
var MemoryDecayConfigSchema = z8.object({
  /**
   * Enable decay-based archival.
   * When false, no automatic archival is triggered.
   * @default false
   */
  enabled: z8.boolean().default(false),
  /**
   * Decay score threshold below which nodes are archived.
   * Nodes with a decay score below this value are marked as archived.
   * Must be between 0 and 1 inclusive.
   * @default 0.1
   */
  threshold: z8.number().min(0).max(1).default(0.1),
  /**
   * Half-life for decay scoring in days.
   * Controls how quickly nodes lose relevance over time.
   * Must be a positive integer.
   * @default 30
   */
  half_life_days: z8.number().int().positive().default(30),
  /**
   * When to trigger decay archival.
   * - 'on_done': Run during wu:done completion lifecycle
   * - 'manual': Only run via pnpm mem:cleanup
   * @default 'on_done'
   */
  trigger: z8.enum(["on_done", "manual"]).default("on_done")
});
var MEMORY_CONFIG_ERRORS = {
  DEPRECATED_SPAWN_CONTEXT_MAX_SIZE: "memory.spawn_context_max_size is no longer supported. Use memory.delegation_context_max_size instead."
};
var MemoryConfigSchema = z8.object({
  /** Memory directory (default: 'memory-bank/') */
  directory: z8.string().default("memory-bank/"),
  /** Session TTL in milliseconds (default: 7 days) */
  sessionTtl: z8.number().int().positive().default(DURATION_MS.SEVEN_DAYS),
  /** Checkpoint TTL in milliseconds (default: 30 days) */
  checkpointTtl: z8.number().int().positive().default(DURATION_MS.THIRTY_DAYS),
  /** Enable auto-cleanup (default: true) */
  enableAutoCleanup: z8.boolean().default(true),
  /**
   * WU-1203: Progress signals configuration for sub-agent coordination.
   * Optional - when not provided, spawn prompts show "Progress Signals (Optional)".
   */
  progress_signals: ProgressSignalsConfigSchema.optional(),
  /**
   * WU-1204: Signal cleanup configuration
   * Controls TTL-based cleanup for signals.jsonl to prevent unbounded growth.
   */
  signalCleanup: SignalCleanupConfigSchema.default(() => SignalCleanupConfigSchema.parse({})),
  /**
   * WU-1674: Maximum size in bytes for delegation memory context.
   * Controls the maximum size of memory context injected into delegation prompts.
   * Larger values include more context but increase token usage.
   * @default 4096 (4KB)
   */
  delegation_context_max_size: z8.number().int().positive().default(4096),
  /**
   * Deprecated key hard-fail for clean-slate cutover.
   * Keep this as an explicit validator so users get a direct migration message.
   */
  spawn_context_max_size: z8.unknown().optional().refine((value) => value === void 0, {
    message: MEMORY_CONFIG_ERRORS.DEPRECATED_SPAWN_CONTEXT_MAX_SIZE
  }),
  /**
   * WU-1471: Memory enforcement configuration.
   * Controls auto-checkpointing and checkpoint requirements for wu:done.
   * Optional - when not provided, existing WU-1943 warn behavior applies.
   */
  enforcement: MemoryEnforcementConfigSchema.optional(),
  /**
   * WU-1474: Decay policy configuration.
   * Controls automated archival of stale memory nodes during lifecycle events.
   * Optional - when not provided, no automatic decay archival runs.
   */
  decay: MemoryDecayConfigSchema.optional()
});

// ../core/dist/schemas/agents-config.js
import { z as z9 } from "zod";
var DEFAULT_METHODOLOGY_PRINCIPLES = [
  "TDD",
  "Hexagonal Architecture",
  "SOLID",
  "DRY",
  "YAGNI",
  "KISS",
  "Library-First"
];
var MethodologyDefaultsSchema = z9.object({
  /** Enable or disable project defaults output */
  enabled: z9.boolean().default(true),
  /** Whether defaults are required or recommended */
  enforcement: z9.enum(["required", "recommended"]).default("required"),
  /** Default methodology principles to apply */
  principles: z9.array(z9.string()).default(DEFAULT_METHODOLOGY_PRINCIPLES),
  /** Optional notes appended to Project Defaults */
  notes: z9.string().optional()
});
var ClientBlockSchema = z9.object({
  /** Block title */
  title: z9.string(),
  /** Block content (markdown allowed) */
  content: z9.string()
});
var ClientSkillsSchema = z9.object({
  /** Optional skills selection guidance text */
  instructions: z9.string().optional(),
  /** Recommended skills to load for this client */
  recommended: z9.array(z9.string()).default([]),
  /**
   * WU-1142: Lane-specific skills to recommend
   * Maps lane names to arrays of skill names
   * @example
   * byLane:
   *   'Framework: Core': ['tdd-workflow', 'lumenflow-gates']
   *   'Content: Documentation': ['worktree-discipline']
   */
  byLane: z9.record(z9.string(), z9.array(z9.string())).optional()
});
var ClientEnforcementSchema = z9.object({
  /**
   * Enable enforcement hooks.
   * When true, hooks are generated in .claude/hooks/
   * @default false
   */
  hooks: z9.boolean().default(false),
  /**
   * Block Write/Edit operations when cwd is not a worktree.
   * Prevents accidental edits to main checkout.
   * @default false
   */
  block_outside_worktree: z9.boolean().default(false),
  /**
   * Require a claimed WU for Write/Edit operations.
   * Ensures all edits are associated with tracked work.
   * @default false
   */
  require_wu_for_edits: z9.boolean().default(false),
  /**
   * Warn when session ends without wu:done being called.
   * Reminds agents to complete their work properly.
   * @default false
   */
  warn_on_stop_without_wu_done: z9.boolean().default(false)
});
var ClientConfigSchema = z9.object({
  /** Preamble file path (e.g. 'CLAUDE.md') or false to disable */
  preamble: z9.union([z9.string(), z9.boolean()]).optional(),
  /** Skills directory path */
  skillsDir: z9.string().optional(),
  /** Agents directory path */
  agentsDir: z9.string().optional(),
  /** Client-specific blocks injected into wu:spawn output */
  blocks: z9.array(ClientBlockSchema).default([]),
  /** Client-specific skills guidance for wu:spawn */
  skills: ClientSkillsSchema.optional(),
  /**
   * WU-1367: Enforcement configuration for Claude Code hooks.
   * When enabled, generates hooks that enforce workflow compliance.
   */
  enforcement: ClientEnforcementSchema.optional(),
  /**
   * WU-1900: Capability-to-skill mapping for classifier-driven skill suggestions.
   * Maps abstract capability tags from the work classifier to client-specific skill names.
   *
   * @example
   * ```yaml
   * agents:
   *   clients:
   *     claude-code:
   *       capabilities_map:
   *         ui-design-awareness: frontend-design
   *         component-reuse-check: library-first
   * ```
   */
  capabilities_map: z9.record(z9.string(), z9.string()).optional()
});
var AgentsConfigSchema = z9.object({
  /** Default client to use if not specified (configure per project; bootstrap default: 'claude-code') */
  defaultClient: z9.string().default(LUMENFLOW_CLIENT_IDS.CLAUDE_CODE),
  /** Client-specific configurations */
  clients: z9.record(z9.string(), ClientConfigSchema).default({}),
  /** Project methodology defaults (agent-facing) */
  methodology: MethodologyDefaultsSchema.default(() => MethodologyDefaultsSchema.parse({}))
});

// ../core/dist/schemas/lanes-config.js
import { z as z10 } from "zod";
var LockPolicySchema = z10.enum(["all", "active", "none"]).default("all");
var LanesEnforcementSchema = z10.object({
  /**
   * When true, lanes MUST use "Parent: Sublane" format if parent has taxonomy.
   * @default true
   */
  require_parent: z10.boolean().default(true),
  /**
   * When false, only lanes in the taxonomy are allowed.
   * When true, custom lanes can be used.
   * @default false
   */
  allow_custom: z10.boolean().default(false)
});
var LaneLifecycleStatusSchema = z10.enum(["unconfigured", "draft", "locked"]);
var LaneLifecycleSchema = z10.object({
  status: LaneLifecycleStatusSchema,
  updated_at: z10.string().optional(),
  migrated_at: z10.string().optional(),
  migration_reason: z10.string().optional()
});
var LaneDefinitionSchema = z10.object({
  /** Lane name in "Parent: Sublane" format (e.g., "Framework: Core") */
  name: z10.string(),
  /** WU-1016: Maximum WUs allowed in progress concurrently for this lane */
  wip_limit: z10.number().int().positive().optional(),
  /** WU-1187: Required justification when wip_limit > 1 */
  wip_justification: z10.string().optional(),
  /**
   * WU-1322: Lock policy for this lane.
   * - 'all': Lock lane for all other agents (default)
   * - 'active': Lock only for agents with overlapping code_paths
   * - 'none': No locking (suitable for documentation lanes)
   *
   * @default 'all'
   *
   * @example
   * ```yaml
   * lanes:
   *   definitions:
   *     - name: 'Content: Documentation'
   *       wip_limit: 4
   *       lock_policy: 'none'  # Docs can be worked in parallel
   * ```
   */
  lock_policy: LockPolicySchema.default("all"),
  /** Code paths associated with this lane (glob patterns) */
  code_paths: z10.array(z10.string()).optional()
});
var LanesConfigSchema = z10.object({
  /** Lane enforcement configuration (validation rules) */
  enforcement: LanesEnforcementSchema.optional(),
  /** WU-1748: Deferred lane lifecycle state */
  lifecycle: LaneLifecycleSchema.optional(),
  /** Primary lane definitions array (recommended format) */
  definitions: z10.array(LaneDefinitionSchema).optional(),
  /** Engineering lanes (alternate format) */
  engineering: z10.array(LaneDefinitionSchema).optional(),
  /** Business lanes (alternate format) */
  business: z10.array(LaneDefinitionSchema).optional()
});

// ../core/dist/schemas/cloud-config.js
import { z as z11 } from "zod";
var CloudEnvSignalSchema = z11.object({
  /**
   * Environment variable name to check.
   * Must be non-empty.
   */
  name: z11.string().min(1),
  /**
   * Optional exact value to match against.
   * When omitted, presence of a non-empty value is sufficient.
   */
  equals: z11.string().optional()
});
var CloudConfigSchema = z11.object({
  /**
   * Enable env-signal auto-detection for cloud mode.
   * When false (default), only explicit activation (--cloud / LUMENFLOW_CLOUD=1) works.
   * When true, env_signals are also checked.
   * @default false
   */
  auto_detect: z11.boolean().default(false),
  /**
   * Environment signals to check when auto_detect is true.
   * Each signal defines an environment variable name and optional value constraint.
   * Signals are checked in order; first match activates cloud mode.
   * @default []
   */
  env_signals: z11.array(CloudEnvSignalSchema).default([])
});

// ../core/dist/schemas/operational-config.js
import { z as z12 } from "zod";
var PackageManagerSchema = z12.enum(["pnpm", "npm", "yarn", "bun"]).default("pnpm");
var TestRunnerSchema = z12.enum(["vitest", "jest", "mocha"]).default("vitest");
var UiConfigSchema = z12.object({
  /** Error box width (default: 70) */
  errorBoxWidth: z12.number().int().positive().default(70),
  /** Status preview lines (default: 5) */
  statusPreviewLines: z12.number().int().positive().default(5),
  /** Readiness box width (default: 50) */
  readinessBoxWidth: z12.number().int().positive().default(50)
});
var YamlConfigSchema = z12.object({
  /** Line width for YAML output (default: 100, -1 for no wrap) */
  lineWidth: z12.number().int().default(100)
});
var ValidationModeSchema = z12.enum(["off", "warn", "error"]).default("warn");
var ExperimentalConfigSchema = z12.object({
  /**
   * Enable context-aware validation for wu:* commands
   * When enabled, commands will check location, WU status, and predicates
   * @default true
   */
  context_validation: z12.boolean().default(true),
  /**
   * Validation behavior mode
   * - 'off': No validation (legacy behavior)
   * - 'warn': Show warnings but proceed
   * - 'error': Block on validation failures
   * @default 'warn'
   */
  validation_mode: ValidationModeSchema,
  /**
   * Show next steps guidance after successful command completion
   * @default true
   */
  show_next_steps: z12.boolean().default(true),
  /**
   * Enable wu:recover command for state recovery
   * @default true
   */
  recovery_command: z12.boolean().default(true)
});
var MethodologyTelemetryConfigSchema = z12.object({
  /**
   * Enable methodology telemetry (opt-in).
   * When true, tracks methodology.testing and methodology.architecture values
   * on wu:spawn events. Data is privacy-preserving (no PII/project info).
   * @default false
   */
  enabled: z12.boolean().default(false)
});
var TelemetryConfigSchema = z12.object({
  /**
   * Methodology telemetry configuration (opt-in).
   * Tracks methodology selection patterns for adoption insights.
   */
  methodology: MethodologyTelemetryConfigSchema.default(() => MethodologyTelemetryConfigSchema.parse({}))
});
var CleanupTriggerSchema = z12.enum(["on_done", "on_init", "manual"]).default("on_done");
var CleanupConfigSchema = z12.object({
  /**
   * When to trigger automatic state cleanup.
   * - 'on_done': Run after wu:done success (default)
   * - 'on_init': Run during lumenflow init
   * - 'manual': Only run via pnpm state:cleanup
   *
   * @default 'on_done'
   */
  trigger: CleanupTriggerSchema,
  /**
   * WU-1542: Commit message for auto-cleanup changes.
   * Consumer repos with strict main-branch guards may reject the default.
   * Configure this to match your repo's allowed commit message patterns.
   *
   * @default 'chore: lumenflow state cleanup [skip ci]'
   *
   * @example
   * ```yaml
   * cleanup:
   *   commit_message: 'chore(repair): auto state cleanup [skip ci]'
   * ```
   */
  commit_message: z12.string().default("chore: lumenflow state cleanup [skip ci]")
});
var EscalationConfigSchema = z12.object({
  /**
   * Email address for human escalation notifications.
   * When escalation triggers fire, this email receives notification.
   *
   * @default 'escalation@example.com'
   */
  email: z12.string().email().default("escalation@example.com")
});

// ../core/dist/lumenflow-config-schema.js
var LumenFlowConfigSchema = z13.object({
  /** Schema version for future migrations */
  version: z13.string().default("1.0.0"),
  /** Directory paths */
  directories: DirectoriesSchema.default(() => DirectoriesSchema.parse({})),
  /** State paths (.lumenflow directory structure) */
  state: StatePathsSchema.default(() => StatePathsSchema.parse({})),
  /** Git configuration */
  git: GitConfigSchema.default(() => GitConfigSchema.parse({})),
  /** WU configuration */
  wu: WuConfigSchema.default(() => WuConfigSchema.parse({})),
  /** Gates configuration */
  gates: GatesConfigSchema.default(() => GatesConfigSchema.parse({})),
  /** Memory layer configuration */
  memory: MemoryConfigSchema.default(() => MemoryConfigSchema.parse({})),
  /** UI configuration */
  ui: UiConfigSchema.default(() => UiConfigSchema.parse({})),
  /** YAML configuration */
  yaml: YamlConfigSchema.default(() => YamlConfigSchema.parse({})),
  /** Agents configuration */
  agents: AgentsConfigSchema.default(() => AgentsConfigSchema.parse({})),
  /** Experimental features (WU-1090) */
  experimental: ExperimentalConfigSchema.default(() => ExperimentalConfigSchema.parse({})),
  /** WU-1366: Cleanup configuration */
  cleanup: CleanupConfigSchema.default(() => CleanupConfigSchema.parse({})),
  /** WU-1270: Telemetry configuration */
  telemetry: TelemetryConfigSchema.default(() => TelemetryConfigSchema.parse({})),
  /** WU-1259: Methodology configuration */
  methodology: MethodologyConfigSchema.optional(),
  /** WU-1495: Cloud auto-detection configuration */
  cloud: CloudConfigSchema.default(() => CloudConfigSchema.parse({})),
  /** WU-1345: Lanes configuration */
  lanes: LanesConfigSchema.optional(),
  /** WU-2122: Escalation routing configuration */
  escalation: EscalationConfigSchema.default(() => EscalationConfigSchema.parse({})),
  /** WU-1356: Package manager for CLI operations */
  package_manager: PackageManagerSchema,
  /** WU-1356: Test runner for incremental test detection */
  test_runner: TestRunnerSchema,
  /** WU-1356: Custom build command for CLI bootstrap */
  build_command: z13.string().default("pnpm build")
});
function parseConfig(data = {}) {
  return LumenFlowConfigSchema.parse(data);
}
function getDefaultConfig() {
  return LumenFlowConfigSchema.parse({});
}

// ../core/dist/normalize-config-keys.js
var GIT_KEY_MAP = {
  agent_branch_patterns: "agentBranchPatterns",
  agent_branch_patterns_override: "agentBranchPatternsOverride",
  disable_agent_pattern_registry: "disableAgentPatternRegistry",
  main_branch: "mainBranch",
  default_remote: "defaultRemote",
  require_remote: "requireRemote",
  lane_branch_prefix: "laneBranchPrefix",
  max_branch_drift: "maxBranchDrift"
};
function normalizeSection(section, keyMap) {
  const result = {};
  for (const [key, value] of Object.entries(section)) {
    const camelKey = keyMap[key];
    if (camelKey) {
      if (!(camelKey in section)) {
        result[camelKey] = value;
      }
    } else {
      result[key] = value;
    }
  }
  return result;
}
function normalizeConfigKeys(raw) {
  if (!raw || typeof raw !== "object") {
    return raw ?? {};
  }
  const result = { ...raw };
  if (result.git && typeof result.git === "object" && !Array.isArray(result.git)) {
    result.git = normalizeSection(result.git, GIT_KEY_MAP);
  }
  return result;
}

// ../core/dist/lumenflow-config.js
import * as fs2 from "fs";
import * as path2 from "path";
import * as yaml2 from "yaml";
var UTF8_ENCODING = "utf8";
var WARNING_PREFIX = "[lumenflow-config]";
var WORKSPACE_INIT_COMMAND = "pnpm workspace-init --yes";
var WORKSPACE_CONFIG_SECTION = WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY;
function getConfigFilePresence(projectRoot) {
  return {
    workspaceConfigExists: fs2.existsSync(path2.join(projectRoot, WORKSPACE_CONFIG_FILE_NAME))
  };
}
var cachedConfig = null;
var cachedProjectRoot = null;
function parseYamlRecord(content) {
  return asRecord(yaml2.parse(content));
}
function findProjectRoot(startDir = process.cwd()) {
  let currentDir = path2.resolve(startDir);
  const filesystemRoot = path2.parse(currentDir).root;
  while (true) {
    if (fs2.existsSync(path2.join(currentDir, WORKSPACE_CONFIG_FILE_NAME))) {
      return currentDir;
    }
    if (fs2.existsSync(path2.join(currentDir, GIT_DIRECTORY_NAME))) {
      return currentDir;
    }
    if (currentDir === filesystemRoot) {
      break;
    }
    currentDir = path2.dirname(currentDir);
  }
  return process.cwd();
}
function loadWorkspaceSoftwareDeliveryConfig(projectRoot) {
  const workspacePath = path2.join(projectRoot, WORKSPACE_CONFIG_FILE_NAME);
  if (!fs2.existsSync(workspacePath)) {
    return null;
  }
  try {
    const content = fs2.readFileSync(workspacePath, UTF8_ENCODING);
    const workspaceData = parseYamlRecord(content);
    if (!workspaceData) {
      console.warn(`${WARNING_PREFIX} ${WORKSPACE_CONFIG_FILE_NAME} does not contain a valid object root.`);
      return null;
    }
    const parsedExtensions = WorkspaceV2ExtensionsSchema.safeParse(workspaceData);
    if (!parsedExtensions.success) {
      const hasSoftwareDeliveryError = parsedExtensions.error.issues.some((issue) => issue.path[0] === WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY);
      if (hasSoftwareDeliveryError) {
        console.warn(`${WARNING_PREFIX} ${WORKSPACE_CONFIG_FILE_NAME} is missing a valid ${WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY} block.`);
      }
      return null;
    }
    return normalizeConfigKeys(parsedExtensions.data[WORKSPACE_V2_KEYS.SOFTWARE_DELIVERY]);
  } catch (error) {
    console.warn(`${WARNING_PREFIX} Failed to parse ${WORKSPACE_CONFIG_FILE_NAME}:`, error instanceof Error ? error.message : String(error));
    return null;
  }
}
function getConfig(options = {}) {
  const { projectRoot: overrideRoot, reload = false, strictWorkspace = false } = options;
  if (cachedConfig && !reload && !overrideRoot) {
    return cachedConfig;
  }
  const projectRoot = overrideRoot || findProjectRoot();
  const { workspaceConfigExists } = getConfigFilePresence(projectRoot);
  if (strictWorkspace && !workspaceConfigExists) {
    throw createError(ErrorCodes.CONFIG_ERROR, `${WARNING_PREFIX} Missing ${WORKSPACE_CONFIG_FILE_NAME}. Run \`${WORKSPACE_INIT_COMMAND}\` to scaffold workspace config.`);
  }
  const workspaceConfig = loadWorkspaceSoftwareDeliveryConfig(projectRoot);
  if (strictWorkspace && workspaceConfigExists && !workspaceConfig) {
    throw createError(ErrorCodes.CONFIG_ERROR, `${WARNING_PREFIX} ${WORKSPACE_CONFIG_FILE_NAME} exists but is invalid. Ensure \`${WORKSPACE_CONFIG_SECTION}\` contains valid configuration values.`);
  }
  const config = parseConfig(workspaceConfig ?? {});
  if (!overrideRoot) {
    cachedConfig = config;
    cachedProjectRoot = projectRoot;
  }
  return config;
}
function getProjectRoot() {
  if (cachedProjectRoot) {
    return cachedProjectRoot;
  }
  cachedProjectRoot = findProjectRoot();
  return cachedProjectRoot;
}
function clearConfigCache() {
  cachedConfig = null;
  cachedProjectRoot = null;
}
function getResolvedPaths(options = {}) {
  const projectRoot = options.projectRoot || getProjectRoot();
  const config = getConfig({
    projectRoot,
    strictWorkspace: options.strictWorkspace
  });
  return {
    wuDir: path2.join(projectRoot, config.directories.wuDir),
    initiativesDir: path2.join(projectRoot, config.directories.initiativesDir),
    backlogPath: path2.join(projectRoot, config.directories.backlogPath),
    statusPath: path2.join(projectRoot, config.directories.statusPath),
    worktrees: path2.join(projectRoot, config.directories.worktrees),
    stampsDir: path2.join(projectRoot, config.state.stampsDir),
    stateDir: path2.join(projectRoot, config.state.stateDir),
    skillsDir: path2.join(projectRoot, config.directories.skillsDir),
    agentsDir: path2.join(projectRoot, config.directories.agentsDir),
    memoryBank: path2.join(projectRoot, config.directories.memoryBank),
    plansDir: path2.join(projectRoot, config.directories.plansDir),
    templatesDir: path2.join(projectRoot, config.directories.templatesDir),
    onboardingDir: path2.join(projectRoot, config.directories.onboardingDir),
    completeGuidePath: path2.join(projectRoot, config.directories.completeGuidePath),
    quickRefPath: path2.join(projectRoot, config.directories.quickRefPath),
    startingPromptPath: path2.join(projectRoot, config.directories.startingPromptPath),
    sizingGuidePath: path2.join(projectRoot, config.directories.sizingGuidePath),
    governancePath: path2.join(projectRoot, config.directories.governancePath),
    safeGitPath: path2.join(projectRoot, config.directories.safeGitPath)
  };
}

export {
  WU_STATUS,
  resolveWUStatus,
  getWUStatusDisplay,
  PROTECTED_WU_STATUSES,
  PROGRESSABLE_WU_STATUSES,
  WU_STATUS_GROUPS,
  CLAIMED_MODES,
  INCIDENT_SEVERITY,
  WU_TYPES,
  WU_EXPOSURE,
  WU_EXPOSURE_VALUES,
  TEST_TYPES,
  WORKSPACE_CONFIG_FILE_NAME,
  GIT_DIRECTORY_NAME,
  GIT_WORKTREES_SENTINEL,
  WORKSPACE_V2_KEYS,
  WRITABLE_ROOT_KEYS,
  MANAGED_ROOT_KEYS,
  DOCS_LAYOUT_PRESETS,
  DEFAULT_DOCS_LAYOUT,
  getDocsLayoutPreset,
  LUMENFLOW_CLIENT_IDS,
  resolvePolicy,
  MS_PER_MINUTE,
  MS_PER_HOUR,
  MS_PER_DAY,
  asRecord,
  GATE_PRESETS,
  getGatesSection,
  resolveTestPolicy,
  resolveTestRunner,
  resolveGatesCommands,
  loadLaneHealthConfig,
  DEFAULT_MIN_COVERAGE,
  CoChangeRuleConfigSchema,
  LumenFlowConfigSchema,
  getDefaultConfig,
  normalizeConfigKeys,
  getConfigFilePresence,
  findProjectRoot,
  getConfig,
  getProjectRoot,
  clearConfigCache,
  getResolvedPaths
};
