import {
  VALIDATION_LIMITS
} from "./chunk-2GXVIN57.js";
import {
  createWuPaths
} from "./chunk-6HO4GWJE.js";
import {
  BRANCHES,
  EXIT_CODES,
  FILE_EXTENSIONS,
  LUMENFLOW_PATHS,
  PATTERNS,
  STRING_LITERALS
} from "./chunk-DWMLTXKQ.js";
import {
  INCIDENT_SEVERITY,
  MS_PER_DAY,
  MS_PER_HOUR,
  MS_PER_MINUTE
} from "./chunk-V6OJGLBA.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../agent/dist/agent-session.js
import { randomUUID } from "crypto";
import { readFile, writeFile, mkdir, unlink, access } from "fs/promises";
import { join as join2 } from "path";
import { simpleGit } from "simple-git";

// ../agent/dist/agent-incidents.js
import { z } from "zod";
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
import { join } from "path";
var SEVERITY_VALUES = ["blocker", "major", "minor", "info"];
var CATEGORY_VALUES = ["workflow", "tooling", "confusion", "violation", "error"];
var IncidentLogSchema = z.object({
  timestamp: z.string().datetime(),
  // ISO 8601 with timezone
  session_id: z.string().uuid(),
  wu_id: z.string().regex(/^WU-\d+$/, "Must match WU-XXX format"),
  lane: z.string().min(1),
  category: z.enum(CATEGORY_VALUES),
  severity: z.enum(SEVERITY_VALUES),
  title: z.string().min(VALIDATION_LIMITS.TITLE_MIN).max(VALIDATION_LIMITS.TITLE_MAX),
  description: z.string().min(VALIDATION_LIMITS.DESCRIPTION_MIN).max(VALIDATION_LIMITS.DESCRIPTION_MAX),
  resolution: z.string().optional(),
  tags: z.array(z.string()).default([]),
  context: z.object({
    git_branch: z.string().optional(),
    current_step: z.string().optional(),
    related_files: z.array(z.string()).optional()
  }).optional().default(() => ({}))
});
function appendIncident(incident, incidentsDir = LUMENFLOW_PATHS.INCIDENTS) {
  const validated = IncidentLogSchema.parse(incident);
  if (!existsSync(incidentsDir)) {
    mkdirSync(incidentsDir, { recursive: true });
  }
  const logFile = join(incidentsDir, `${validated.category}${FILE_EXTENSIONS.NDJSON}`);
  appendFileSync(logFile, `${JSON.stringify(validated)}
`, { encoding: "utf-8" });
}

