// ../control-plane-sdk/dist/sync-port.js
var CONTROL_PLANE_POLICY_MODES = {
  AUTHORITATIVE: "authoritative",
  TIGHTEN_ONLY: "tighten-only",
  DEV_OVERRIDE: "dev-override"
};
var CONTROL_PLANE_POLICY_MODE_VALUES = [
  CONTROL_PLANE_POLICY_MODES.AUTHORITATIVE,
  CONTROL_PLANE_POLICY_MODES.TIGHTEN_ONLY,
  CONTROL_PLANE_POLICY_MODES.DEV_OVERRIDE
];
var DEFAULT_CONTROL_PLANE_AUTH_TOKEN_ENV = "LUMENFLOW_CONTROL_PLANE_TOKEN";
var CONTROL_PLANE_AUTH_TOKEN_ENV_PATTERN = /^[A-Z][A-Z0-9_]*$/;

// ../control-plane-sdk/dist/workspace-config.js
var CONTROL_PLANE_POLICY_MODE_SET = new Set(CONTROL_PLANE_POLICY_MODE_VALUES);
var CONTROL_PLANE_REQUIRED_FIELDS = [
  "endpoint",
  "org_id",
  "project_id",
  "sync_interval",
  "policy_mode"
];
function isObject(input) {
  return typeof input === "object" && input !== null;
}
function asPositiveInt(value, field) {
  if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
    throw new Error(`Invalid ${field}: expected a positive integer`);
  }
  return value;
}
function asNonEmptyString(value, field) {
  if (typeof value !== "string" || value.trim().length === 0) {
    throw new Error(`Invalid ${field}: expected a non-empty string`);
  }
  return value;
}
function asUrlString(value, field) {
  const parsed = asNonEmptyString(value, field);
  try {
    void new URL(parsed);
  } catch {
    throw new Error(`Invalid ${field}: expected a valid URL`);
  }
  return parsed;
}
function asPolicyMode(value) {
  if (typeof value === "string" && CONTROL_PLANE_POLICY_MODE_SET.has(value)) {
    return value;
  }
  throw new Error("Invalid control_plane.policy_mode");
}
function asEnvVarName(value, field) {
  const parsed = asNonEmptyString(value, field);
  if (!CONTROL_PLANE_AUTH_TOKEN_ENV_PATTERN.test(parsed)) {
    throw new Error(`Invalid ${field}: expected an uppercase env var name`);
  }
  return parsed;
}
function parseAuthConfig(input) {
  if (!isObject(input)) {
    throw new Error("Invalid control_plane.auth: expected an object");
  }
  return {
    token_env: asEnvVarName(input.token_env, "control_plane.auth.token_env")
  };
}
function parseControlPlaneConfig(input) {
  if (!isObject(input)) {
    throw new Error("Invalid control_plane config: expected an object");
  }
  for (const field of CONTROL_PLANE_REQUIRED_FIELDS) {
    if (!(field in input)) {
      throw new Error(`Invalid control_plane config: missing required field control_plane.${field}`);
    }
  }
  return {
    endpoint: asUrlString(input.endpoint, "control_plane.endpoint"),
    org_id: asNonEmptyString(input.org_id, "control_plane.org_id"),
    project_id: asNonEmptyString(input.project_id, "control_plane.project_id"),
    sync_interval: asPositiveInt(input.sync_interval, "control_plane.sync_interval"),
    policy_mode: asPolicyMode(input.policy_mode),
    auth: parseAuthConfig(input.auth)
  };
}
var ControlPlaneConfigSchema = {
  parse: parseControlPlaneConfig
};
var WorkspaceControlPlaneSchema = {
  parse(input) {
    if (!isObject(input)) {
      throw new Error("Invalid workspace config: expected an object");
    }
    const idRaw = input.id;
    const id = idRaw === void 0 ? void 0 : typeof idRaw === "string" && idRaw.trim().length > 0 ? idRaw : (() => {
      throw new Error("Invalid id: expected a non-empty string when provided");
    })();
    return {
      id,
      control_plane: parseControlPlaneConfig(input.control_plane)
    };
  }
};
function parseWorkspaceControlPlaneConfig(input) {
  return WorkspaceControlPlaneSchema.parse(input);
}

