import { randomUUID } from "node:crypto";
export function mapWorkspace(row) {
    if (!isRecord(row))
        throw new Error("Workspace row not found.");
    return {
        id: readString(row.id, "id"),
        rootPath: readString(row.root_path, "root_path"),
        createdAt: readString(row.created_at, "created_at"),
        updatedAt: readString(row.updated_at, "updated_at"),
    };
}
export function mapRun(row) {
    if (!isRecord(row))
        throw new Error("Run row not found.");
    const lastError = typeof row.last_error === "string" ? row.last_error : undefined;
    const title = typeof row.title === "string" ? row.title : undefined;
    const runtimeSessionId = typeof row.runtime_session_id === "string"
        ? row.runtime_session_id
        : undefined;
    const sourceWorkItemId = typeof row.source_work_item_id === "string"
        ? row.source_work_item_id
        : undefined;
    const sourceRepositoryId = typeof row.source_repository_id === "string"
        ? row.source_repository_id
        : undefined;
    const sourcePreparationId = typeof row.source_preparation_id === "string"
        ? row.source_preparation_id
        : undefined;
    const sourceRunIntentId = typeof row.source_run_intent_id === "string"
        ? row.source_run_intent_id
        : undefined;
    const branchPlanId = typeof row.branch_plan_id === "string" ? row.branch_plan_id : undefined;
    const branchName = typeof row.branch_name === "string" ? row.branch_name : undefined;
    const baseBranch = typeof row.base_branch === "string" ? row.base_branch : undefined;
    const capPolicy = typeof row.cap_policy_json === "string"
        ? readRunCapPolicy(row.cap_policy_json)
        : undefined;
    const attemptCount = typeof row.attempt_count === "number" ? row.attempt_count : undefined;
    const previousRunId = typeof row.previous_run_id === "string" ? row.previous_run_id : undefined;
    return {
        id: readString(row.id, "id"),
        workspaceId: readString(row.workspace_id, "workspace_id"),
        provider: "opencode",
        status: readRunStatus(row.status),
        createdAt: readString(row.created_at, "created_at"),
        updatedAt: readString(row.updated_at, "updated_at"),
        ...(title ? { title } : {}),
        ...(runtimeSessionId ? { runtimeSessionId } : {}),
        ...(lastError ? { lastError } : {}),
        ...(sourceWorkItemId ? { sourceWorkItemId } : {}),
        ...(sourceRepositoryId ? { sourceRepositoryId } : {}),
        ...(sourcePreparationId ? { sourcePreparationId } : {}),
        ...(sourceRunIntentId ? { sourceRunIntentId } : {}),
        ...(branchPlanId ? { branchPlanId } : {}),
        ...(branchName ? { branchName } : {}),
        ...(baseBranch ? { baseBranch } : {}),
        ...(capPolicy ? { capPolicy } : {}),
        ...(attemptCount !== undefined ? { attemptCount } : {}),
        ...(previousRunId ? { previousRunId } : {}),
    };
}
export function sanitizeRunCapPolicy(policy) {
    const result = {};
    if (isSafePositiveNumber(policy.costUsdPerRun, 1_000_000)) {
        result.costUsdPerRun = Number(policy.costUsdPerRun.toFixed(4));
    }
    if (isSafePositiveNumber(policy.wallTimeSecondsPerRun, 86_400)) {
        result.wallTimeSecondsPerRun = Math.trunc(policy.wallTimeSecondsPerRun);
    }
    return result;
}
export function readRunCapPolicy(value) {
    try {
        const parsed = JSON.parse(value);
        if (!isRecord(parsed))
            return undefined;
        const candidate = {};
        if (typeof parsed.costUsdPerRun === "number") {
            candidate.costUsdPerRun = parsed.costUsdPerRun;
        }
        if (typeof parsed.wallTimeSecondsPerRun === "number") {
            candidate.wallTimeSecondsPerRun = parsed.wallTimeSecondsPerRun;
        }
        const policy = sanitizeRunCapPolicy(candidate);
        return Object.keys(policy).length > 0 ? policy : undefined;
    }
    catch {
        return undefined;
    }
}
export function isSafePositiveNumber(value, max) {
    return (typeof value === "number" &&
        Number.isFinite(value) &&
        value > 0 &&
        value <= max);
}
export function mapRunEvidence(row) {
    if (!isRecord(row))
        throw new Error("Run proof evidence row not found.");
    return {
        runId: readString(row.run_id, "run_id"),
        changedFiles: readJsonArray(row.changed_files_json, "changed_files_json"),
        validations: readJsonArray(row.validations_json, "validations_json"),
        warnings: readJsonArray(row.warnings_json, "warnings_json"),
        patchFiles: readJsonArrayOrEmpty(row.patch_files_json, "patch_files_json"),
        createdAt: readString(row.created_at, "created_at"),
        updatedAt: readString(row.updated_at, "updated_at"),
    };
}
export function mapRuntimeEvent(row) {
    if (!isRecord(row))
        throw new Error("Runtime event row not found.");
    const runId = typeof row.run_id === "string" ? row.run_id : undefined;
    const runtimeSessionId = typeof row.runtime_session_id === "string"
        ? row.runtime_session_id
        : undefined;
    return {
        id: readString(row.id, "id"),
        source: readRuntimeEventSource(row.source),
        type: readString(row.type, "type"),
        occurredAt: readString(row.occurred_at, "occurred_at"),
        title: readString(row.title, "title"),
        description: readString(row.description, "description"),
        tone: readRuntimeEventTone(row.tone),
        metadata: readRuntimeEventMetadata(row.metadata_json),
        createdAt: readString(row.created_at, "created_at"),
        ...(runId ? { runId } : {}),
        ...(runtimeSessionId ? { runtimeSessionId } : {}),
    };
}
export function mapPermissionRequest(row) {
    if (!isRecord(row))
        throw new Error("Permission request row not found.");
    const runId = typeof row.run_id === "string" ? row.run_id : undefined;
    const providerRequestId = typeof row.provider_request_id === "string"
        ? row.provider_request_id
        : undefined;
    const providerPermissionId = typeof row.provider_permission_id === "string"
        ? row.provider_permission_id
        : undefined;
    const sourceRuntimeEventId = typeof row.source_runtime_event_id === "string"
        ? row.source_runtime_event_id
        : undefined;
    const selectedOption = typeof row.selected_option === "string" ? row.selected_option : undefined;
    const opencodeReply = readOptionalOpenCodeReply(row.opencode_reply);
    const decisionAuditId = typeof row.decision_audit_id === "string"
        ? row.decision_audit_id
        : undefined;
    const lastError = typeof row.last_error === "string" ? row.last_error : undefined;
    const answeredAt = typeof row.answered_at === "string" ? row.answered_at : undefined;
    return {
        id: readString(row.id, "id"),
        workspaceId: readString(row.workspace_id, "workspace_id"),
        provider: readPermissionRequestProvider(row.provider),
        runtimeSessionId: readString(row.runtime_session_id, "runtime_session_id"),
        requestJson: readString(row.request_json, "request_json"),
        evaluationJson: readString(row.evaluation_json, "evaluation_json"),
        status: readPermissionRequestStatus(row.status),
        createdAt: readString(row.created_at, "created_at"),
        updatedAt: readString(row.updated_at, "updated_at"),
        ...(runId ? { runId } : {}),
        ...(providerRequestId ? { providerRequestId } : {}),
        ...(providerPermissionId ? { providerPermissionId } : {}),
        ...(sourceRuntimeEventId ? { sourceRuntimeEventId } : {}),
        ...(selectedOption ? { selectedOption } : {}),
        ...(opencodeReply ? { opencodeReply } : {}),
        ...(decisionAuditId ? { decisionAuditId } : {}),
        ...(lastError ? { lastError } : {}),
        ...(answeredAt ? { answeredAt } : {}),
    };
}
export function mapPermissionRequestActivityEvent(row) {
    if (!isRecord(row))
        throw new Error("Permission request activity row not found.");
    const kind = readPermissionRequestActivityKind(row.activity_kind);
    const request = mapPermissionRequest(row);
    const toolCall = readPermissionActivityToolCall(request.requestJson);
    const externalServiceMutation = readPermissionExternalMutation(request.requestJson);
    const denyOnlyDiagnostics = readPermissionDenyOnlyDiagnostics(request.requestJson);
    const base = {
        id: readString(row.activity_id, "activity_id"),
        kind,
        at: readString(row.activity_at, "activity_at"),
        source: "opencode",
        workspaceId: request.workspaceId,
        ...(request.runId ? { runId: request.runId } : {}),
        runtimeSessionId: request.runtimeSessionId,
        requestId: request.id,
        ...toolCall,
        ...(externalServiceMutation ? { externalServiceMutation: true } : {}),
        ...(denyOnlyDiagnostics ? { denyOnlyDiagnostics } : {}),
    };
    if (kind === "request_created") {
        return {
            ...base,
            status: "pending",
        };
    }
    if (kind === "request_answered") {
        return {
            ...base,
            status: "answered",
            ...(request.selectedOption
                ? { selectedOption: request.selectedOption }
                : {}),
            ...(request.opencodeReply
                ? { opencodeReply: request.opencodeReply }
                : {}),
        };
    }
    return {
        ...base,
        status: "reply_failed",
        ...(request.selectedOption
            ? { selectedOption: request.selectedOption }
            : {}),
        ...(request.opencodeReply ? { opencodeReply: request.opencodeReply } : {}),
        ...(request.lastError ? { error: request.lastError } : {}),
    };
}
export function mapPermissionDecisionActivityEvent(row) {
    if (!isRecord(row))
        throw new Error("Permission decision activity row not found.");
    const kind = readPermissionDecisionActivityKind(row.activity_kind);
    const decision = mapPermissionDecision(row);
    const base = {
        id: readString(row.activity_id, "activity_id"),
        kind,
        at: readString(row.activity_at, "activity_at"),
        source: "opencode",
        workspaceId: decision.workspaceId,
        ...(decision.runId ? { runId: decision.runId } : {}),
        ...(decision.runtimeSessionId
            ? { runtimeSessionId: decision.runtimeSessionId }
            : {}),
        decisionId: decision.id,
        toolName: decision.toolName,
        toolTitle: decision.toolTitle,
        toolRisk: decision.toolRisk,
        inputPreview: decision.inputPreview,
        affectedPathsJson: decision.affectedPathsJson,
    };
    if (kind === "session_decision_recorded") {
        return {
            ...base,
            status: "active",
            selectedOption: decision.option,
            ...(decision.sourcePermissionRequestId
                ? { requestId: decision.sourcePermissionRequestId }
                : {}),
        };
    }
    return {
        ...base,
        status: "revoked",
        selectedOption: decision.option,
        ...(decision.sourcePermissionRequestId
            ? { requestId: decision.sourcePermissionRequestId }
            : {}),
        ...(decision.revokeReason ? { revokeReason: decision.revokeReason } : {}),
        ...(decision.revokeSource ? { revokeSource: decision.revokeSource } : {}),
    };
}
export function mapPermissionActivityEvent(row) {
    if (!isRecord(row))
        throw new Error("Permission activity row not found.");
    const kind = readPermissionActivityKind(row.kind);
    const runId = typeof row.run_id === "string" ? row.run_id : undefined;
    const runtimeSessionId = typeof row.runtime_session_id === "string"
        ? row.runtime_session_id
        : undefined;
    const requestId = typeof row.request_id === "string" ? row.request_id : undefined;
    const decisionId = typeof row.decision_id === "string" ? row.decision_id : undefined;
    const selectedOption = typeof row.selected_option === "string" ? row.selected_option : undefined;
    const opencodeReply = readOptionalOpenCodeReply(row.opencode_reply);
    const externalServiceMutation = row.external_service_mutation === 1;
    const denyOnlyDiagnostics = readPermissionDenyOnlyDiagnosticsJson(row.deny_only_diagnostics_json);
    const error = typeof row.error === "string" ? row.error : undefined;
    const revokeReason = typeof row.revoke_reason === "string" ? row.revoke_reason : undefined;
    const revokeSource = readPermissionDecisionRevokeSource(row.revoke_source);
    const status = readPermissionActivityStatus(kind, row.status);
    return {
        id: readString(row.id, "id"),
        kind,
        at: readString(row.activity_at, "activity_at"),
        source: readRuntimeEventSource(row.source),
        workspaceId: readString(row.workspace_id, "workspace_id"),
        toolName: readString(row.tool_name, "tool_name"),
        toolTitle: readString(row.tool_title, "tool_title"),
        toolRisk: readString(row.tool_risk, "tool_risk"),
        inputPreview: readString(row.input_preview, "input_preview"),
        affectedPathsJson: readString(row.affected_paths_json, "affected_paths_json"),
        ...(runId ? { runId } : {}),
        ...(runtimeSessionId ? { runtimeSessionId } : {}),
        ...(requestId ? { requestId } : {}),
        ...(decisionId ? { decisionId } : {}),
        ...(status ? { status } : {}),
        ...(selectedOption ? { selectedOption } : {}),
        ...(opencodeReply ? { opencodeReply } : {}),
        ...(externalServiceMutation ? { externalServiceMutation: true } : {}),
        ...(denyOnlyDiagnostics ? { denyOnlyDiagnostics } : {}),
        ...(error ? { error } : {}),
        ...(revokeReason ? { revokeReason } : {}),
        ...(revokeSource ? { revokeSource } : {}),
    };
}
export function readPermissionActivityKind(value) {
    if (value === "request_created" ||
        value === "request_answered" ||
        value === "request_reply_failed" ||
        value === "session_decision_recorded" ||
        value === "session_decision_revoked") {
        return value;
    }
    throw new Error(`Invalid permission activity kind: ${String(value)}`);
}
export function readPermissionActivityStatus(kind, value) {
    if (typeof value !== "string")
        return undefined;
    if (kind === "request_created" ||
        kind === "request_answered" ||
        kind === "request_reply_failed") {
        return readPermissionRequestStatus(value);
    }
    return readPermissionDecisionStatus(value);
}
export function readPermissionRequestActivityKind(value) {
    if (value === "request_created" ||
        value === "request_answered" ||
        value === "request_reply_failed") {
        return value;
    }
    throw new Error(`Invalid permission request activity kind: ${String(value)}`);
}
export function readPermissionDecisionActivityKind(value) {
    if (value === "session_decision_recorded" ||
        value === "session_decision_revoked") {
        return value;
    }
    throw new Error(`Invalid permission decision activity kind: ${String(value)}`);
}
export function readPermissionActivityToolCall(requestJson) {
    try {
        const parsed = JSON.parse(requestJson);
        const toolCall = isRecord(parsed) && isRecord(parsed.toolCall)
            ? parsed.toolCall
            : undefined;
        if (!toolCall)
            return unknownPermissionActivityToolCall();
        const affectedPaths = Array.isArray(toolCall.affectedPaths)
            ? toolCall.affectedPaths.filter((item) => typeof item === "string")
            : [];
        const name = typeof toolCall.name === "string" ? toolCall.name : "unknown";
        return {
            toolName: name,
            toolTitle: typeof toolCall.title === "string" ? toolCall.title : name,
            toolRisk: typeof toolCall.risk === "string" ? toolCall.risk : "read",
            inputPreview: typeof toolCall.inputPreview === "string"
                ? toolCall.inputPreview
                : name,
            affectedPathsJson: JSON.stringify(affectedPaths),
        };
    }
    catch {
        return unknownPermissionActivityToolCall();
    }
}
export function unknownPermissionActivityToolCall() {
    return {
        toolName: "unknown",
        toolTitle: "Unknown tool",
        toolRisk: "read",
        inputPreview: "Permission request details unavailable.",
        affectedPathsJson: "[]",
    };
}
export function readPermissionExternalMutation(requestJson) {
    try {
        const parsed = JSON.parse(requestJson);
        return isRecord(parsed) && parsed.externalServiceMutation === true;
    }
    catch {
        return false;
    }
}
export function readPermissionDenyOnlyDiagnostics(requestJson) {
    try {
        const parsed = JSON.parse(requestJson);
        if (!isRecord(parsed) || !isRecord(parsed.denyOnlyDiagnostics)) {
            return undefined;
        }
        const diagnostics = parsed.denyOnlyDiagnostics;
        if (diagnostics.policyClass !== "external_service_mutation") {
            return undefined;
        }
        const riskReason = typeof diagnostics.riskReason === "string"
            ? diagnostics.riskReason.slice(0, 500)
            : undefined;
        const evidence = Array.isArray(diagnostics.evidence)
            ? diagnostics.evidence
                .filter((item) => typeof item === "string")
                .map((item) => item.slice(0, 120))
                .slice(0, 10)
            : [];
        if (!riskReason || evidence.length === 0)
            return undefined;
        return {
            policyClass: "external_service_mutation",
            riskReason,
            evidence,
        };
    }
    catch {
        return undefined;
    }
}
export function readPermissionDenyOnlyDiagnosticsJson(value) {
    if (typeof value !== "string")
        return undefined;
    try {
        const parsed = JSON.parse(value);
        if (!isRecord(parsed) ||
            parsed.policyClass !== "external_service_mutation") {
            return undefined;
        }
        const riskReason = typeof parsed.riskReason === "string"
            ? parsed.riskReason.slice(0, 500)
            : undefined;
        const evidence = Array.isArray(parsed.evidence)
            ? parsed.evidence
                .filter((item) => typeof item === "string")
                .map((item) => item.slice(0, 120))
                .slice(0, 10)
            : [];
        if (!riskReason || evidence.length === 0)
            return undefined;
        return {
            policyClass: "external_service_mutation",
            riskReason,
            evidence,
        };
    }
    catch {
        return undefined;
    }
}
export function mapPermissionDecision(row) {
    if (!isRecord(row))
        throw new Error("Permission decision row not found.");
    const runId = typeof row.run_id === "string" ? row.run_id : undefined;
    const runtimeSessionId = typeof row.runtime_session_id === "string"
        ? row.runtime_session_id
        : undefined;
    const sourcePermissionRequestId = typeof row.source_permission_request_id === "string"
        ? row.source_permission_request_id
        : undefined;
    const revokedAt = typeof row.revoked_at === "string" ? row.revoked_at : undefined;
    const revokeAuditId = typeof row.revoke_audit_id === "string" ? row.revoke_audit_id : undefined;
    const revokeReason = typeof row.revoke_reason === "string" ? row.revoke_reason : undefined;
    const revokeSource = readPermissionDecisionRevokeSource(row.revoke_source);
    return {
        id: readString(row.id, "id"),
        workspaceId: readString(row.workspace_id, "workspace_id"),
        scope: readString(row.scope, "scope"),
        effect: readPermissionDecisionEffect(row.effect),
        option: readString(row.option, "option"),
        capabilitiesJson: readString(row.capabilities_json, "capabilities_json"),
        pattern: readString(row.pattern, "pattern"),
        toolName: readString(row.tool_name, "tool_name"),
        toolTitle: readString(row.tool_title, "tool_title"),
        toolRisk: readString(row.tool_risk, "tool_risk"),
        inputPreview: readString(row.input_preview, "input_preview"),
        affectedPathsJson: readString(row.affected_paths_json, "affected_paths_json"),
        auditId: readString(row.audit_id, "audit_id"),
        status: readPermissionDecisionStatus(row.status),
        createdAt: readString(row.created_at, "created_at"),
        updatedAt: readString(row.updated_at, "updated_at"),
        ...(runId ? { runId } : {}),
        ...(runtimeSessionId ? { runtimeSessionId } : {}),
        ...(sourcePermissionRequestId ? { sourcePermissionRequestId } : {}),
        ...(revokedAt ? { revokedAt } : {}),
        ...(revokeAuditId ? { revokeAuditId } : {}),
        ...(revokeReason ? { revokeReason } : {}),
        ...(revokeSource ? { revokeSource } : {}),
    };
}
export function mapOutboxEvent(row) {
    if (!isRecord(row))
        throw new Error("Outbox event row not found.");
    return {
        id: readString(row.id, "id"),
        type: readString(row.type, "type"),
        aggregateId: readString(row.aggregate_id, "aggregate_id"),
        payloadJson: readString(row.payload_json, "payload_json"),
        status: readOutboxStatus(row.status),
        attempts: readNumber(row.attempts, "attempts"),
        createdAt: readString(row.created_at, "created_at"),
        updatedAt: readString(row.updated_at, "updated_at"),
    };
}
export function mapDebugRevealEvent(row) {
    if (!isRecord(row))
        throw new Error("Debug reveal event row not found.");
    const expiresAt = typeof row.expires_at === "string" ? row.expires_at : undefined;
    const ttlSeconds = typeof row.ttl_seconds === "number" ? row.ttl_seconds : undefined;
    const reasonLabel = typeof row.reason_label === "string" ? row.reason_label : undefined;
    return {
        id: readString(row.id, "id"),
        workspaceId: readString(row.workspace_id, "workspace_id"),
        revealSessionId: readString(row.reveal_session_id, "reveal_session_id"),
        kind: readDebugRevealEventKind(row.kind),
        eventAt: readString(row.event_at, "event_at"),
        surfaces: readDebugRevealSurfaces(row.surfaces_json),
        createdAt: readString(row.created_at, "created_at"),
        ...(expiresAt ? { expiresAt } : {}),
        ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
        ...(reasonLabel ? { reasonLabel } : {}),
    };
}
export function debugRevealSessionStatusFromEvent(event, now) {
    if (!event.expiresAt || event.ttlSeconds === undefined)
        return undefined;
    const ttlRemainingSeconds = Math.max(0, Math.ceil((new Date(event.expiresAt).getTime() - now.getTime()) / 1_000));
    return {
        id: event.revealSessionId,
        activatedAt: event.eventAt,
        expiresAt: event.expiresAt,
        ttlSeconds: event.ttlSeconds,
        ttlRemainingSeconds,
        surfaces: [...event.surfaces],
        ...(event.reasonLabel ? { reasonLabel: event.reasonLabel } : {}),
    };
}
export function readString(value, name) {
    if (typeof value !== "string") {
        throw new Error(`Expected string column ${name}.`);
    }
    return value;
}
export function readNumber(value, name) {
    if (typeof value !== "number") {
        throw new Error(`Expected number column ${name}.`);
    }
    return value;
}
export function readJsonArray(value, name) {
    const parsed = JSON.parse(readString(value, name));
    return Array.isArray(parsed) ? parsed : [];
}
export function readJsonArrayOrEmpty(value, name) {
    if (value === null || value === undefined)
        return [];
    return readJsonArray(value, name);
}
export function readRunStatus(value) {
    if (value === "queued" ||
        value === "running" ||
        value === "completed" ||
        value === "failed" ||
        value === "cancelled" ||
        value === "blocked-budget" ||
        value === "blocked-timeout" ||
        value === "blocked-concurrency") {
        return value;
    }
    throw new Error(`Invalid run status: ${String(value)}`);
}
export function readRuntimeEventSource(value) {
    if (value === "opencode")
        return value;
    throw new Error(`Invalid runtime event source: ${String(value)}`);
}
export function readRuntimeEventTone(value) {
    if (value === "primary" ||
        value === "success" ||
        value === "warning" ||
        value === "destructive" ||
        value === "muted") {
        return value;
    }
    throw new Error(`Invalid runtime event tone: ${String(value)}`);
}
export function readRuntimeEventMetadata(value) {
    const parsed = JSON.parse(readString(value, "metadata_json"));
    if (!isRecord(parsed))
        return {};
    const metadata = {};
    for (const [key, entry] of Object.entries(parsed)) {
        if (typeof entry === "string" ||
            typeof entry === "number" ||
            typeof entry === "boolean" ||
            entry === null) {
            metadata[key] = entry;
        }
    }
    return metadata;
}
export function readPermissionRequestProvider(value) {
    if (value === "opencode")
        return value;
    throw new Error(`Invalid permission request provider: ${String(value)}`);
}
export function readPermissionRequestStatus(value) {
    if (value === "pending" ||
        value === "replying" ||
        value === "answered" ||
        value === "reply_failed") {
        return value;
    }
    throw new Error(`Invalid permission request status: ${String(value)}`);
}
export function readPermissionDecisionStatus(value) {
    if (value === "active" || value === "revoked")
        return value;
    throw new Error(`Invalid permission decision status: ${String(value)}`);
}
export function readPermissionDecisionEffect(value) {
    if (value === "allow" || value === "deny")
        return value;
    throw new Error(`Invalid permission decision effect: ${String(value)}`);
}
export function readPermissionDecisionRevokeSource(value) {
    if (value === "local_ui" || value === "bridge_api" || value === "unknown") {
        return value;
    }
    return undefined;
}
export function readOptionalOpenCodeReply(value) {
    if (value === "once" || value === "always" || value === "reject")
        return value;
    return undefined;
}
export function readOutboxStatus(value) {
    if (value === "pending" || value === "sent" || value === "failed") {
        return value;
    }
    throw new Error(`Invalid outbox status: ${String(value)}`);
}
export function readDebugRevealEventKind(value) {
    if (value === "activated" || value === "revoked" || value === "expired") {
        return value;
    }
    throw new Error(`Invalid debug reveal event kind: ${String(value)}`);
}
export function readDebugRevealSurfaces(value) {
    if (typeof value !== "string")
        return [];
    try {
        const parsed = JSON.parse(value);
        if (!Array.isArray(parsed))
            return [];
        return parsed.filter((item) => typeof item === "string");
    }
    catch {
        return [];
    }
}
export function normalizeAffectedPathsJson(value) {
    try {
        const parsed = JSON.parse(value);
        if (!Array.isArray(parsed))
            return "[]";
        return JSON.stringify(parsed.filter((item) => typeof item === "string"));
    }
    catch {
        return "[]";
    }
}
export function isPermissionSessionDecisionActivity(decision) {
    return (decision.scope === "session" &&
        decision.effect === "allow" &&
        decision.option === "allow_for_session");
}
export function createPermissionActivityEventId() {
    return `pact_${process.hrtime.bigint().toString(36).padStart(16, "0")}_${randomUUID()}`;
}
export function isRecord(value) {
    return typeof value === "object" && value !== null && !Array.isArray(value);
}
