#!/usr/bin/env node
// src/bootstrap/state.ts
import { realpathSync } from "fs";
import { cwd } from "process";

// src/utils/crypto.ts
import { randomUUID } from "crypto";

// src/utils/settings/settingsCache.ts
var perSourceCache = new Map;
var parseFileCache = new Map;

// src/utils/signal.ts
function createSignal() {
  const listeners = new Set;
  return {
    subscribe(listener) {
      listeners.add(listener);
      return () => {
        listeners.delete(listener);
      };
    },
    emit(...args) {
      for (const listener of listeners)
        listener(...args);
    },
    clear() {
      listeners.clear();
    }
  };
}

// src/bootstrap/state.ts
function getInitialState() {
  let resolvedCwd = "";
  if (typeof process !== "undefined" && typeof process.cwd === "function" && typeof realpathSync === "function") {
    const rawCwd = cwd();
    try {
      resolvedCwd = realpathSync(rawCwd).normalize("NFC");
    } catch {
      resolvedCwd = rawCwd.normalize("NFC");
    }
  }
  const state = {
    originalCwd: resolvedCwd,
    projectRoot: resolvedCwd,
    totalCostUSD: 0,
    totalAPIDuration: 0,
    totalAPIDurationWithoutRetries: 0,
    totalToolDuration: 0,
    turnHookDurationMs: 0,
    turnToolDurationMs: 0,
    turnClassifierDurationMs: 0,
    turnToolCount: 0,
    turnHookCount: 0,
    turnClassifierCount: 0,
    startTime: Date.now(),
    lastInteractionTime: Date.now(),
    totalLinesAdded: 0,
    totalLinesRemoved: 0,
    hasUnknownModelCost: false,
    cwd: resolvedCwd,
    modelUsage: {},
    mainLoopModelOverride: undefined,
    initialMainLoopModel: null,
    modelStrings: null,
    isInteractive: false,
    kairosActive: false,
    strictToolResultPairing: false,
    sdkAgentProgressSummariesEnabled: false,
    userMsgOptIn: false,
    clientType: "cli",
    sessionSource: undefined,
    questionPreviewFormat: undefined,
    sessionIngressToken: undefined,
    oauthTokenFromFd: undefined,
    apiKeyFromFd: undefined,
    flagSettingsPath: undefined,
    flagSettingsInline: null,
    allowedSettingSources: [
      "userSettings",
      "projectSettings",
      "localSettings",
      "flagSettings",
      "policySettings"
    ],
    meter: null,
    sessionCounter: null,
    locCounter: null,
    prCounter: null,
    commitCounter: null,
    costCounter: null,
    tokenCounter: null,
    codeEditToolDecisionCounter: null,
    activeTimeCounter: null,
    statsStore: null,
    sessionId: randomUUID(),
    parentSessionId: undefined,
    loggerProvider: null,
    eventLogger: null,
    meterProvider: null,
    tracerProvider: null,
    agentColorMap: new Map,
    agentColorIndex: 0,
    lastAPIRequest: null,
    lastAPIRequestMessages: null,
    lastClassifierRequests: null,
    cachedSaluziMdContent: null,
    inMemoryErrorLog: [],
    inlinePlugins: [],
    chromeFlagOverride: undefined,
    useCoworkPlugins: false,
    sessionBypassPermissionsMode: false,
    scheduledTasksEnabled: false,
    sessionCronTasks: [],
    sessionCreatedTeams: new Set,
    sessionTrustAccepted: false,
    sessionPersistenceDisabled: false,
    hasExitedPlanMode: false,
    needsPlanModeExitAttachment: false,
    needsAutoModeExitAttachment: false,
    lspRecommendationShownThisSession: false,
    initJsonSchema: null,
    registeredHooks: null,
    planSlugCache: new Map,
    teleportedSessionInfo: null,
    invokedSkills: new Map,
    slowOperations: [],
    sdkBetas: undefined,
    mainThreadAgentType: undefined,
    isRemoteMode: false,
    ...process.env.USER_TYPE === "ant" ? {
      replBridgeActive: false
    } : {},
    directConnectServerUrl: undefined,
    systemPromptSectionCache: new Map,
    lastEmittedDate: null,
    additionalDirectoriesForSaluziMd: [],
    allowedChannels: [],
    hasDevChannels: false,
    sessionProjectDir: null,
    promptCache1hAllowlist: null,
    promptCache1hEligible: null,
    afkModeHeaderLatched: null,
    fastModeHeaderLatched: null,
    cacheEditingHeaderLatched: null,
    promptId: null,
    lastMainRequestId: undefined,
    lastApiCompletionTimestamp: null,
    pendingPostCompaction: false,
    snipTokensFreed: 0
  };
  return state;
}
var STATE = getInitialState();
var sessionSwitched = createSignal();
var onSessionSwitch = sessionSwitched.subscribe;

// src/commands/oms/shared/state-io.ts
import {
  existsSync,
  mkdirSync,
  readdirSync,
  readFileSync,
  rmSync,
  statSync,
  writeFileSync,
  unlinkSync
} from "node:fs";
import { join } from "node:path";