// ../control-plane-sdk/dist/policy-mode.js
function clonePolicySet(input) {
  return {
    default_decision: input.default_decision,
    rules: input.rules.map((rule) => ({ ...rule }))
  };
}
function isLoosening(remoteDecision, localDecision) {
  return remoteDecision === "deny" && localDecision === "allow";
}
function createWarningEvent(message, timestamp) {
  return {
    schema_version: 1,
    kind: "workspace_warning",
    timestamp,
    message
  };
}
function applyPolicyMode(input) {
  const timestamp = input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
  const remote = clonePolicySet(input.remote);
  const local = input.local;
  if (input.mode === "authoritative" || !local) {
    return {
      effective: remote,
      events: []
    };
  }
  const events = [];
  const localDefault = local.default_decision;
  if (isLoosening(remote.default_decision, localDefault)) {
    if (input.mode === "tighten-only") {
      throw new Error(`tighten-only mode rejected local policy loosening for default_decision in workspace ${input.workspace_id}`);
    }
    events.push(createWarningEvent(`dev-override allowed local policy loosening for default_decision in workspace ${input.workspace_id}`, timestamp));
  }
  const mergedRules = new Map(remote.rules.map((rule) => [rule.id, { ...rule }]));
  for (const localRule of local.rules) {
    const remoteRule = mergedRules.get(localRule.id);
    const remoteDecision = remoteRule?.decision ?? remote.default_decision;
    if (isLoosening(remoteDecision, localRule.decision)) {
      if (input.mode === "tighten-only") {
        throw new Error(`tighten-only mode rejected local policy loosening for rule ${localRule.id} in workspace ${input.workspace_id}`);
      }
      events.push(createWarningEvent(`dev-override allowed local policy loosening for rule ${localRule.id} in workspace ${input.workspace_id}`, timestamp));
    }
    mergedRules.set(localRule.id, { ...localRule });
  }
  return {
    effective: {
      default_decision: localDefault,
      rules: Array.from(mergedRules.values())
    },
    events
  };
}

