// ../core/src/codeEditSession/index.ts
var AGENT_EDIT_SESSION_CONTRACT_VERSION = "agent_edit_session_v1";
var AGENT_EDIT_SESSION_SCHEMA_VERSION = 1;
var AGENT_EDIT_EXECUTION_POLICY_VERSION = "agent_edit_execution_policy_v1";
function buildAgentEditSessionHandoffV1(args) {
  const createdAt = args.createdAt ?? Date.now();
  const reasonCodes = uniqueStrings([
    ...args.policy.localToCloud.reasonCodes,
    ...args.reasonCodes ?? []
  ]);
  return {
    schemaVersion: AGENT_EDIT_SESSION_SCHEMA_VERSION,
    contractVersion: AGENT_EDIT_SESSION_CONTRACT_VERSION,
    handoffId: `agent-edit-handoff:${args.sourceSessionId}:${createdAt.toString(36)}`,
    sourceSessionId: args.sourceSessionId,
    editSessionId: args.editSessionId,
    projectId: args.projectId,
    repoId: args.repoId,
    targetRunner: args.policy.localToCloud.target,
    editCommands: args.editCommands ?? buildDefaultModalEditCommands(args.policy.localToCloud.carry.validationCommand),
    workroomRunId: args.workroomRunId,
    synapseReceiptRef: args.synapseReceiptRef,
    synapseWaiverRef: args.synapseWaiverRef,
    validationTrust: args.validationTrust,
    carry: {
      allowedPaths: args.policy.localToCloud.carry.allowedPaths,
      deniedPaths: args.policy.localToCloud.carry.deniedPaths,
      validationCommand: args.policy.localToCloud.carry.validationCommand,
      baselineRequired: true,
      receiptBoundContext: true,
      baseline: args.baseline,
      contextRefs: uniqueStrings(args.contextRefs ?? []),
      diagnosticEvidence: uniqueStrings(args.diagnosticEvidence ?? []),
      prompt: args.prompt,
      maxAttempts: args.maxAttempts,
      sourceRepoPath: args.sourceRepoPath
    },
    reasonCodes,
    battleProofRefs: uniqueStrings(args.battleProofRefs ?? []),
    createdAt,
    noAuthority: true
  };
}
function buildDefaultModalEditCommands(validationCommand) {
  const commands = [{
    schemaVersion: AGENT_EDIT_SESSION_SCHEMA_VERSION,
    commandKind: "edit",
    runner: "opencode_run_json",
    command: "opencode run --format json",
    argv: ["opencode", "run", "--format", "json"],
    runAfter: "dispatch",
    maxRuns: 1,
    sandboxOnly: true,
    noCanonicalApply: true
  }];
  if (validationCommand) {
    commands.push({
      schemaVersion: AGENT_EDIT_SESSION_SCHEMA_VERSION,
      commandKind: "validation",
      runner: "shell",
      command: validationCommand,
      runAfter: "edit",
      maxRuns: 1,
      sandboxOnly: true,
      noCanonicalApply: true
    });
  }
  return commands;
}
function mapAgentEditOutcomeToExecutionReceiptStatus(outcome) {
  if (outcome === "fixed")
    return "succeeded";
  if (outcome === "still_failing")
    return "failed";
  return "blocked";
}
function isAgentEditExecutionModeV1(value) {
  return value === "sandboxed" || value === "scoped" || value === "yolo";
}
function isAgentEditCallerContextV1(value) {
  return typeof value === "string" && [
    "local_cli",
    "local_app",
    "web_app",
    "cloud_worker",
    "pr_review_local",
    "pr_review_cloud",
    "review_local",
    "review_cloud",
    "api",
    "unknown"
  ].includes(value);
}
function isAgentEditWorkspaceKindV1(value) {
  return typeof value === "string" && [
    "local_worktree",
    "modal_sandbox",
    "cloud_ephemeral",
    "provider_sandbox",
    "unknown"
  ].includes(value);
}
function resolveAgentEditExecutionPolicyV1(args = {}) {
  const callerContext = args.callerContext ?? "unknown";
  const workspaceKind = args.workspaceKind ?? defaultWorkspaceKind(callerContext);
  const requestedMode = normalizeRequestedMode(args.requestedMode) ?? defaultModeForContext(callerContext, workspaceKind);
  const reviewLike = isReviewLikeContext(callerContext);
  const cloudLike = isCloudLikeContext(callerContext, workspaceKind);
  const localLike = isLocalLikeContext(callerContext, workspaceKind);
  const yoloRequested = requestedMode === "yolo";
  const yoloAllowed = yoloRequested && args.allowYolo === true && (!cloudLike && !reviewLike || args.environmentAllowsYolo === true);
  const effectiveMode = yoloAllowed ? "yolo" : requestedMode === "scoped" && !cloudLike && !reviewLike ? "scoped" : defaultModeForContext(callerContext, workspaceKind);
  const deniedPaths = uniqueStrings(args.deniedPaths ?? []);
  const allowedPaths = uniqueStrings(args.allowedPaths ?? []);
  const runnerKind = args.runnerKind ?? defaultRunnerKind(workspaceKind, callerContext);
  const editEngine = args.editEngine ?? (runnerKind === "modal" ? "opencode_run_json" : "rhei_code_session");
  const providerKind = args.providerKind ?? "workpool";
  const yoloReasonCodes = uniqueStrings([
    yoloRequested ? "yolo:requested" : undefined,
    yoloRequested && args.allowYolo !== true ? "yolo:missing_explicit_allow" : undefined,
    yoloRequested && (cloudLike || reviewLike) && args.environmentAllowsYolo !== true ? "yolo:blocked_for_cloud_or_review_without_environment_allow" : undefined,
    yoloAllowed ? "yolo:allowed_outside_allowed_paths" : undefined
  ]);
  const localToCloud = resolveLocalToCloudPolicy({
    ...args,
    callerContext,
    workspaceKind,
    allowedPaths,
    deniedPaths,
    yoloDenied: yoloRequested && !yoloAllowed
  });
  const reasonCodes = uniqueStrings([
    `caller:${callerContext}`,
    `workspace:${workspaceKind}`,
    `requested_mode:${requestedMode}`,
    `effective_mode:${effectiveMode}`,
    reviewLike ? "policy:review_defaults_to_sandbox" : undefined,
    cloudLike ? "policy:cloud_defaults_to_sandbox" : undefined,
    localLike && effectiveMode === "scoped" ? "policy:local_coding_scoped" : undefined,
    localToCloud.recommended ? "policy:local_to_cloud_available" : undefined,
    ...yoloReasonCodes
  ]);
  return {
    schemaVersion: AGENT_EDIT_SESSION_SCHEMA_VERSION,
    policyVersion: AGENT_EDIT_EXECUTION_POLICY_VERSION,
    requestedMode,
    effectiveMode,
    callerContext,
    workspaceKind,
    runnerKind,
    editEngine,
    providerKind,
    pathPolicy: {
      allowedPaths,
      deniedPaths,
      allowOutsideAllowedPaths: effectiveMode === "yolo",
      deniedPathsAlwaysBlock: true
    },
    authority: {
      sandboxMutationAllowed: effectiveMode === "sandboxed" || effectiveMode === "yolo" || runnerKind === "modal",
      canonicalApplyRequiresWriteArbitration: true,
      sourceApplyAuthority: args.sourceApplyAuthority ?? "none",
      autoApply: false,
      autoPush: false,
      autoPrComment: false,
      memoryPromotion: false
    },
    yolo: {
      requested: yoloRequested,
      allowed: yoloAllowed,
      reasonCodes: yoloReasonCodes,
      requiresExplicitOptIn: true,
      neverBypassesDeniedPaths: true,
      neverBypassesWriteArbitration: true
    },
    isolation: {
      prepCallbackMayUseNetworkAndSecrets: true,
      editSandboxReceivesCallbackSecret: false,
      singleUseContainerPreferred: runnerKind === "modal" || workspaceKind === "modal_sandbox",
      callbackSecretRequiredForCallback: runnerKind === "modal" || providerKind === "workpool"
    },
    network: {
      editValidationDefault: args.validationNeedsNetwork === true ? "allowed" : "blocked",
      installPhaseAllowed: args.installPhaseAllowed === true,
      validationCanRequestScopedInstall: true
    },
    callbacks: {
      submitAuthRequired: true,
      callbackHmacFormat: "convex_workpool_hmac_v1",
      idempotentReceiptsRequired: true,
      failClosedWithoutRunnerKey: true
    },
    localToCloud,
    reasonCodes
  };
}
function normalizeRequestedMode(value) {
  if (value === "safe")
    return "sandboxed";
  return isAgentEditExecutionModeV1(value) ? value : undefined;
}
function defaultModeForContext(callerContext, workspaceKind) {
  if (callerContext === "unknown" || workspaceKind === "unknown")
    return "sandboxed";
  if (isReviewLikeContext(callerContext) || isCloudLikeContext(callerContext, workspaceKind))
    return "sandboxed";
  return "scoped";
}
function defaultWorkspaceKind(callerContext) {
  if (callerContext === "local_cli" || callerContext === "local_app" || callerContext === "pr_review_local" || callerContext === "review_local") {
    return "local_worktree";
  }
  if (callerContext === "web_app" || callerContext === "cloud_worker" || callerContext === "pr_review_cloud" || callerContext === "review_cloud") {
    return "modal_sandbox";
  }
  return "unknown";
}
function defaultRunnerKind(workspaceKind, callerContext) {
  if (workspaceKind === "modal_sandbox" || workspaceKind === "cloud_ephemeral" || callerContext === "web_app" || callerContext === "cloud_worker")
    return "modal";
  if (workspaceKind === "local_worktree")
    return "local_cli";
  return "unknown";
}
function isLocalLikeContext(callerContext, workspaceKind) {
  return workspaceKind === "local_worktree" || callerContext === "local_cli" || callerContext === "local_app";
}
function isCloudLikeContext(callerContext, workspaceKind) {
  return workspaceKind === "modal_sandbox" || workspaceKind === "cloud_ephemeral" || workspaceKind === "provider_sandbox" || callerContext === "web_app" || callerContext === "cloud_worker" || callerContext === "pr_review_cloud" || callerContext === "review_cloud" || callerContext === "api";
}
function isReviewLikeContext(callerContext) {
  return callerContext === "pr_review_local" || callerContext === "pr_review_cloud" || callerContext === "review_local" || callerContext === "review_cloud";
}
function resolveLocalToCloudPolicy(args) {
  const localLike = isLocalLikeContext(args.callerContext, args.workspaceKind);
  const requested = args.localToCloudRequested === true;
  const reasonCodes = uniqueStrings([
    requested ? "caller_requested_cloud" : undefined,
    args.localSessionNeedsHandoff === true ? "local_session_needs_handoff" : undefined,
    args.localOperatorLeaving === true ? "operator_left_local" : undefined,
    args.yoloDenied ? "local_yolo_denied" : undefined,
    args.validationNeedsNetwork === true ? "validation_needs_network" : undefined,
    args.baselineMismatch === true || args.scopeRisk === "high" ? "baseline_or_scope_risk" : undefined,
    isReviewLikeContext(args.callerContext) ? "review_surface_requires_sandbox" : undefined,
    isCloudLikeContext(args.callerContext, args.workspaceKind) ? "web_or_cloud_default" : undefined
  ]);
  const recommended = requested || localLike && (args.localSessionNeedsHandoff === true || args.localOperatorLeaving === true || args.yoloDenied || args.validationNeedsNetwork === true) || isReviewLikeContext(args.callerContext);
  const allowed = recommended && args.cloudHandoffAllowed === true;
  return {
    requested,
    recommended,
    allowed,
    reasonCodes,
    sourceSessionId: args.sourceSessionId,
    target: {
      providerKind: "workpool",
      runnerKind: "modal",
      workspaceKind: "modal_sandbox",
      editEngine: "opencode_run_json"
    },
    carry: {
      allowedPaths: args.allowedPaths,
      deniedPaths: args.deniedPaths,
      validationCommand: args.validationCommand,
      baselineRequired: true,
      receiptBoundContext: true
    },
    nextAction: allowed ? "handoff_to_cloud" : recommended ? "offer_cloud_handoff" : "continue_local"
  };
}
function uniqueStrings(values) {
  const seen = new Set;
  const output = [];
  for (const value of values) {
    const text = value?.trim();
    if (!text || seen.has(text))
      continue;
    seen.add(text);
    output.push(text);
  }
  return output;
}
export {
  resolveAgentEditExecutionPolicyV1,
  mapAgentEditOutcomeToExecutionReceiptStatus,
  isAgentEditWorkspaceKindV1,
  isAgentEditExecutionModeV1,
  isAgentEditCallerContextV1,
  buildAgentEditSessionHandoffV1,
  AGENT_EDIT_SESSION_SCHEMA_VERSION,
  AGENT_EDIT_SESSION_CONTRACT_VERSION,
  AGENT_EDIT_EXECUTION_POLICY_VERSION
};