// src/commands/oms/shared/validation.ts
function ok() {
  return { valid: true, errors: [] };
}
function fail(...errors) {
  return { valid: false, errors };
}
var VALID_MODES = new Set([
  "team",
  "ralph",
  "ralplan",
  "autopilot",
  "ultrawork",
  "clarify",
  "autoresearch",
  "goal",
  "orchestra"
]);
var VALID_STATUSES = new Set([
  "running",
  "complete",
  "cancelled",
  "failed"
]);
function validateBase(obj) {
  const errors = [];
  if (typeof obj.mode !== "string" || !VALID_MODES.has(obj.mode)) {
    errors.push(`mode must be one of: ${[...VALID_MODES].join(", ")}; got ${JSON.stringify(obj.mode)}`);
  }
  if (typeof obj.status !== "string" || !VALID_STATUSES.has(obj.status)) {
    errors.push(`status must be one of: ${[...VALID_STATUSES].join(", ")}; got ${JSON.stringify(obj.status)}`);
  }
  if (typeof obj.active !== "boolean") {
    errors.push(`active must be boolean; got ${JSON.stringify(obj.active)}`);
  }
  if (typeof obj.started_at !== "string" || obj.started_at.length === 0) {
    errors.push("started_at must be a non-empty ISO string");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
function validateTeamState(obj) {
  const errors = [];
  if (typeof obj.worker_count !== "number" || obj.worker_count < 1 || obj.worker_count > 100) {
    errors.push("worker_count must be a number between 1 and 100");
  }
  if (typeof obj.task !== "string" || obj.task.length === 0) {
    errors.push("task must be a non-empty string");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
function validateRalphState(obj) {
  const errors = [];
  if (typeof obj.iteration !== "number" || obj.iteration < 0) {
    errors.push("iteration must be a number ≥ 0");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
var VALID_RALPLAN_PHASES = new Set([
  "planning",
  "architect_review",
  "critic_review",
  "revision",
  "approval"
]);
function validateRalplanState(obj) {
  const errors = [];
  if (typeof obj.phase !== "string" || !VALID_RALPLAN_PHASES.has(obj.phase)) {
    errors.push(`phase must be one of: ${[...VALID_RALPLAN_PHASES].join(", ")}; got ${JSON.stringify(obj.phase)}`);
  }
  if (typeof obj.iteration !== "number" || obj.iteration < 0) {
    errors.push("iteration must be a number ≥ 0");
  }
  if (typeof obj.max_iterations !== "number" || obj.max_iterations < 1) {
    errors.push("max_iterations must be a number ≥ 1");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
function validateAutopilotState(obj) {
  const errors = [];
  if (typeof obj.phase !== "number" || obj.phase < 0 || obj.phase > 5) {
    errors.push("phase must be a number between 0 and 5");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
function validateUltraworkState(obj) {
  const errors = [];
  if (typeof obj.task !== "string" || obj.task.length === 0) {
    errors.push("task must be a non-empty string");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
var VALID_CLARIFY_PHASES = new Set([
  "interview",
  "challenge",
  "crystallize",
  "bridge"
]);
function validateClarifyState(obj) {
  const errors = [];
  if (typeof obj.current_phase !== "string" || !VALID_CLARIFY_PHASES.has(obj.current_phase)) {
    errors.push(`current_phase must be one of: ${[...VALID_CLARIFY_PHASES].join(", ")}; got ${JSON.stringify(obj.current_phase)}`);
  }
  if (typeof obj.rounds !== "number" || obj.rounds < 0) {
    errors.push("rounds must be a number ≥ 0");
  }
  if (typeof obj.current_ambiguity !== "number" || obj.current_ambiguity < 0 || obj.current_ambiguity > 1) {
    errors.push("current_ambiguity must be a number between 0 and 1");
  }
  if (typeof obj.threshold !== "number" || obj.threshold < 0 || obj.threshold > 1) {
    errors.push("threshold must be a number between 0 and 1");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
function validateAutoresearchState(obj) {
  const errors = [];
  if (typeof obj.mission_slug !== "string" || obj.mission_slug.length === 0) {
    errors.push("mission_slug must be a non-empty string");
  }
  if (typeof obj.iteration !== "number" || obj.iteration < 0) {
    errors.push("iteration must be a number ≥ 0");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
function validateOrchestraState(obj) {
  const errors = [];
  if (typeof obj.workflow_name !== "string" || obj.workflow_name.length === 0) {
    errors.push("workflow_name must be a non-empty string");
  }
  if (typeof obj.stages_total !== "number" || obj.stages_total < 1) {
    errors.push("stages_total must be a number ≥ 1");
  }
  if (typeof obj.stages_completed !== "number" || obj.stages_completed < 0) {
    errors.push("stages_completed must be a number ≥ 0");
  }
  if (typeof obj.workers_active !== "number" || obj.workers_active < 0) {
    errors.push("workers_active must be a number ≥ 0");
  }
  return errors.length > 0 ? fail(...errors) : ok();
}
var MODE_VALIDATORS = {
  team: validateTeamState,
  ralph: validateRalphState,
  ralplan: validateRalplanState,
  autopilot: validateAutopilotState,
  ultrawork: validateUltraworkState,
  clarify: validateClarifyState,
  autoresearch: validateAutoresearchState,
  goal: null,
  orchestra: validateOrchestraState
};
function validateModeState(state) {
  if (typeof state !== "object" || state === null) {
    return fail("state must be a non-null object");
  }
  const obj = state;
  const baseResult = validateBase(obj);
  if (!baseResult.valid)
    return baseResult;
  const mode = obj.mode;
  const validator = MODE_VALIDATORS[mode];
  if (!validator)
    return ok();
  const modeResult = validator(obj);
  if (!modeResult.valid)
    return modeResult;
  return ok();
}
function assertValidModeState(state) {
  const result = validateModeState(state);
  if (!result.valid) {
    const obj = state;
    const mode = obj?.mode ?? "unknown";
    throw new Error(`Invalid ${String(mode)} state: ${result.errors.join("; ")}`);
  }
}

// src/commands/oms/shared/state-io.ts
function getOmsStateDir(projectRoot) {
  return join(projectRoot, ".oms", "state");
}
function ensureOmsStateDir(projectRoot) {
  const dir = getOmsStateDir(projectRoot);
  mkdirSync(dir, { recursive: true });
  return dir;
}
function getStateFilePath(projectRoot, mode) {
  return join(getOmsStateDir(projectRoot), `${mode}-state.json`);
}
function readModeState(projectRoot, mode) {
  const filePath = getStateFilePath(projectRoot, mode);
  if (!existsSync(filePath))
    return null;
  try {
    const parsed = JSON.parse(readFileSync(filePath, "utf-8"));
    if (!validateModeState(parsed).valid)
      return null;
    return parsed;
  } catch {
    return null;
  }
}
function writeModeState(projectRoot, state) {
  const dir = ensureOmsStateDir(projectRoot);
  const filePath = join(dir, `${state.mode}-state.json`);
  writeFileSync(filePath, JSON.stringify(state, null, 2), "utf-8");
}
function clearModeState(projectRoot, mode) {
  const filePath = getStateFilePath(projectRoot, mode);
  if (existsSync(filePath)) {
    unlinkSync(filePath);
  }
}
var MODE_AUXILIARY_PATHS = {
  team: ["state/team-results"],
  ralph: ["state/ralph-prd.json", "state/progress.txt"],
  autopilot: ["autopilot"],
  goal: ["ultragoal"],
  ralplan: ["state/handoff-tracking.json"],
  clarify: ["state/handoff-tracking.json"],
  orchestra: ["../.orchestra/worktrees"]
};
function clearModeArtifacts(projectRoot, mode) {
  const omsDir = join(projectRoot, ".oms");
  const paths = MODE_AUXILIARY_PATHS[mode];
  if (!paths)
    return;
  for (const relPath of paths) {
    const fullPath = join(omsDir, relPath);
    if (!existsSync(fullPath))
      continue;
    try {
      const stat = statSync(fullPath);
      if (stat.isDirectory()) {
        rmSync(fullPath, { recursive: true, force: true });
      } else {
        unlinkSync(fullPath);
      }
    } catch {}
  }
}
var STALE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
var ORPHAN_RUNNING_THRESHOLD_MS = 60 * 60 * 1000;

// src/commands/oms/shared/state-machine.ts
class TransitionError extends Error {
  mode;
  from;
  to;
  constructor(mode, from, to, message) {
    super(message ?? `Invalid ${mode} transition: ${from} → ${to}`);
    this.name = "TransitionError";
    this.mode = mode;
    this.from = from;
    this.to = to;
  }
}
var STATUS_TRANSITIONS = {
  running: new Set(["complete", "cancelled", "failed"]),
  complete: new Set,
  cancelled: new Set,
  failed: new Set(["running"])
};
var PHASE_TRANSITIONS = {
  autopilot: {
    phaseField: "phase",
    transitions: {
      "0": new Set([1]),
      "1": new Set([2]),
      "2": new Set([3]),
      "3": new Set([4]),
      "4": new Set([5]),
      "5": new Set
    }
  },
  ralplan: {
    phaseField: "phase",
    transitions: {
      planning: new Set(["architect_review"]),
      architect_review: new Set(["critic_review"]),
      critic_review: new Set(["revision", "approval"]),
      revision: new Set(["planning"]),
      approval: new Set
    }
  },
  clarify: {
    phaseField: "current_phase",
    transitions: {
      interview: new Set(["challenge", "crystallize"]),
      challenge: new Set(["interview", "crystallize"]),
      crystallize: new Set(["bridge"]),
      bridge: new Set
    }
  },
  orchestra: {
    phaseField: "stages_completed",
    transitions: {}
  }
};
function transitionState(projectRoot, mode, updates) {
  const current = readModeState(projectRoot, mode);
  if (!current) {
    throw new TransitionError(mode, "null", "any", `Cannot transition ${mode}: no state file found`);
  }
  const next = { ...current, ...updates };
  if (updates.status && updates.status !== current.status) {
    const allowed = STATUS_TRANSITIONS[current.status];
    if (!allowed || !allowed.has(updates.status)) {
      throw new TransitionError(mode, `status:${current.status}`, `status:${updates.status}`);
    }
  }
  const phaseConfig = PHASE_TRANSITIONS[mode];
  if (phaseConfig) {
    const field = phaseConfig.phaseField;
    const currentRaw = current[field];
    const nextRaw = next[field];
    if (mode === "orchestra" && typeof currentRaw === "number" && typeof nextRaw === "number") {
      if (nextRaw < currentRaw) {
        throw new TransitionError(mode, `${field}:${currentRaw}`, `${field}:${nextRaw}`);
      }
    } else {
      const currentPhase = String(currentRaw);
      const nextPhase = String(nextRaw);
      if (currentPhase !== nextPhase) {
        const allowed = phaseConfig.transitions[currentPhase];
        if (!allowed || !allowed.has(nextRaw)) {
          throw new TransitionError(mode, `${field}:${currentPhase}`, `${field}:${nextPhase}`);
        }
      }
    }
  }
  assertValidModeState(next);
  writeModeState(projectRoot, next);
  return next;
}
function completeMode(projectRoot, mode) {
  const current = readModeState(projectRoot, mode);
  if (!current) {
    return {
      mode,
      status: "complete",
      active: false,
      started_at: new Date().toISOString(),
      completed_at: new Date().toISOString()
    };
  }
  const final = transitionState(projectRoot, mode, {
    status: "complete",
    active: false,
    completed_at: new Date().toISOString()
  });
  clearModeState(projectRoot, mode);
  clearModeArtifacts(projectRoot, mode);
  return final;
}
function cancelMode(projectRoot, mode) {
  const current = readModeState(projectRoot, mode);
  if (!current) {
    return {
      mode,
      status: "cancelled",
      active: false,
      started_at: new Date().toISOString(),
      completed_at: new Date().toISOString()
    };
  }
  const final = transitionState(projectRoot, mode, {
    status: "cancelled",
    active: false,
    completed_at: new Date().toISOString()
  });
  clearModeState(projectRoot, mode);
  clearModeArtifacts(projectRoot, mode);
  return final;
}
function getValidTransitions(projectRoot, mode) {
  const current = readModeState(projectRoot, mode);
  if (!current)
    return { statuses: [], phases: [] };
  const statuses = [...STATUS_TRANSITIONS[current.status] ?? []];
  const phaseConfig = PHASE_TRANSITIONS[mode];
  if (!phaseConfig)
    return { statuses, phases: [] };
  const currentPhase = String(current[phaseConfig.phaseField]);
  const phases = [...phaseConfig.transitions[currentPhase] ?? []];
  return { statuses, phases };
}

// src/commands/oms/shared/project-root.ts
import { existsSync as existsSync2, statSync as statSync2 } from "node:fs";
import { dirname, join as join2, resolve } from "node:path";
var PROJECT_ROOT_MARKERS = [".oms", ".git", "package.json"];
var MAX_WALK_DEPTH = 10;
function findProjectRoot(startDir) {
  const start = resolve(startDir ?? process.cwd());
  let current = start;
  for (let i = 0;i < MAX_WALK_DEPTH; i++) {
    for (const marker of PROJECT_ROOT_MARKERS) {
      const candidate = join2(current, marker);
      if (existsSync2(candidate)) {
        if (marker === ".oms" || marker === ".git") {
          try {
            if (statSync2(candidate).isDirectory())
              return current;
          } catch {}
        } else {
          return current;
        }
      }
    }
    const parent = dirname(current);
    if (parent === current)
      break;
    current = parent;
  }
  return start;
}

// src/commands/oms/shared/quality-gates.ts
import { readFileSync as readFileSync3, existsSync as existsSync4, readdirSync as readdirSync2 } from "node:fs";
import { join as join3 } from "node:path";

// src/commands/oms/goal/check-goal-state.ts
import { readFileSync as readFileSync2, existsSync as existsSync3 } from "node:fs";
import { resolve as resolve2 } from "node:path";
function checkSchemaCompliance(state) {
  const issues = [];
  if (state.version !== 2) {
    issues.push(`version must be 2, got ${state.version}`);
  }
  if (!state.intake) {
    issues.push("missing intake block");
  } else {
    const requiredIntakeFields = [
      "interpreted_outcome",
      "input_shape",
      "proof_type",
      "completion_proof",
      "likely_misfire"
    ];
    for (const field of requiredIntakeFields) {
      const val = state.intake[field];
      if (!val || val.trim() === "") {
        issues.push(`intake.${field} is empty or missing`);
      }
    }
    const validShapes = [
      "vague",
      "specific",
      "existing_plan",
      "recovery",
      "audit"
    ];
    if (state.intake.input_shape && !validShapes.includes(state.intake.input_shape)) {
      issues.push(`intake.input_shape must be one of ${validShapes.join(", ")}`);
    }
    const validProofTypes = ["test", "demo", "artifact", "metric", "review"];
    if (state.intake.proof_type && !validProofTypes.includes(state.intake.proof_type)) {
      issues.push(`intake.proof_type must be one of ${validProofTypes.join(", ")}`);
    }
  }
  if (!state.oracle) {
    issues.push("missing oracle block");
  } else {
    if (!state.oracle.signal || state.oracle.signal.trim() === "") {
      issues.push("oracle.signal is empty or missing");
    }
    if (!state.oracle.final_proof || state.oracle.final_proof.trim() === "") {
      issues.push("oracle.final_proof is empty or missing");
    }
    const validCadences = ["per_goal", "per_slice", "final"];
    if (state.oracle.cadence && !validCadences.includes(state.oracle.cadence)) {
      issues.push(`oracle.cadence must be one of ${validCadences.join(", ")}`);
    }
  }
  if (!Array.isArray(state.goals)) {
    issues.push("goals must be an array");
  }
  return {
    category: "Schema compliance",
    status: issues.length > 0 ? "FAIL" : "PASS",
    details: issues
  };
}
function checkActiveGoalInvariants(state) {
  const issues = [];
  const inProgress = state.goals.filter((g) => g.status === "in_progress");
  if (inProgress.length > 1) {
    issues.push(`${inProgress.length} goals are in_progress (max 1): ${inProgress.map((g) => g.id).join(", ")}`);
  }
  if (state.activeGoalId) {
    const activeGoal = state.goals.find((g) => g.id === state.activeGoalId);
    if (!activeGoal) {
      issues.push(`activeGoalId "${state.activeGoalId}" does not match any goal`);
    } else if (activeGoal.status !== "in_progress") {
      issues.push(`activeGoalId "${state.activeGoalId}" points to goal with status "${activeGoal.status}" (expected "in_progress")`);
    }
  } else if (inProgress.length === 1) {
    issues.push(`goal "${inProgress[0].id}" is in_progress but activeGoalId is null`);
  }
  for (const goal of inProgress) {
    const activeSlices = (goal.slices ?? []).filter((s) => s.status === "in_progress" || s.status === "pending");
    if (activeSlices.length === 0 && (goal.slices?.length ?? 0) > 0) {
      issues.push(`goal "${goal.id}" is in_progress but has no active/pending slices`);
    }
  }
  return {
    category: "Active goal invariants",
    status: issues.length > 0 ? "FAIL" : "PASS",
    details: issues
  };
}
function checkReceiptCompliance(state) {
  const issues = [];
  for (const goal of state.goals) {
    for (const slice of goal.slices ?? []) {
      if (slice.status === "complete") {
        if (!slice.receipt) {
          issues.push(`${goal.id}/${slice.id}: ${slice.role} slice completed without receipt`);
          continue;
        }
        if (slice.role === "worker") {
          const changedFiles = slice.receipt.changed_files;
          if (!Array.isArray(changedFiles) || changedFiles.length === 0) {
            issues.push(`${goal.id}/${slice.id}: WorkerReceipt missing or empty changed_files`);
          }
        }
        if (slice.role === "judge") {
          if (typeof slice.receipt.decision !== "string" || slice.receipt.decision.trim() === "") {
            issues.push(`${goal.id}/${slice.id}: JudgeReceipt missing decision`);
          }
          if (typeof slice.receipt.full_outcome_complete !== "boolean") {
            issues.push(`${goal.id}/${slice.id}: JudgeReceipt missing full_outcome_complete boolean`);
          }
        }
        if (slice.role === "scout") {
          if (typeof slice.receipt.summary !== "string" || slice.receipt.summary.trim() === "") {
            issues.push(`${goal.id}/${slice.id}: ScoutReceipt missing summary`);
          }
        }
      }
    }
  }
  return {
    category: "Receipt schema compliance",
    status: issues.length > 0 ? "FAIL" : "PASS",
    details: issues
  };
}
function checkSliceSizing(state) {
  const warnings = [];
  for (const goal of state.goals) {
    let consecutiveTiny = 0;
    for (const slice of goal.slices ?? []) {
      if (slice.size === "tiny" && slice.status === "complete") {
        consecutiveTiny++;
        if (consecutiveTiny > 2) {
          warnings.push(`${goal.id}: ${consecutiveTiny} consecutive tiny slices (max recommended: 2)`);
        }
      } else {
        consecutiveTiny = 0;
      }
    }
  }
  return {
    category: "Slice sizing policy",
    status: warnings.length > 0 ? "WARN" : "PASS",
    details: warnings
  };
}
function checkOracleConsistency(state) {
  const issues = [];
  for (const goal of state.goals) {
    if (goal.status === "complete") {
      if (!goal.oracle) {
        issues.push(`${goal.id}: complete goal has no oracle defined`);
        continue;
      }
      if (goal.oracle.last_result !== "pass") {
        issues.push(`${goal.id}: complete goal but oracle.last_result is "${goal.oracle.last_result}" (expected "pass")`);
      }
    }
  }
  return {
    category: "Oracle consistency",
    status: issues.length > 0 ? "FAIL" : "PASS",
    details: issues
  };
}
function checkTemporalConsistency(state) {
  const issues = [];
  for (const goal of state.goals) {
    if (goal.startedAt && goal.completedAt) {
      if (new Date(goal.startedAt) > new Date(goal.completedAt)) {
        issues.push(`${goal.id}: startedAt (${goal.startedAt}) is after completedAt (${goal.completedAt})`);
      }
    }
    if (goal.createdAt && goal.startedAt) {
      if (new Date(goal.createdAt) > new Date(goal.startedAt)) {
        issues.push(`${goal.id}: createdAt (${goal.createdAt}) is after startedAt (${goal.startedAt})`);
      }
    }
    for (const slice of goal.slices ?? []) {
      if (slice.startedAt && slice.completedAt) {
        if (new Date(slice.startedAt) > new Date(slice.completedAt)) {
          issues.push(`${goal.id}/${slice.id}: startedAt is after completedAt`);
        }
      }
    }
  }
  return {
    category: "Temporal consistency",
    status: issues.length > 0 ? "FAIL" : "PASS",
    details: issues
  };
}
function formatReport(filePath, state, results) {
  const lines = [];
  lines.push("OMS Goal State Validation");
  lines.push("=========================");
  lines.push(`File: ${filePath}`);
  if (state) {
    lines.push(`Version: ${state.version}`);
    const statusCounts = {};
    for (const g of state.goals) {
      statusCounts[g.status] = (statusCounts[g.status] ?? 0) + 1;
    }
    const countsStr = Object.entries(statusCounts).map(([s, c]) => `${c} ${s}`).join(", ");
    lines.push(`Goals: ${state.goals.length} (${countsStr})`);
  }
  lines.push("");
  let violations = 0;
  let warnings = 0;
  for (const r of results) {
    const prefix = `[${r.status}]`;
    lines.push(`${prefix} ${r.category}`);
    for (const d of r.details) {
      lines.push(`       ${d}`);
    }
    if (r.status === "FAIL")
      violations++;
    if (r.status === "WARN")
      warnings++;
  }
  lines.push("");
  if (violations === 0 && warnings === 0) {
    lines.push("Result: PASS");
  } else if (violations === 0) {
    lines.push(`Result: PASS (${warnings} warning${warnings > 1 ? "s" : ""})`);
  } else {
    lines.push(`Result: FAIL (${violations} violation${violations > 1 ? "s" : ""}, ${warnings} warning${warnings > 1 ? "s" : ""})`);
  }
  return lines.join(`
`);
}
function validateGoalStateFile(filePath) {
  const absPath = resolve2(filePath);
  if (!existsSync3(absPath)) {
    return {
      results: [],
      hasViolations: false,
      hasError: true,
      report: `File not found: ${absPath}`
    };
  }
  let state;
  try {
    state = JSON.parse(readFileSync2(absPath, "utf-8"));
  } catch (err) {
    return {
      results: [],
      hasViolations: true,
      hasError: true,
      report: `Invalid JSON: ${err.message}`
    };
  }
  const results = [
    checkSchemaCompliance(state),
    checkActiveGoalInvariants(state),
    checkReceiptCompliance(state),
    checkSliceSizing(state),
    checkOracleConsistency(state),
    checkTemporalConsistency(state)
  ];
  const hasViolations = results.some((r) => r.status === "FAIL");
  const report = formatReport(filePath, state, results);
  return { results, hasViolations, hasError: false, report };
}
if (false) {}

// src/commands/oms/shared/quality-gates.ts
function checkRalphQualityGate(projectRoot) {
  const prdPath = join3(projectRoot, ".oms", "state", "ralph-prd.json");
  if (!existsSync4(prdPath)) {
    return {
      mode: "ralph",
      passed: false,
      reason: "Cannot complete ralph: no PRD file found at .oms/state/ralph-prd.json. Create the PRD first."
    };
  }
  let prd;
  try {
    prd = JSON.parse(readFileSync3(prdPath, "utf-8"));
  } catch {
    return {
      mode: "ralph",
      passed: false,
      reason: "Cannot complete ralph: failed to parse ralph-prd.json"
    };
  }
  const stories = prd.stories;
  if (!Array.isArray(stories) || stories.length === 0) {
    return {
      mode: "ralph",
      passed: false,
      reason: "Cannot complete ralph: no stories found in PRD. Add stories with acceptance criteria first."
    };
  }
  const allPass = stories.every((s) => typeof s === "object" && s !== null && s.passes === true);
  if (!allPass) {
    const passed = stories.filter((s) => typeof s === "object" && s !== null && s.passes === true).length;
    return {
      mode: "ralph",
      passed: false,
      reason: `Cannot complete ralph: only ${passed}/${stories.length} PRD stories pass verification. Continue working on incomplete stories.`
    };
  }
  return { mode: "ralph", passed: true, reason: "All PRD stories pass" };
}
function checkAutopilotQualityGate(projectRoot) {
  const statePath = join3(projectRoot, ".oms", "state", "autopilot-state.json");
  if (!existsSync4(statePath)) {
    return {
      mode: "autopilot",
      passed: false,
      reason: "Cannot complete autopilot: no state file found. Initialize the workflow first."
    };
  }
  let state;
  try {
    state = JSON.parse(readFileSync3(statePath, "utf-8"));
  } catch {
    return {
      mode: "autopilot",
      passed: false,
      reason: "Cannot complete autopilot: failed to parse state file"
    };
  }
  const phase = state.phase;
  if (typeof phase !== "number" || phase < 5) {
    return {
      mode: "autopilot",
      passed: false,
      reason: `Cannot complete autopilot: at phase ${phase ?? "?"}/5. Must reach phase 5 (cleanup) before completing.`
    };
  }
  return {
    mode: "autopilot",
    passed: true,
    reason: "Autopilot at phase 5 (cleanup)"
  };
}
function checkGoalQualityGate(projectRoot) {
  const statePath = join3(projectRoot, ".oms", "ultragoal", "state.json");
  if (!existsSync4(statePath)) {
    return {
      mode: "goal",
      passed: true,
      reason: "No goal state.json found (early workflow)"
    };
  }
  const { hasViolations, report } = validateGoalStateFile(statePath);
  if (hasViolations) {
    return {
      mode: "goal",
      passed: false,
      reason: `Cannot complete goal: state validation failed:
${report}`
    };
  }
  return {
    mode: "goal",
    passed: true,
    reason: "Goal state validation passed"
  };
}
function readHandoffTracking(projectRoot) {
  const trackingPath = join3(projectRoot, ".oms", "state", "handoff-tracking.json");
  if (!existsSync4(trackingPath))
    return null;
  try {
    const data = JSON.parse(readFileSync3(trackingPath, "utf-8"));
    if (data && Array.isArray(data.calls))
      return data;
    return null;
  } catch {
    return null;
  }
}
function hasHandoffTo(tracking, targets) {
  if (!tracking || tracking.calls.length === 0)
    return false;
  return tracking.calls.some((call) => targets.has(call.skill));
}
var RALPLAN_HANDOFF_TARGETS = new Set([
  "oms-team",
  "oms-ralph",
  "team",
  "ralph"
]);
function checkRalplanQualityGate(projectRoot) {
  const tracking = readHandoffTracking(projectRoot);
  if (!hasHandoffTo(tracking, RALPLAN_HANDOFF_TARGETS)) {
    return {
      mode: "ralplan",
      passed: false,
      reason: "Cannot complete ralplan: no Skill() handoff to an execution mode (oms-team or oms-ralph) was recorded. Use the Skill tool to invoke the chosen execution mode before completing."
    };
  }
  return {
    mode: "ralplan",
    passed: true,
    reason: "Ralplan handoff to execution mode verified"
  };
}
var CLARIFY_HANDOFF_TARGETS = new Set([
  "oms-ralplan",
  "oms-autopilot",
  "oms-ralph",
  "oms-team",
  "ralplan",
  "autopilot",
  "ralph",
  "team"
]);
function checkClarifyQualityGate(projectRoot) {
  const tracking = readHandoffTracking(projectRoot);
  if (!hasHandoffTo(tracking, CLARIFY_HANDOFF_TARGETS)) {
    return {
      mode: "clarify",
      passed: false,
      reason: "Cannot complete clarify: no Skill() handoff to an execution mode (oms-ralplan, oms-autopilot, oms-ralph, or oms-team) was recorded. Use the Skill tool to invoke the chosen execution mode before completing."
    };
  }
  return {
    mode: "clarify",
    passed: true,
    reason: "Clarify handoff to execution mode verified"
  };
}
function checkOrchestraQualityGate(projectRoot) {
  const statePath = join3(projectRoot, ".oms", "state", "orchestra-state.json");
  if (!existsSync4(statePath)) {
    return {
      mode: "orchestra",
      passed: true,
      reason: "No active orchestra state — completion allowed"
    };
  }
  let state;
  try {
    state = JSON.parse(readFileSync3(statePath, "utf-8"));
  } catch {
    return {
      mode: "orchestra",
      passed: false,
      reason: "Cannot complete orchestra: failed to parse orchestra-state.json"
    };
  }
  if (state.mode !== "orchestra") {
    return {
      mode: "orchestra",
      passed: true,
      reason: "No active orchestra state — completion allowed"
    };
  }
  const stagesCompleted = state.stages_completed;
  const stagesTotal = state.stages_total;
  const workersActive = state.workers_active;
  const workflowName = state.workflow_name;
  if (typeof stagesCompleted !== "number" || typeof stagesTotal !== "number") {
    return {
      mode: "orchestra",
      passed: false,
      reason: "Cannot complete orchestra: stages_completed or stages_total missing or invalid"
    };
  }
  if (stagesCompleted < stagesTotal) {
    return {
      mode: "orchestra",
      passed: false,
      reason: `Cannot complete orchestra: ${stagesCompleted}/${stagesTotal} stages completed. All stages must be finished before completing.`
    };
  }
  if (typeof workersActive === "number" && workersActive > 0) {
    return {
      mode: "orchestra",
      passed: false,
      reason: `Cannot complete orchestra: ${workersActive} workers still active. Wait for all workers to finish or cancel them.`
    };
  }
  const executionMode = state.execution_mode;
  if (stagesTotal >= 2 && executionMode !== "llm") {
    const handoffsDir = join3(projectRoot, ".oms", "handoffs");
    const hasHandoffs = existsSync4(handoffsDir) && (() => {
      try {
        return readdirSync2(handoffsDir).some((f) => f.endsWith(".md") || f.endsWith(".txt"));
      } catch {
        return false;
      }
    })();
    if (!hasHandoffs) {
      return {
        mode: "orchestra",
        passed: false,
        reason: "Cannot complete orchestra: no inter-stage handoff files found in .oms/handoffs/. " + "Workflow stages may not have actually executed. Run the workflow stages before completing."
      };
    }
  }
  return {
    mode: "orchestra",
    passed: true,
    reason: `Orchestra workflow "${workflowName}" complete: ${stagesCompleted}/${stagesTotal} stages done, no active workers`
  };
}
function checkTeamQualityGate(projectRoot) {
  const statePath = join3(projectRoot, ".oms", "state", "team-state.json");
  if (!existsSync4(statePath)) {
    return {
      mode: "team",
      passed: true,
      reason: "No active team state — completion allowed"
    };
  }
  let state;
  try {
    state = JSON.parse(readFileSync3(statePath, "utf-8"));
  } catch {
    return {
      mode: "team",
      passed: false,
      reason: "Cannot complete team: failed to parse team-state.json"
    };
  }
  const workerCount = state.worker_count;
  if (typeof workerCount !== "number" || workerCount < 1) {
    return {
      mode: "team",
      passed: true,
      reason: "No worker_count set — completion allowed"
    };
  }
  const resultsDir = join3(projectRoot, ".oms", "state", "team-results");
  let completedCount = 0;
  try {
    completedCount = readdirSync2(resultsDir).filter((f) => f.endsWith(".json")).length;
  } catch {
    return {
      mode: "team",
      passed: false,
      reason: `Cannot complete team: ${completedCount}/${workerCount} workers done. Continue working on remaining subtasks.`
    };
  }
  if (completedCount < workerCount) {
    return {
      mode: "team",
      passed: false,
      reason: `Cannot complete team: ${completedCount}/${workerCount} workers done. Continue working on remaining subtasks.`
    };
  }
  return {
    mode: "team",
    passed: true,
    reason: `Team complete: ${completedCount}/${workerCount} workers done`
  };
}
function checkUltraworkQualityGate(projectRoot) {
  const statePath = join3(projectRoot, ".oms", "state", "ultrawork-state.json");
  if (!existsSync4(statePath)) {
    return {
      mode: "ultrawork",
      passed: true,
      reason: "No active ultrawork state — completion allowed"
    };
  }
  let state;
  try {
    state = JSON.parse(readFileSync3(statePath, "utf-8"));
  } catch {
    return {
      mode: "ultrawork",
      passed: false,
      reason: "Cannot complete ultrawork: failed to parse ultrawork-state.json"
    };
  }
  const taskCount = state.task_count;
  const tasksCompleted = state.tasks_completed;
  if (typeof taskCount !== "number" || taskCount < 1) {
    return {
      mode: "ultrawork",
      passed: true,
      reason: "No task_count set — completion allowed"
    };
  }
  if (typeof tasksCompleted !== "number" || tasksCompleted < taskCount) {
    return {
      mode: "ultrawork",
      passed: false,
      reason: `Cannot complete ultrawork: ${tasksCompleted ?? 0}/${taskCount} tasks done. Continue working on remaining tasks.`
    };
  }
  return {
    mode: "ultrawork",
    passed: true,
    reason: `Ultrawork complete: ${tasksCompleted}/${taskCount} tasks done`
  };
}
var MODES_WITH_QUALITY_GATES = new Set([
  "ralph",
  "autopilot",
  "goal",
  "ralplan",
  "clarify",
  "orchestra",
  "team",
  "ultrawork"
]);
function checkQualityGate(projectRoot, mode) {
  switch (mode) {
    case "ralph":
      return checkRalphQualityGate(projectRoot);
    case "autopilot":
      return checkAutopilotQualityGate(projectRoot);
    case "goal":
      return checkGoalQualityGate(projectRoot);
    case "ralplan":
      return checkRalplanQualityGate(projectRoot);
    case "clarify":
      return checkClarifyQualityGate(projectRoot);
    case "orchestra":
      return checkOrchestraQualityGate(projectRoot);
    case "team":
      return checkTeamQualityGate(projectRoot);
    case "ultrawork":
      return checkUltraworkQualityGate(projectRoot);
    default:
      return null;
  }
}

// src/commands/oms/shared/oms-transition.ts
import { join as join4 } from "node:path";
var VALID_MODES2 = new Set([
  "team",
  "ralph",
  "ralplan",
  "autopilot",
  "ultrawork",
  "clarify",
  "autoresearch",
  "goal",
  "orchestra"
]);
var VALID_ACTIONS = new Set([
  "update",
  "complete",
  "cancel",
  "status",
  "phases",
  "validate-quality",
  "check-goal-state"
]);
function parseKeyValuePairs(args) {
  const result = {};
  for (const arg of args) {
    const eqIdx = arg.indexOf("=");
    if (eqIdx === -1)
      continue;
    const key = arg.slice(0, eqIdx);
    const rawValue = arg.slice(eqIdx + 1);
    if (rawValue === "true")
      result[key] = true;
    else if (rawValue === "false")
      result[key] = false;
    else if (/^-?\d+(\.\d+)?$/.test(rawValue))
      result[key] = Number.parseFloat(rawValue);
    else
      result[key] = rawValue;
  }
  return result;
}
function isValidMode(mode) {
  return VALID_MODES2.has(mode);
}
function doUpdate(projectRoot, mode, kvPairs) {
  if (Object.keys(kvPairs).length === 0) {
    console.error("Error: update requires at least one key=value pair");
    process.exit(2);
  }
  const currentState = readModeState(projectRoot, mode);
  if (!currentState) {
    console.error(`Error: ${mode} has no active state file (.oms/state/${mode}-state.json not found). ` + `The mode may not have been started, or its state was already cleaned up. ` + `Run "oms-transition ${mode} status" to verify, or start the mode first.`);
    process.exit(1);
  }
  try {
    const result = transitionState(projectRoot, mode, kvPairs);
    console.log(JSON.stringify(result, null, 2));
  } catch (err) {
    if (err instanceof TransitionError) {
      console.error(`TransitionError: ${err.mode} ${err.from} → ${err.to}: ${err.message}`);
    } else {
      console.error(`Error: ${err.message}`);
    }
    process.exit(1);
  }
}
function doComplete(projectRoot, mode) {
  const gate = checkQualityGate(projectRoot, mode);
  if (gate && !gate.passed) {
    console.error(`QualityGateError: ${gate.reason}`);
    process.exit(1);
  }
  try {
    const result = completeMode(projectRoot, mode);
    console.log(JSON.stringify(result, null, 2));
  } catch (err) {
    console.error(`Error: ${err.message}`);
    process.exit(1);
  }
}
function doValidateQuality(projectRoot, mode) {
  const gate = checkQualityGate(projectRoot, mode);
  if (!gate) {
    console.log(JSON.stringify({ mode, passed: true, reason: "No quality gate configured" }, null, 2));
    return;
  }
  console.log(JSON.stringify(gate, null, 2));
  if (!gate.passed) {
    process.exit(1);
  }
}
function doCancel(projectRoot, mode) {
  try {
    const result = cancelMode(projectRoot, mode);
    console.log(JSON.stringify(result, null, 2));
  } catch (err) {
    console.error(`Error: ${err.message}`);
    process.exit(1);
  }
}
function doStatus(projectRoot, mode) {
  const state = readModeState(projectRoot, mode);
  if (!state) {
    console.log("null");
    return;
  }
  console.log(JSON.stringify(state, null, 2));
}
function doPhases(projectRoot, mode) {
  const transitions = getValidTransitions(projectRoot, mode);
  console.log(JSON.stringify(transitions, null, 2));
}
function doCheckGoalState(projectRoot, _mode, args) {
  const filePath = args[0] ?? join4(projectRoot, ".oms", "ultragoal", "state.json");
  const { hasViolations, hasError, report } = validateGoalStateFile(filePath);
  console.log(report);
  if (hasError) {
    process.exit(2);
  }
  if (hasViolations) {
    process.exit(1);
  }
}
function main() {
  const args = process.argv.slice(2);
  if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
    console.log([
      "Usage: oms-transition <mode> <action> [args...]",
      "",
      "Modes: team, ralph, ralplan, autopilot, ultrawork, clarify, autoresearch, goal, orchestra",
      "",
      "Actions:",
      "  update <key=value>...   Validated state transition",
      "  complete                Quality-gate check, then mark complete (deletes state file)",
      "  cancel                  Mark workflow cancelled (deletes state file)",
      "  status                  Print current state as JSON",
      "  phases                  Print valid next transitions",
      "  validate-quality        Run quality gate without completing (exit 1 on failure)",
      "  check-goal-state [path]  Validate goal state file (default: .oms/ultragoal/state.json)",
      "",
      "Examples:",
      "  oms-transition autopilot update phase=1 phase_name=planning",
      "  oms-transition ralph update iteration=2 current_story=US-002",
      "  oms-transition team complete",
      "  oms-transition ralplan status"
    ].join(`
`));
    process.exit(0);
  }
  const mode = args[0];
  const action = args[1];
  if (!isValidMode(mode)) {
    console.error(`Error: invalid mode "${mode}". Valid: ${[...VALID_MODES2].join(", ")}`);
    process.exit(2);
  }
  if (!action || !VALID_ACTIONS.has(action)) {
    console.error(`Error: invalid action "${action}". Valid: ${[...VALID_ACTIONS].join(", ")}`);
    process.exit(2);
  }
  const projectRoot = findProjectRoot();
  switch (action) {
    case "update": {
      const kvPairs = parseKeyValuePairs(args.slice(2));
      doUpdate(projectRoot, mode, kvPairs);
      break;
    }
    case "complete":
      doComplete(projectRoot, mode);
      break;
    case "cancel":
      doCancel(projectRoot, mode);
      break;
    case "status":
      doStatus(projectRoot, mode);
      break;
    case "phases":
      doPhases(projectRoot, mode);
      break;
    case "validate-quality":
      doValidateQuality(projectRoot, mode);
      break;
    case "check-goal-state":
      doCheckGoalState(projectRoot, mode, args.slice(2));
      break;
  }
}
main();