// ../control-plane-sdk/dist/http/http-control-plane-sync-port.js
var API_PATH = {
  AUTHENTICATE: "/api/v1/authenticate",
  HEARTBEAT: "/api/v1/heartbeat",
  APPROVAL_REQUEST: "/api/v1/approvals/request",
  APPROVAL_RESOLVE: "/api/v1/approvals/resolve",
  APPROVAL_LIST: "/api/v1/approvals/list",
  EVENTS: "/api/v1/events",
  EVIDENCE: "/api/v1/evidence",
  TELEMETRY: "/api/v1/telemetry",
  POLICIES: "/api/v1/policies",
  CONFIG: "/api/v1/config"
};
var HTTP = {
  METHOD_POST: "POST",
  HEADER_AUTHORIZATION: "authorization",
  HEADER_CONTENT_TYPE: "content-type",
  CONTENT_TYPE_JSON: "application/json"
};
var DEFAULT_TIMEOUT_MS = 1e4;
var TIMEOUT_ERROR_PREFIX = "request timed out after";
var ERROR_NAME = {
  ABORT: "AbortError"
};
function normalizeEndpoint(endpoint) {
  return endpoint.endsWith("/") ? endpoint.slice(0, endpoint.length - 1) : endpoint;
}
function asError(error) {
  if (error instanceof Error) {
    return error;
  }
  return new Error(String(error));
}
function describeError(error) {
  return asError(error).message;
}
function asFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function asNonEmptyString2(value) {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
}
function cloneControlPlaneConfig(config) {
  return {
    ...config,
    auth: {
      ...config.auth
    }
  };
}
async function safeResponseText(response) {
  try {
    return await response.text();
  } catch {
    return "";
  }
}
var HttpControlPlaneSyncPort = class {
  config;
  endpoint;
  token;
  timeoutMs;
  fetchFn;
  logger;
  constructor(config, options = {}) {
    this.config = cloneControlPlaneConfig(config);
    this.endpoint = normalizeEndpoint(config.endpoint);
    this.fetchFn = options.fetchFn ?? fetch;
    this.logger = options.logger;
    this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
    const environment = options.environment ?? process.env;
    const rawToken = environment[config.auth.token_env];
    this.token = typeof rawToken === "string" ? rawToken.trim() : "";
    if (this.token.length === 0) {
      this.warn(`Missing auth token in env "${config.auth.token_env}". Requests may fail.`);
    }
  }
  async pullPolicies(input) {
    try {
      return await this.postJson(API_PATH.POLICIES, input);
    } catch (error) {
      this.warnFailure("pullPolicies", error);
      throw error;
    }
  }
  async pullConfig(input) {
    try {
      return await this.postJson(API_PATH.CONFIG, input);
    } catch (error) {
      this.warnFailure("pullConfig", error);
      return {
        id: input.workspace_id,
        control_plane: cloneControlPlaneConfig(this.config)
      };
    }
  }
  async pushTelemetry(input) {
    try {
      return await this.postJson(API_PATH.TELEMETRY, input);
    } catch (error) {
      this.warnFailure("pushTelemetry", error);
      return { accepted: 0 };
    }
  }
  async pushEvidence(input) {
    try {
      return await this.postJson(API_PATH.EVIDENCE, input);
    } catch (error) {
      this.warnFailure("pushEvidence", error);
      return { accepted: 0 };
    }
  }
  async pushKernelEvents(input) {
    try {
      return await this.postJson(API_PATH.EVENTS, input);
    } catch (error) {
      this.warnFailure("pushKernelEvents", error);
      throw error;
    }
  }
  async authenticate(input) {
    try {
      return await this.postJson(API_PATH.AUTHENTICATE, input);
    } catch (error) {
      this.warnFailure("authenticate", error);
      return {
        workspace_id: input.workspace_id,
        org_id: input.org_id,
        agent_id: input.agent_id,
        token: ""
      };
    }
  }
  async heartbeat(input) {
    try {
      const response = await this.postJson(API_PATH.HEARTBEAT, input);
      const normalized = {
        status: response.status ?? "ok",
        server_time: asNonEmptyString2(response.server_time) ?? (/* @__PURE__ */ new Date()).toISOString()
      };
      const nextHeartbeatMs = asFiniteNumber(response.next_heartbeat_ms);
      if (nextHeartbeatMs !== void 0) {
        normalized.next_heartbeat_ms = nextHeartbeatMs;
      }
      if (response.assignment) {
        normalized.assignment = response.assignment;
      }
      const budgetRemainingUsd = asFiniteNumber(response.budget_remaining_usd);
      if (budgetRemainingUsd !== void 0) {
        normalized.budget_remaining_usd = budgetRemainingUsd;
      }
      const coalescedSignals = asFiniteNumber(response.coalesced_signals);
      if (coalescedSignals !== void 0) {
        normalized.coalesced_signals = coalescedSignals;
      }
      return normalized;
    } catch (error) {
      this.warnFailure("heartbeat", error);
      throw error;
    }
  }
  async requestApproval(input) {
    try {
      return await this.postJson(API_PATH.APPROVAL_REQUEST, input);
    } catch (error) {
      this.warnFailure("requestApproval", error);
      throw error;
    }
  }
  async resolveApproval(input) {
    try {
      return await this.postJson(API_PATH.APPROVAL_RESOLVE, input);
    } catch (error) {
      this.warnFailure("resolveApproval", error);
      throw error;
    }
  }
  async listApprovals(input) {
    try {
      return await this.postJson(API_PATH.APPROVAL_LIST, input);
    } catch (error) {
      this.warnFailure("listApprovals", error);
      throw error;
    }
  }
  warn(message) {
    this.logger?.warn?.(`[control-plane] ${message}`);
  }
  warnFailure(operation, error) {
    this.warn(`${operation} failed: ${describeError(error)}`);
  }
  getHeaders() {
    return {
      [HTTP.HEADER_AUTHORIZATION]: `Bearer ${this.token}`,
      [HTTP.HEADER_CONTENT_TYPE]: HTTP.CONTENT_TYPE_JSON
    };
  }
  async postJson(apiPath, payload) {
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
    try {
      const response = await this.fetchFn(`${this.endpoint}${apiPath}`, {
        method: HTTP.METHOD_POST,
        headers: this.getHeaders(),
        body: JSON.stringify(payload),
        signal: controller.signal
      });
      if (!response.ok) {
        const responseText = await safeResponseText(response);
        const suffix = responseText.length > 0 ? `: ${responseText}` : "";
        throw new Error(`HTTP ${response.status}${suffix}`);
      }
      return await response.json();
    } catch (error) {
      const parsedError = asError(error);
      if (parsedError.name === ERROR_NAME.ABORT) {
        throw new Error(`${TIMEOUT_ERROR_PREFIX} ${this.timeoutMs}ms`, { cause: error });
      }
      throw parsedError;
    } finally {
      clearTimeout(timeout);
    }
  }
};
function createHttpControlPlaneSyncPort(config, logger, options = {}) {
  return new HttpControlPlaneSyncPort(config, {
    ...options,
    logger: options.logger ?? logger
  });
}

