import {
  CONFIG_FILES,
  FILE_EXTENSIONS,
  LUMENFLOW_PATHS,
  STDIO,
  STRING_LITERALS
} from "./chunk-DWMLTXKQ.js";

// ../core/dist/telemetry.js
import { appendFileSync, mkdirSync, existsSync, readFileSync, writeFileSync } from "fs";
import { execSync } from "child_process";
import path from "path";
import YAML from "yaml";
var TELEMETRY_DIR = LUMENFLOW_PATHS.TELEMETRY;
var GATES_LOG = `${TELEMETRY_DIR}/gates${FILE_EXTENSIONS.NDJSON}`;
var LLM_CLASSIFICATION_LOG = `${TELEMETRY_DIR}/llm-classification${FILE_EXTENSIONS.NDJSON}`;
var COSTS_LOG = `${TELEMETRY_DIR}/costs${FILE_EXTENSIONS.NDJSON}`;
var FLOW_LOG = LUMENFLOW_PATHS.FLOW_LOG;
var DORA_LOG = `${TELEMETRY_DIR}/dora${FILE_EXTENSIONS.NDJSON}`;
var WORKSPACE_FILE = CONFIG_FILES.WORKSPACE_CONFIG;
var CLOUD_SYNC_STATE_FILE = `${TELEMETRY_DIR}/cloud-sync-state${FILE_EXTENSIONS.JSON}`;
var CLOUD_SYNC_LOG_PREFIX = "[telemetry:cloud-sync]";
var PACK_KEY_SOFTWARE_DELIVERY = "software_delivery";
var CONTROL_PLANE_FIELD = "control_plane";
var CONTROL_PLANE_AUTH_FIELD = "auth";
var CONTROL_PLANE_ENDPOINT_FIELD = "endpoint";
var CONTROL_PLANE_SYNC_INTERVAL_FIELD = "sync_interval";
var CONTROL_PLANE_BATCH_SIZE_FIELD = "batch_size";
var CONTROL_PLANE_TIMEOUT_MS_FIELD = "timeout_ms";
var CONTROL_PLANE_TOKEN_ENV_FIELD = "token_env";
var WORKSPACE_ID_FIELD = "id";
var HTTP = {
  METHOD_POST: "POST",
  HEADER_AUTHORIZATION: "authorization",
  HEADER_CONTENT_TYPE: "content-type",
  CONTENT_TYPE_JSON: "application/json"
};
var CONTROL_PLANE_API_PATH = {
  TELEMETRY: "/api/v1/telemetry"
};
var DEFAULT_BATCH_SIZE = 100;
var DEFAULT_TIMEOUT_MS = 1e4;
var MS_PER_SECOND = 1e3;
var ERROR_NAME = {
  ABORT: "AbortError"
};
var CONTROL_PLANE_TOKEN_ENV_PATTERN = /^[A-Z][A-Z0-9_]*$/;
var METRIC_NAME = {
  GATES_DURATION_MS: "gates.duration_ms",
  FLOW_EVENT: "flow.event",
  DORA_METRIC: "dora",
  COST_USD: "cost.usd",
  RAW_GATES: "telemetry.raw.gates",
  RAW_FLOW: "telemetry.raw.flow",
  RAW_DORA: "telemetry.raw.dora",
  RAW_COSTS: "telemetry.raw.costs"
};
var TELEMETRY_SOURCE = {
  GATES: "gates",
  FLOW: "flow",
  DORA: "dora",
  COSTS: "costs"
};
function ensureTelemetryDir() {
  try {
    mkdirSync(TELEMETRY_DIR, { recursive: true });
  } catch {
  }
}
function emit(filePath, event) {
  ensureTelemetryDir();
  const line = `${JSON.stringify(event)}${STRING_LITERALS.NEWLINE}`;
  try {
    appendFileSync(filePath, line, { encoding: "utf-8" });
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.error(`[telemetry] Failed to emit to ${filePath}:`, message);
  }
}
function emitGateEvent(data) {
  const event = {
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    wu_id: data.wu_id || null,
    lane: data.lane || null,
    gate_name: data.gate_name,
    passed: data.passed,
    duration_ms: data.duration_ms
  };
  emit(GATES_LOG, event);
}
function getCurrentWU() {
  try {
    const branch = execSync("git rev-parse --abbrev-ref HEAD", {
      encoding: "utf-8",
      stdio: [STDIO.PIPE, STDIO.PIPE, STDIO.IGNORE]
    }).trim();
    const match = branch.match(/wu-(\d+)/i);
    if (match) {
      return `WU-${match[1]}`.toUpperCase();
    }
  } catch {
  }
  return null;
}
function getCurrentLane() {
  try {
    const branch = execSync("git rev-parse --abbrev-ref HEAD", {
      encoding: "utf-8",
      stdio: [STDIO.PIPE, STDIO.PIPE, STDIO.IGNORE]
    }).trim();
    const match = branch.match(/^lane\/([^/]+)\//i);
    const laneSegment = match?.[1];
    if (laneSegment) {
      return laneSegment.charAt(0).toUpperCase() + laneSegment.slice(1).toLowerCase();
    }
  } catch {
  }
  return null;
}
function emitWUFlowEvent(event, logPath = FLOW_LOG) {
  const logDir = path.dirname(logPath);
  if (!existsSync(logDir)) {
    mkdirSync(logDir, { recursive: true });
  }
  const line = JSON.stringify({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), ...event });
  try {
    appendFileSync(logPath, `${line}${STRING_LITERALS.NEWLINE}`, { encoding: "utf-8" });
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.error(`[telemetry] Failed to emit flow event: ${message}`);
  }
}
function emitDoraTelemetry(record) {
  ensureTelemetryDir();
  const line = JSON.stringify({
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    metric: record.metric,
    value: record.value,
    tier: record.tier
  });
  try {
    appendFileSync(DORA_LOG, `${line}${STRING_LITERALS.NEWLINE}`, { encoding: "utf-8" });
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    console.error(`[telemetry] Failed to emit DORA telemetry: ${message}`);
  }
}
function isRecord(value) {
  return typeof value === "object" && value !== null;
}
function asNonEmptyString(value) {
  if (typeof value !== "string") {
    return void 0;
  }
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : void 0;
}
function asPositiveInteger(value) {
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
    return void 0;
  }
  return value;
}
function asFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function asPrimitiveTagValue(value) {
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
    return value;
  }
  return void 0;
}
function normalizeEndpoint(endpoint) {
  return endpoint.endsWith("/") ? endpoint.slice(0, endpoint.length - 1) : endpoint;
}
function normalizeTimestamp(value, fallbackIso) {
  const rawTimestamp = asNonEmptyString(value);
  return rawTimestamp ?? fallbackIso;
}
function warnCloudSync(logger, message) {
  logger?.warn?.(`${CLOUD_SYNC_LOG_PREFIX} ${message}`);
}
function createDefaultCloudSyncState() {
  return {
    version: 1,
    lastSyncAtMs: 0,
    files: {
      gates: {
        offset: 0
      },
      flow: {
        offset: 0
      },
      dora: {
        offset: 0
      },
      costs: {
        offset: 0
      }
    }
  };
}
function normalizeStateOffset(value) {
  if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
    return 0;
  }
  return value;
}
function loadCloudSyncState(statePath) {
  if (!existsSync(statePath)) {
    return createDefaultCloudSyncState();
  }
  try {
    const raw = readFileSync(statePath, "utf-8");
    const parsed = JSON.parse(raw);
    if (!isRecord(parsed)) {
      return createDefaultCloudSyncState();
    }
    const filesRaw = Reflect.get(parsed, "files");
    const gatesRaw = isRecord(filesRaw) ? Reflect.get(filesRaw, TELEMETRY_SOURCE.GATES) : void 0;
    const flowRaw = isRecord(filesRaw) ? Reflect.get(filesRaw, TELEMETRY_SOURCE.FLOW) : void 0;
    const doraRaw = isRecord(filesRaw) ? Reflect.get(filesRaw, TELEMETRY_SOURCE.DORA) : void 0;
    const costsRaw = isRecord(filesRaw) ? Reflect.get(filesRaw, TELEMETRY_SOURCE.COSTS) : void 0;
    const gatesOffset = isRecord(gatesRaw) ? normalizeStateOffset(Reflect.get(gatesRaw, "offset")) : 0;
    const flowOffset = isRecord(flowRaw) ? normalizeStateOffset(Reflect.get(flowRaw, "offset")) : 0;
    const doraOffset = isRecord(doraRaw) ? normalizeStateOffset(Reflect.get(doraRaw, "offset")) : 0;
    const costsOffset = isRecord(costsRaw) ? normalizeStateOffset(Reflect.get(costsRaw, "offset")) : 0;
    const lastSyncAtMs = normalizeStateOffset(Reflect.get(parsed, "lastSyncAtMs"));
    return {
      version: 1,
      lastSyncAtMs,
      files: {
        gates: {
          offset: gatesOffset
        },
        flow: {
          offset: flowOffset
        },
        dora: {
          offset: doraOffset
        },
        costs: {
          offset: costsOffset
        }
      }
    };
  } catch {
    return createDefaultCloudSyncState();
  }
}
function saveCloudSyncState(statePath, state) {
  mkdirSync(path.dirname(statePath), { recursive: true });
  writeFileSync(statePath, `${JSON.stringify(state, null, 2)}${STRING_LITERALS.NEWLINE}`, {
    encoding: "utf-8"
  });
}
function getSourceOffset(state, source) {
  if (source === TELEMETRY_SOURCE.GATES) {
    return state.files.gates.offset;
  }
  if (source === TELEMETRY_SOURCE.DORA) {
    return state.files.dora.offset;
  }
  if (source === TELEMETRY_SOURCE.COSTS) {
    return state.files.costs.offset;
  }
  return state.files.flow.offset;
}
function setSourceOffset(state, source, offset) {
  if (source === TELEMETRY_SOURCE.GATES) {
    state.files.gates.offset = offset;
    return;
  }
  if (source === TELEMETRY_SOURCE.DORA) {
    state.files.dora.offset = offset;
    return;
  }
  if (source === TELEMETRY_SOURCE.COSTS) {
    state.files.costs.offset = offset;
    return;
  }
  state.files.flow.offset = offset;
}
function resolveTelemetryPath(workspaceRoot, source) {
  if (source === TELEMETRY_SOURCE.GATES) {
    return path.join(workspaceRoot, GATES_LOG);
  }
  if (source === TELEMETRY_SOURCE.DORA) {
    return path.join(workspaceRoot, DORA_LOG);
  }
  if (source === TELEMETRY_SOURCE.COSTS) {
    return path.join(workspaceRoot, COSTS_LOG);
  }
  return path.join(workspaceRoot, FLOW_LOG);
}
function mapGatesEventToTelemetryRecord(payload, fallbackIso) {
  const gateName = asNonEmptyString(Reflect.get(payload, "gate_name")) ?? "unknown";
  const passedRaw = Reflect.get(payload, "passed");
  const passed = typeof passedRaw === "boolean" ? passedRaw : false;
  const durationMs = asFiniteNumber(Reflect.get(payload, "duration_ms")) ?? 0;
  const wuId = asPrimitiveTagValue(Reflect.get(payload, "wu_id"));
  const lane = asPrimitiveTagValue(Reflect.get(payload, "lane"));
  const tags = {
    source: TELEMETRY_SOURCE.GATES,
    gate_name: gateName,
    passed
  };
  if (wuId !== void 0) {
    tags.wu_id = wuId;
  }
  if (lane !== void 0) {
    tags.lane = lane;
  }
  return {
    metric: METRIC_NAME.GATES_DURATION_MS,
    value: durationMs,
    timestamp: normalizeTimestamp(Reflect.get(payload, "timestamp"), fallbackIso),
    tags
  };
}
function mapFlowEventToTelemetryRecord(payload, fallbackIso) {
  const script = asNonEmptyString(Reflect.get(payload, "script")) ?? "unknown";
  const step = asNonEmptyString(Reflect.get(payload, "step")) ?? asNonEmptyString(Reflect.get(payload, "event_type")) ?? "event";
  const value = asFiniteNumber(Reflect.get(payload, "duration_ms")) ?? 1;
  const status = asPrimitiveTagValue(Reflect.get(payload, "status"));
  const wuId = asPrimitiveTagValue(Reflect.get(payload, "wu_id"));
  const lane = asPrimitiveTagValue(Reflect.get(payload, "lane"));
  const tags = {
    source: TELEMETRY_SOURCE.FLOW,
    script,
    step
  };
  if (status !== void 0) {
    tags.status = status;
  }
  if (wuId !== void 0) {
    tags.wu_id = wuId;
  }
  if (lane !== void 0) {
    tags.lane = lane;
  }
  return {
    metric: METRIC_NAME.FLOW_EVENT,
    value,
    timestamp: normalizeTimestamp(Reflect.get(payload, "timestamp"), fallbackIso),
    tags
  };
}
function mapDoraEventToTelemetryRecord(payload, fallbackIso) {
  const metric = asNonEmptyString(Reflect.get(payload, "metric")) ?? "dora.unknown";
  const value = asFiniteNumber(Reflect.get(payload, "value")) ?? 0;
  const tier = asNonEmptyString(Reflect.get(payload, "tier"));
  const tags = {
    source: TELEMETRY_SOURCE.DORA
  };
  if (tier !== void 0) {
    tags.tier = tier;
  }
  return {
    metric,
    value,
    timestamp: normalizeTimestamp(Reflect.get(payload, "timestamp"), fallbackIso),
    tags
  };
}
function mapCostEventToTelemetryRecord(payload, fallbackIso) {
  const costUsd = asFiniteNumber(Reflect.get(payload, "cost_usd")) ?? 0;
  const inputTokens = asFiniteNumber(Reflect.get(payload, "input_tokens"));
  const outputTokens = asFiniteNumber(Reflect.get(payload, "output_tokens"));
  const operation = asPrimitiveTagValue(Reflect.get(payload, "operation"));
  const model = asPrimitiveTagValue(Reflect.get(payload, "model"));
  const wuId = asPrimitiveTagValue(Reflect.get(payload, "wu_id"));
  const agentId = asPrimitiveTagValue(Reflect.get(payload, "agent_id"));
  const sessionId = asPrimitiveTagValue(Reflect.get(payload, "session_id"));
  const tags = {
    source: TELEMETRY_SOURCE.COSTS,
    source_type: "cost"
  };
  if (operation !== void 0) {
    tags.operation = operation;
  }
  if (model !== void 0) {
    tags.model = model;
  }
  if (wuId !== void 0) {
    tags.wu_id = wuId;
  }
  if (agentId !== void 0) {
    tags.agent_id = agentId;
  }
  if (sessionId !== void 0) {
    tags.session_id = sessionId;
  }
  if (inputTokens !== void 0) {
    tags.input_tokens = inputTokens;
  }
  if (outputTokens !== void 0) {
    tags.output_tokens = outputTokens;
  }
  return {
    metric: METRIC_NAME.COST_USD,
    value: costUsd,
    timestamp: normalizeTimestamp(Reflect.get(payload, "timestamp"), fallbackIso),
    tags
  };
}
function resolveRawMetricName(source) {
  if (source === TELEMETRY_SOURCE.GATES)
    return METRIC_NAME.RAW_GATES;
  if (source === TELEMETRY_SOURCE.DORA)
    return METRIC_NAME.RAW_DORA;
  if (source === TELEMETRY_SOURCE.COSTS)
    return METRIC_NAME.RAW_COSTS;
  return METRIC_NAME.RAW_FLOW;
}
function mapTelemetryLineToRecord(source, payload, fallbackIso) {
  if (!isRecord(payload)) {
    return {
      metric: resolveRawMetricName(source),
      value: 1,
      timestamp: fallbackIso,
      tags: {
        source
      }
    };
  }
  if (source === TELEMETRY_SOURCE.GATES) {
    return mapGatesEventToTelemetryRecord(payload, fallbackIso);
  }
  if (source === TELEMETRY_SOURCE.DORA) {
    return mapDoraEventToTelemetryRecord(payload, fallbackIso);
  }
  if (source === TELEMETRY_SOURCE.COSTS) {
    return mapCostEventToTelemetryRecord(payload, fallbackIso);
  }
  return mapFlowEventToTelemetryRecord(payload, fallbackIso);
}
function readTelemetryLinesFromOffset(input) {
  if (!existsSync(input.filePath)) {
    return {
      items: [],
      malformedLines: 0,
      effectiveOffset: 0
    };
  }
  const fileBuffer = readFileSync(input.filePath);
  const fileSize = fileBuffer.byteLength;
  const effectiveOffset = Math.min(input.initialOffset, fileSize);
  const sliceBuffer = fileBuffer.subarray(effectiveOffset);
  const content = sliceBuffer.toString("utf-8");
  let malformedLines = 0;
  const items = [];
  let cursor = 0;
  let runningOffset = effectiveOffset;
  while (cursor < content.length) {
    const newlineIndex = content.indexOf(STRING_LITERALS.NEWLINE, cursor);
    if (newlineIndex < 0) {
      break;
    }
    const lineWithNewline = content.slice(cursor, newlineIndex + 1);
    runningOffset += Buffer.byteLength(lineWithNewline, "utf8");
    const line = content.slice(cursor, newlineIndex).trim();
    cursor = newlineIndex + 1;
    if (line.length === 0) {
      items.push({
        record: null,
        offsetAfterLine: runningOffset
      });
      continue;
    }
    try {
      const parsed = JSON.parse(line);
      items.push({
        record: mapTelemetryLineToRecord(input.source, parsed, input.fallbackIso),
        offsetAfterLine: runningOffset
      });
    } catch {
      malformedLines += 1;
      warnCloudSync(input.logger, `Skipping malformed NDJSON line in ${input.filePath} at offset ${runningOffset}.`);
      items.push({
        record: null,
        offsetAfterLine: runningOffset
      });
    }
  }
  return {
    items,
    malformedLines,
    effectiveOffset
  };
}
function safeResponseText(response) {
  return response.text().catch(() => "");
}
async function pushTelemetryBatch(input) {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), input.timeoutMs);
  try {
    const response = await input.fetchFn(`${input.endpoint}${CONTROL_PLANE_API_PATH.TELEMETRY}`, {
      method: HTTP.METHOD_POST,
      headers: {
        [HTTP.HEADER_AUTHORIZATION]: `Bearer ${input.token}`,
        [HTTP.HEADER_CONTENT_TYPE]: HTTP.CONTENT_TYPE_JSON
      },
      body: JSON.stringify({
        workspace_id: input.workspaceId,
        records: input.records
      }),
      signal: controller.signal
    });
    if (!response.ok) {
      const responseText = await safeResponseText(response);
      const suffix = responseText.length > 0 ? `: ${responseText}` : "";
      throw new Error(`HTTP ${response.status}${suffix}`);
    }
  } catch (error) {
    if (error instanceof Error && error.name === ERROR_NAME.ABORT) {
      throw new Error(`request timed out after ${input.timeoutMs}ms`, { cause: error });
    }
    throw error;
  } finally {
    clearTimeout(timeout);
  }
}
function detectMisnestedControlPlane(workspace) {
  const rootControlPlane = Reflect.get(workspace, CONTROL_PLANE_FIELD);
  if (isRecord(rootControlPlane)) {
    return null;
  }
  const softwareDelivery = Reflect.get(workspace, PACK_KEY_SOFTWARE_DELIVERY);
  if (!isRecord(softwareDelivery)) {
    return null;
  }
  const nestedControlPlane = Reflect.get(softwareDelivery, CONTROL_PLANE_FIELD);
  if (!isRecord(nestedControlPlane)) {
    return null;
  }
  const detectedPath = `${PACK_KEY_SOFTWARE_DELIVERY}.${CONTROL_PLANE_FIELD}`;
  return {
    message: `${CONTROL_PLANE_FIELD} is misnested under ${PACK_KEY_SOFTWARE_DELIVERY}. It must be a root-level key in workspace.yaml.`,
    detectedPath,
    remediation: `Move ${CONTROL_PLANE_FIELD} to the workspace root. Run: pnpm config:set --key control_plane.<sub-key> --value <value>`
  };
}
function resolveCloudSyncConfig(input) {
  const workspacePath = path.join(input.workspaceRoot, WORKSPACE_FILE);
  if (!existsSync(workspacePath)) {
    return null;
  }
  let parsedWorkspace;
  try {
    parsedWorkspace = YAML.parse(readFileSync(workspacePath, "utf-8"));
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    warnCloudSync(input.logger, `Unable to parse workspace config: ${message}`);
    return null;
  }
  if (!isRecord(parsedWorkspace)) {
    return null;
  }
  const workspaceId = asNonEmptyString(Reflect.get(parsedWorkspace, WORKSPACE_ID_FIELD));
  if (!workspaceId) {
    warnCloudSync(input.logger, "Skipping sync: workspace id is missing in workspace.yaml.");
    return null;
  }
  const controlPlaneRaw = Reflect.get(parsedWorkspace, CONTROL_PLANE_FIELD);
  if (!isRecord(controlPlaneRaw)) {
    const misnesting = detectMisnestedControlPlane(parsedWorkspace);
    if (misnesting) {
      warnCloudSync(input.logger, misnesting.message);
      warnCloudSync(input.logger, misnesting.remediation);
    }
    return null;
  }
  const endpoint = asNonEmptyString(Reflect.get(controlPlaneRaw, CONTROL_PLANE_ENDPOINT_FIELD));
  const syncIntervalSeconds = asPositiveInteger(Reflect.get(controlPlaneRaw, CONTROL_PLANE_SYNC_INTERVAL_FIELD));
  const batchSize = asPositiveInteger(Reflect.get(controlPlaneRaw, CONTROL_PLANE_BATCH_SIZE_FIELD)) ?? DEFAULT_BATCH_SIZE;
  const timeoutMs = asPositiveInteger(Reflect.get(controlPlaneRaw, CONTROL_PLANE_TIMEOUT_MS_FIELD)) ?? DEFAULT_TIMEOUT_MS;
  if (!endpoint || !syncIntervalSeconds) {
    warnCloudSync(input.logger, "Skipping sync: control_plane endpoint and sync_interval must be configured.");
    return null;
  }
  const authRaw = Reflect.get(controlPlaneRaw, CONTROL_PLANE_AUTH_FIELD);
  if (!isRecord(authRaw)) {
    warnCloudSync(input.logger, "Skipping sync: control_plane.auth is missing.");
    return null;
  }
  const tokenEnv = asNonEmptyString(Reflect.get(authRaw, CONTROL_PLANE_TOKEN_ENV_FIELD));
  if (!tokenEnv || !CONTROL_PLANE_TOKEN_ENV_PATTERN.test(tokenEnv)) {
    warnCloudSync(input.logger, "Skipping sync: control_plane.auth.token_env is invalid.");
    return null;
  }
  const tokenValue = input.environment[tokenEnv];
  const token = typeof tokenValue === "string" ? tokenValue.trim() : "";
  if (token.length === 0) {
    warnCloudSync(input.logger, `Skipping sync: missing cloud auth token in env "${tokenEnv}".`);
    return null;
  }
  try {
    void new URL(endpoint);
  } catch {
    warnCloudSync(input.logger, `Skipping sync: invalid control_plane endpoint "${endpoint}".`);
    return null;
  }
  return {
    workspaceId,
    endpoint: normalizeEndpoint(endpoint),
    token,
    syncIntervalMs: syncIntervalSeconds * MS_PER_SECOND,
    batchSize,
    timeoutMs
  };
}
async function syncNdjsonTelemetryToCloud(options = {}) {
  const workspaceRoot = options.workspaceRoot ?? process.cwd();
  const logger = options.logger;
  const fetchFn = options.fetchFn ?? fetch;
  const now = options.now ?? Date.now;
  const environment = options.environment ?? process.env;
  const statePath = path.join(workspaceRoot, CLOUD_SYNC_STATE_FILE);
  const config = resolveCloudSyncConfig({
    workspaceRoot,
    environment,
    logger
  });
  if (config === null) {
    return {
      recordsRead: 0,
      recordsSent: 0,
      malformedLines: 0,
      batchesAttempted: 0,
      batchesSucceeded: 0,
      skippedReason: "control-plane-unavailable"
    };
  }
  const state = loadCloudSyncState(statePath);
  const nowMs = now();
  if (state.lastSyncAtMs > 0 && nowMs - state.lastSyncAtMs < config.syncIntervalMs) {
    return {
      recordsRead: 0,
      recordsSent: 0,
      malformedLines: 0,
      batchesAttempted: 0,
      batchesSucceeded: 0,
      skippedReason: "sync-interval-not-elapsed"
    };
  }
  const fallbackIso = new Date(nowMs).toISOString();
  const nextState = {
    version: 1,
    lastSyncAtMs: state.lastSyncAtMs,
    files: {
      gates: { offset: state.files.gates.offset },
      flow: { offset: state.files.flow.offset },
      dora: { offset: state.files.dora.offset },
      costs: { offset: state.files.costs.offset }
    }
  };
  let malformedLines = 0;
  let recordsRead = 0;
  let recordsSent = 0;
  let batchesAttempted = 0;
  let batchesSucceeded = 0;
  let syncFailed = false;
  let stateChanged = false;
  for (const source of [
    TELEMETRY_SOURCE.GATES,
    TELEMETRY_SOURCE.FLOW,
    TELEMETRY_SOURCE.DORA,
    TELEMETRY_SOURCE.COSTS
  ]) {
    const filePath = resolveTelemetryPath(workspaceRoot, source);
    const sourceLines = readTelemetryLinesFromOffset({
      filePath,
      source,
      initialOffset: getSourceOffset(nextState, source),
      logger,
      fallbackIso
    });
    malformedLines += sourceLines.malformedLines;
    let acknowledgedOffset = sourceLines.effectiveOffset;
    let index = 0;
    while (index < sourceLines.items.length) {
      const currentLine = sourceLines.items[index];
      if (currentLine?.record === null) {
        acknowledgedOffset = currentLine.offsetAfterLine;
        stateChanged = true;
        index += 1;
        continue;
      }
      const batch = [];
      let lastBatchOffset = acknowledgedOffset;
      while (index < sourceLines.items.length && sourceLines.items[index]?.record !== null && batch.length < config.batchSize) {
        const line = sourceLines.items[index];
        if (!line || line.record === null) {
          break;
        }
        batch.push(line.record);
        lastBatchOffset = line.offsetAfterLine;
        index += 1;
      }
      recordsRead += batch.length;
      batchesAttempted += 1;
      try {
        await pushTelemetryBatch({
          endpoint: config.endpoint,
          workspaceId: config.workspaceId,
          token: config.token,
          timeoutMs: config.timeoutMs,
          records: batch,
          fetchFn
        });
        recordsSent += batch.length;
        batchesSucceeded += 1;
        acknowledgedOffset = lastBatchOffset;
        stateChanged = true;
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        warnCloudSync(logger, `Telemetry sync failed: ${message}`);
        syncFailed = true;
        break;
      }
    }
    setSourceOffset(nextState, source, acknowledgedOffset);
    if (syncFailed) {
      break;
    }
  }
  if (stateChanged) {
    if (!syncFailed) {
      nextState.lastSyncAtMs = nowMs;
    }
    saveCloudSyncState(statePath, nextState);
  } else if (!syncFailed) {
    nextState.lastSyncAtMs = nowMs;
    saveCloudSyncState(statePath, nextState);
  }
  return {
    recordsRead,
    recordsSent,
    malformedLines,
    batchesAttempted,
    batchesSucceeded,
    ...syncFailed ? { skippedReason: "sync-failed" } : {}
  };
}

// ../core/dist/spawn-policy-resolver.js
function emitMethodologyTelemetry(config, policy) {
  if (!config.telemetry?.methodology?.enabled) {
    return;
  }
  const event = {
    timestamp: (/* @__PURE__ */ new Date()).toISOString(),
    event_type: "methodology.selection",
    methodology_testing: policy.testing,
    methodology_architecture: policy.architecture,
    event_context: "spawn"
  };
  emit(LUMENFLOW_PATHS.METHODOLOGY_LOG, event);
}

export {
  emit,
  emitGateEvent,
  getCurrentWU,
  getCurrentLane,
  emitWUFlowEvent,
  emitDoraTelemetry,
  syncNdjsonTelemetryToCloud,
  emitMethodologyTelemetry
};