// ../agent/dist/agent-session.js
var SESSION_DIR = LUMENFLOW_PATHS.SESSIONS;
var SESSION_FILE = join2(SESSION_DIR, "current.json");
var DEFAULT_AGENT_VERSION = "unknown";
var DEFAULT_HOST_ID = "unknown";
var DEFAULT_AGENT_CAPABILITIES = ["session_lifecycle", "incident_logging"];
var AGENT_CAPABILITIES_ENV = "LUMENFLOW_AGENT_CAPABILITIES";
var AGENT_VERSION_ENV = "LUMENFLOW_AGENT_VERSION";
function asNonEmptyString(value) {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
}
function parseCapabilities(rawValue) {
  if (!rawValue) {
    return [...DEFAULT_AGENT_CAPABILITIES];
  }
  const parsed = rawValue.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
  return parsed.length > 0 ? parsed : [...DEFAULT_AGENT_CAPABILITIES];
}
function normalizeSessionData(session) {
  return {
    ...session,
    client_type: session.client_type ?? session.agent_type,
    capabilities: Array.isArray(session.capabilities) ? session.capabilities.filter((entry) => typeof entry === "string") : [...DEFAULT_AGENT_CAPABILITIES],
    agent_version: session.agent_version ?? DEFAULT_AGENT_VERSION,
    host_id: session.host_id ?? DEFAULT_HOST_ID
  };
}
async function startSession(wuId, tier, agentType = "claude-code") {
  const sessionExists = await access(SESSION_FILE).then(() => true).catch(() => false);
  if (sessionExists) {
    const content = await readFile(SESSION_FILE, { encoding: "utf-8" });
    const existing = JSON.parse(content);
    throw createError(ErrorCodes.SESSION_ERROR, `Session ${existing.session_id} already active for ${existing.wu_id}. Run 'pnpm agent:session:end' first.`);
  }
  if (!PATTERNS.WU_ID.test(wuId)) {
    throw createError(ErrorCodes.INVALID_WU_ID, `Invalid WU ID format: ${wuId}. Must match WU-XXX.`);
  }
  if (![1, 2, 3].includes(tier)) {
    throw createError(ErrorCodes.VALIDATION_ERROR, `Invalid context tier: ${tier}. Must be 1, 2, or 3.`);
  }
  const git = simpleGit();
  let lane = "Unknown";
  try {
    const branch = await git.revparse(["--abbrev-ref", "HEAD"]);
    const match = branch.match(/^lane\/([^/]+)\//);
    if (match && match[1]) {
      lane = match[1].split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(": ");
    }
  } catch {
  }
  const sessionId = randomUUID();
  const capabilities = parseCapabilities(asNonEmptyString(process.env[AGENT_CAPABILITIES_ENV]));
  const agentVersion = asNonEmptyString(process.env[AGENT_VERSION_ENV]) ?? DEFAULT_AGENT_VERSION;
  const hostId = asNonEmptyString(process.env.HOSTNAME) ?? asNonEmptyString(process.env.COMPUTERNAME) ?? DEFAULT_HOST_ID;
  const session = {
    session_id: sessionId,
    wu_id: wuId,
    lane,
    started: (/* @__PURE__ */ new Date()).toISOString(),
    agent_type: agentType,
    client_type: agentType,
    capabilities,
    agent_version: agentVersion,
    host_id: hostId,
    context_tier: tier,
    incidents_logged: 0,
    incidents_major: 0
  };
  const dirExists = await access(SESSION_DIR).then(() => true).catch(() => false);
  if (!dirExists) {
    await mkdir(SESSION_DIR, { recursive: true });
  }
  await writeFile(SESSION_FILE, JSON.stringify(session, null, 2));
  return sessionId;
}
async function getCurrentSession() {
  const sessionExists = await access(SESSION_FILE).then(() => true).catch(() => false);
  if (!sessionExists)
    return null;
  const content = await readFile(SESSION_FILE, { encoding: "utf-8" });
  return normalizeSessionData(JSON.parse(content));
}
async function logIncident(incidentData) {
  const session = await getCurrentSession();
  if (!session) {
    throw createError(ErrorCodes.SESSION_ERROR, "No active session. Run: pnpm agent:session start --wu WU-XXX --tier N");
  }
  const git = simpleGit();
  let gitBranch = "unknown";
  try {
    gitBranch = await git.revparse(["--abbrev-ref", "HEAD"]);
  } catch {
  }
  const incident = {
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    session_id: session.session_id,
    wu_id: session.wu_id,
    lane: session.lane,
    ...incidentData,
    context: {
      git_branch: gitBranch,
      ...incidentData.context ?? {}
    }
  };
  appendIncident(incident);
  session.incidents_logged++;
  if (incident.severity === INCIDENT_SEVERITY.MAJOR || incident.severity === INCIDENT_SEVERITY.BLOCKER) {
    session.incidents_major++;
  }
  await writeFile(SESSION_FILE, JSON.stringify(session, null, 2));
}
async function endSession() {
  const session = await getCurrentSession();
  if (!session) {
    throw createError(ErrorCodes.SESSION_ERROR, "No active session to end.");
  }
  session.completed = (/* @__PURE__ */ new Date()).toISOString();
  await unlink(SESSION_FILE);
  return {
    wu_id: session.wu_id,
    lane: session.lane,
    session_id: session.session_id,
    started: session.started,
    completed: session.completed,
    agent_type: session.agent_type,
    client_type: session.client_type,
    capabilities: [...session.capabilities],
    agent_version: session.agent_version,
    host_id: session.host_id,
    context_tier: session.context_tier,
    incidents_logged: session.incidents_logged,
    incidents_major: session.incidents_major
    // artifacts can be added manually later
  };
}

// ../agent/dist/agent-verification.js
import { execSync } from "child_process";
import { existsSync as existsSync2 } from "fs";
import { fileURLToPath } from "url";
function run(cmd) {
  try {
    return execSync(cmd, { stdio: "pipe", encoding: "utf-8" }).trim();
  } catch {
    return "";
  }
}
function formatWUId(wuId) {
  if (!wuId || typeof wuId !== "string") {
    throw createError(ErrorCodes.VALIDATION_ERROR, "verifyWUComplete requires a WU id (e.g., WU-123)", { wuId, type: typeof wuId });
  }
  const normalized = wuId.trim().toUpperCase();
  if (!PATTERNS.WU_ID.test(normalized)) {
    throw createError(ErrorCodes.INVALID_WU_ID, `Invalid WU id "${wuId}". Expected format: WU-123`, { wuId, normalized });
  }
  return normalized;
}
function checkGitStatus(runFn = run) {
  const status = runFn("git status --porcelain");
  if (!status)
    return null;
  const lines = status.split(STRING_LITERALS.NEWLINE).filter(Boolean).slice(0, 10);
  return `Working tree dirty (stage or discard changes): ${lines.join("; ")}`;
}
function stampPath(wuId, paths) {
  return paths.STAMP(wuId);
}
function checkStamp(wuId, paths, existsFn = existsSync2) {
  if (existsFn(stampPath(wuId, paths)))
    return null;
  return `Missing stamp ${paths.STAMPS_DIR()}/${wuId}.done`;
}
function checkCommit(wuId, paths, runFn = run) {
  const history = runFn(`git log --oneline ${BRANCHES.MAIN} -- ${paths.WU(wuId)} | head -n 1`);
  if (history)
    return null;
  return `No commit on ${BRANCHES.MAIN} touching ${paths.WU(wuId)}`;
}
function verifyWUComplete(wuId, overrides = {}) {
  const normalized = formatWUId(wuId);
  const failures = [];
  const runFn = typeof overrides.run === "function" ? overrides.run : run;
  const existsFn = typeof overrides.exists === "function" ? overrides.exists : (filePath) => existsSync2(filePath);
  const paths = createWuPaths({ projectRoot: overrides.projectRoot });
  const gitStatusFailure = checkGitStatus(runFn);
  if (gitStatusFailure)
    failures.push(gitStatusFailure);
  const stampFailure = checkStamp(normalized, paths, existsFn);
  if (stampFailure)
    failures.push(stampFailure);
  const commitFailure = checkCommit(normalized, paths, runFn);
  if (commitFailure)
    failures.push(commitFailure);
  return {
    complete: failures.length === 0,
    failures
  };
}
function debugSummary(result) {
  if (!result || typeof result !== "object") {
    return "No verification result";
  }
  if (result.complete) {
    return "Verification passed: WU complete.";
  }
  const failures = Array.isArray(result.failures) ? result.failures : [];
  if (!failures.length) {
    return "Verification failed: unknown reason.";
  }
  return `Verification failed:${STRING_LITERALS.NEWLINE}- ${failures.join(`${STRING_LITERALS.NEWLINE}- `)}`;
}
var isDirectExecution = (() => {
  if (typeof process === "undefined")
    return false;
  if (!Array.isArray(process.argv))
    return false;
  if (!process.argv[1])
    return false;
  try {
    return fileURLToPath(import.meta.url) === process.argv[1];
  } catch {
    return false;
  }
})();
if (isDirectExecution) {
  const wuId = process.argv[2] ?? "";
  try {
    const result = verifyWUComplete(wuId);
    const message = debugSummary(result);
    console.log(message);
    process.exit(result.complete ? EXIT_CODES.SUCCESS : EXIT_CODES.ERROR);
  } catch (error) {
    console.error(`Verification error: ${error instanceof Error ? error.message : String(error)}`);
    process.exit(EXIT_CODES.ERROR);
  }
}

// ../agent/dist/feedback-promote-core.js
import fs from "fs/promises";
import path from "path";
var DRAFT_DIRECTORY = LUMENFLOW_PATHS.FEEDBACK_DRAFTS;
var FEEDBACK_INDEX_PATH = LUMENFLOW_PATHS.FEEDBACK_INDEX;
var LANES = {
  OPERATIONS_TOOLING: "Operations: Tooling",
  OPERATIONS_DOCUMENTATION: "Operations: Documentation",
  OPERATIONS_SECURITY: "Operations: Security",
  OPERATIONS_COMPLIANCE: "Operations: Compliance",
  OPERATIONS: "Operations",
  CORE_SYSTEMS: "Core Systems",
  EXPERIENCE: "Experience",
  INTELLIGENCE: "Intelligence"
};
var CATEGORY_TO_LANE = {
  test: LANES.OPERATIONS_TOOLING,
  tooling: LANES.OPERATIONS_TOOLING,
  docs: LANES.OPERATIONS_DOCUMENTATION,
  documentation: LANES.OPERATIONS_DOCUMENTATION,
  infrastructure: LANES.CORE_SYSTEMS,
  database: LANES.CORE_SYSTEMS,
  api: LANES.CORE_SYSTEMS,
  ui: LANES.EXPERIENCE,
  frontend: LANES.EXPERIENCE,
  ux: LANES.EXPERIENCE,
  llm: LANES.INTELLIGENCE,
  prompt: LANES.INTELLIGENCE,
  ai: LANES.INTELLIGENCE,
  security: LANES.OPERATIONS_SECURITY,
  compliance: LANES.OPERATIONS_COMPLIANCE,
  uncategorized: LANES.OPERATIONS
};

// ../agent/dist/feedback-review-core.js
import fs2 from "fs/promises";
import path2 from "path";
var SEVERITY_WEIGHTS = {
  [INCIDENT_SEVERITY.BLOCKER]: 4,
  [INCIDENT_SEVERITY.MAJOR]: 3,
  [INCIDENT_SEVERITY.MINOR]: 2,
  [INCIDENT_SEVERITY.INFO]: 1
};
var RECENCY_DECAY_MS = 30 * MS_PER_DAY;
var DURATION_MULTIPLIERS = {
  m: MS_PER_MINUTE,
  // minutes
  h: MS_PER_HOUR,
  // hours
  d: MS_PER_DAY,
  // days
  w: 7 * MS_PER_DAY
  // weeks
};

export {
  startSession,
  getCurrentSession,
  logIncident,
  endSession
};