// ../control-plane-sdk/dist/mock/mock-control-plane-sync-port.js
var DEFAULT_REMOTE_POLICIES = {
  default_decision: "deny",
  rules: []
};
var DEFAULT_LOCAL_POLICIES = {
  default_decision: "deny",
  rules: []
};
var DEFAULT_SYNC_INTERVAL_SECONDS = 30;
var DEFAULT_LOCAL_OVERRIDE = false;
var MockControlPlaneSyncPort = class {
  options;
  telemetryByEndpoint = /* @__PURE__ */ new Map();
  evidenceByWorkspace = /* @__PURE__ */ new Map();
  kernelEventsByWorkspace = /* @__PURE__ */ new Map();
  constructor(options) {
    this.options = {
      ...options,
      local_override: options.local_override ?? DEFAULT_LOCAL_OVERRIDE,
      auth_token_env: options.auth_token_env ?? DEFAULT_CONTROL_PLANE_AUTH_TOKEN_ENV,
      remote_policies: options.remote_policies ?? DEFAULT_REMOTE_POLICIES,
      local_policies: options.local_policies ?? DEFAULT_LOCAL_POLICIES
    };
  }
  async pullPolicies(input) {
    const merged = applyPolicyMode({
      mode: this.options.policy_mode,
      workspace_id: input.workspace_id,
      remote: this.options.remote_policies ?? DEFAULT_REMOTE_POLICIES,
      local: this.options.local_override ? this.options.local_policies : void 0
    });
    if (merged.events.length > 0) {
      const events = this.kernelEventsByWorkspace.get(input.workspace_id) ?? [];
      this.kernelEventsByWorkspace.set(input.workspace_id, events.concat(merged.events));
    }
    return merged.effective;
  }
  async pullConfig(input) {
    return {
      id: input.workspace_id,
      control_plane: {
        endpoint: this.options.endpoint,
        org_id: this.options.org_id,
        project_id: this.options.project_id,
        sync_interval: DEFAULT_SYNC_INTERVAL_SECONDS,
        policy_mode: this.options.policy_mode,
        auth: {
          token_env: this.options.auth_token_env ?? DEFAULT_CONTROL_PLANE_AUTH_TOKEN_ENV
        }
      }
    };
  }
  async pushTelemetry(input) {
    const entries = this.telemetryByEndpoint.get(this.options.endpoint) ?? [];
    this.telemetryByEndpoint.set(this.options.endpoint, entries.concat(input.records));
    return { accepted: input.records.length };
  }
  async pushEvidence(input) {
    const entries = this.evidenceByWorkspace.get(input.workspace_id) ?? [];
    this.evidenceByWorkspace.set(input.workspace_id, entries.concat(input.evidence_refs));
    return { accepted: input.evidence_refs.length };
  }
  async pushKernelEvents(input) {
    const entries = this.kernelEventsByWorkspace.get(input.workspace_id) ?? [];
    this.kernelEventsByWorkspace.set(input.workspace_id, entries.concat(input.events));
    return { accepted: input.events.length };
  }
  async authenticate(input) {
    return {
      workspace_id: input.workspace_id,
      org_id: input.org_id,
      agent_id: input.agent_id,
      token: `mock-token:${input.workspace_id}:${input.agent_id}`
    };
  }
  async heartbeat(input) {
    let assignment;
    if (input.health?.stalled && input.wu_id) {
      assignment = {
        wu_id: input.wu_id,
        action: "abort",
        hint: "agent reported stalled heartbeat"
      };
    } else if (input.health?.busy === false && !input.wu_id) {
      assignment = {
        wu_id: "mock-wu-assignment",
        action: "claim",
        hint: "mock assignment for idle agent"
      };
    }
    return {
      status: "ok",
      server_time: (/* @__PURE__ */ new Date()).toISOString(),
      next_heartbeat_ms: DEFAULT_SYNC_INTERVAL_SECONDS * 1e3,
      ...assignment ? { assignment } : {},
      coalesced_signals: 0
    };
  }
  readTelemetryEndpoint(endpoint) {
    return (this.telemetryByEndpoint.get(endpoint) ?? []).map((record) => ({ ...record }));
  }
  readEvidence(workspaceId) {
    return [...this.evidenceByWorkspace.get(workspaceId) ?? []];
  }
  readKernelEvents(workspaceId) {
    return [...this.kernelEventsByWorkspace.get(workspaceId) ?? []];
  }
};
function createMockControlPlaneSyncPort(options) {
  return new MockControlPlaneSyncPort(options);
}

// ../control-plane-sdk/dist/mock/mock-signal-sync-port.js
var DEFAULT_PAGE_LIMIT = 50;
var CURSOR_BASE = 10;
function memoryKey(record) {
  return `${record.namespace}:${record.key}`;
}
function cloneSignal(signal) {
  return {
    ...signal,
    payload: { ...signal.payload }
  };
}
function cloneMemoryRecord(record) {
  return {
    ...record,
    value: record.value
  };
}
function parseCursor(cursor) {
  if (!cursor) {
    return 0;
  }
  const parsed = Number.parseInt(cursor, CURSOR_BASE);
  if (!Number.isFinite(parsed) || parsed < 0) {
    return 0;
  }
  return parsed;
}
function sortMemoryRecords(records) {
  return [...records].sort((a, b) => {
    if (a.updated_at === b.updated_at) {
      return memoryKey(a).localeCompare(memoryKey(b));
    }
    return a.updated_at.localeCompare(b.updated_at);
  });
}
function isStringArray(value) {
  return Array.isArray(value) && value.every((entry) => typeof entry === "string");
}
function normalizeSessionMetadata(input) {
  const metadata = {
    ...input.metadata ?? {}
  };
  if (typeof input.client_type === "string") {
    metadata.client_type = input.client_type;
  }
  if (Array.isArray(input.capabilities)) {
    metadata.capabilities = [...input.capabilities];
  }
  if (typeof input.agent_version === "string") {
    metadata.agent_version = input.agent_version;
  }
  if (typeof input.host_id === "string") {
    metadata.host_id = input.host_id;
  }
  const clientType = typeof metadata.client_type === "string" && metadata.client_type.length > 0 ? metadata.client_type : void 0;
  const capabilities = isStringArray(metadata.capabilities) ? [...metadata.capabilities] : void 0;
  const agentVersion = typeof metadata.agent_version === "string" && metadata.agent_version.length > 0 ? metadata.agent_version : void 0;
  const hostId = typeof metadata.host_id === "string" && metadata.host_id.length > 0 ? metadata.host_id : void 0;
  if (clientType) {
    metadata.client_type = clientType;
  }
  if (capabilities) {
    metadata.capabilities = capabilities;
  }
  if (agentVersion) {
    metadata.agent_version = agentVersion;
  }
  if (hostId) {
    metadata.host_id = hostId;
  }
  return {
    client_type: clientType,
    capabilities,
    agent_version: agentVersion,
    host_id: hostId,
    metadata: Object.keys(metadata).length > 0 ? metadata : void 0
  };
}
var MockSignalSyncPort = class {
  conflictKeys;
  now;
  signalsByWorkspace = /* @__PURE__ */ new Map();
  sessionsByWorkspace = /* @__PURE__ */ new Map();
  memoryByWorkspace = /* @__PURE__ */ new Map();
  constructor(options = {}) {
    this.conflictKeys = new Set(options.conflict_keys ?? []);
    this.now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
  }
  async pushSignals(input) {
    const existing = this.signalsByWorkspace.get(input.workspace_id) ?? [];
    const next = existing.concat(input.signals.map((signal) => cloneSignal({
      ...signal,
      origin: signal.origin ?? "local"
    })));
    this.signalsByWorkspace.set(input.workspace_id, next);
    return { accepted: input.signals.length };
  }
  async pullSignals(input) {
    const existing = this.signalsByWorkspace.get(input.workspace_id) ?? [];
    const start = parseCursor(input.cursor);
    const limit = input.limit ?? DEFAULT_PAGE_LIMIT;
    const slice = existing.slice(start, start + limit).map(cloneSignal);
    const nextIndex = start + slice.length;
    return {
      signals: slice,
      next_cursor: nextIndex < existing.length ? String(nextIndex) : void 0
    };
  }
  async registerSession(input) {
    const workspaceSessions = this.sessionsByWorkspace.get(input.workspace_id) ?? /* @__PURE__ */ new Map();
    const normalizedMetadata = normalizeSessionMetadata(input);
    const session = {
      workspace_id: input.workspace_id,
      session_id: input.session_id,
      agent_id: input.agent_id,
      started_at: input.started_at,
      lane: input.lane,
      wu_id: input.wu_id,
      client_type: normalizedMetadata.client_type,
      capabilities: normalizedMetadata.capabilities,
      agent_version: normalizedMetadata.agent_version,
      host_id: normalizedMetadata.host_id,
      metadata: normalizedMetadata.metadata,
      active: true,
      last_heartbeat_at: this.now()
    };
    workspaceSessions.set(input.session_id, session);
    this.sessionsByWorkspace.set(input.workspace_id, workspaceSessions);
    return { ...session };
  }
  async deregisterSession(input) {
    const workspaceSessions = this.sessionsByWorkspace.get(input.workspace_id);
    if (!workspaceSessions) {
      return { accepted: 0 };
    }
    const session = workspaceSessions.get(input.session_id);
    if (!session) {
      return { accepted: 0 };
    }
    workspaceSessions.set(input.session_id, {
      ...session,
      active: false,
      last_heartbeat_at: input.ended_at ?? this.now()
    });
    return { accepted: 1 };
  }
  async listSessions(input) {
    const workspaceSessions = this.sessionsByWorkspace.get(input.workspace_id);
    if (!workspaceSessions) {
      return { sessions: [] };
    }
    const includeInactive = input.include_inactive ?? false;
    const sessions = Array.from(workspaceSessions.values()).filter((session) => includeInactive ? true : session.active).filter((session) => input.lane ? session.lane === input.lane : true).map((session) => ({ ...session }));
    return { sessions };
  }
  async syncMemory(input) {
    const workspaceMemory = this.memoryByWorkspace.get(input.workspace_id) ?? /* @__PURE__ */ new Map();
    const conflicts = [];
    let pushed = 0;
    if (input.direction === "push" || input.direction === "bidirectional") {
      for (const localRecord of input.local_records) {
        const key = memoryKey(localRecord);
        const existing = workspaceMemory.get(key);
        const hasRevisionConflict = Boolean(existing?.revision) && Boolean(localRecord.revision) && existing?.revision !== localRecord.revision;
        const forcedConflict = this.conflictKeys.has(key) && Boolean(existing);
        if (hasRevisionConflict || forcedConflict) {
          conflicts.push({
            namespace: localRecord.namespace,
            key: localRecord.key,
            local_revision: localRecord.revision,
            remote_revision: existing?.revision,
            resolution: "manual"
          });
          continue;
        }
        workspaceMemory.set(key, cloneMemoryRecord({
          ...localRecord,
          origin: localRecord.origin ?? "local"
        }));
        pushed += 1;
      }
    }
    this.memoryByWorkspace.set(input.workspace_id, workspaceMemory);
    const allRemoteRecords = sortMemoryRecords(Array.from(workspaceMemory.values()).map(cloneMemoryRecord));
    const start = parseCursor(input.cursor);
    const limit = input.limit ?? DEFAULT_PAGE_LIMIT;
    const remoteRecords = input.direction === "pull" || input.direction === "bidirectional" ? allRemoteRecords.slice(start, start + limit) : [];
    const nextIndex = start + remoteRecords.length;
    return {
      pushed,
      pulled: remoteRecords.length,
      conflicts,
      remote_records: remoteRecords,
      next_cursor: (input.direction === "pull" || input.direction === "bidirectional") && nextIndex < allRemoteRecords.length ? String(nextIndex) : void 0
    };
  }
  readSignals(workspaceId) {
    return (this.signalsByWorkspace.get(workspaceId) ?? []).map(cloneSignal);
  }
  readSessions(workspaceId) {
    return Array.from(this.sessionsByWorkspace.get(workspaceId)?.values() ?? []).map((session) => ({
      ...session
    }));
  }
  readMemory(workspaceId) {
    return Array.from(this.memoryByWorkspace.get(workspaceId)?.values() ?? []).map(cloneMemoryRecord);
  }
};
function createMockSignalSyncPort(options = {}) {
  return new MockSignalSyncPort(options);
}

export {
  CONTROL_PLANE_POLICY_MODES,
  CONTROL_PLANE_POLICY_MODE_VALUES,
  DEFAULT_CONTROL_PLANE_AUTH_TOKEN_ENV,
  CONTROL_PLANE_AUTH_TOKEN_ENV_PATTERN,
  ControlPlaneConfigSchema,
  WorkspaceControlPlaneSchema,
  parseWorkspaceControlPlaneConfig,
  applyPolicyMode,
  HttpControlPlaneSyncPort,
  createHttpControlPlaneSyncPort,
  MockControlPlaneSyncPort,
  createMockControlPlaneSyncPort,
  MockSignalSyncPort,
  createMockSignalSyncPort
};
