/**
 * INTENT - Goal Processing
 *
 * Production-grade intent intake with validation, persistence, and audit events.
 */
import { z } from 'zod';
import type { Redis } from 'ioredis';
import { type Config } from '../common/config.js';
import { type LockService } from '../common/lock.js';
import { type TenantContext } from '../common/tenant-context.js';
import type { ID, Intent, IntentEvaluationRecord, IntentStatus, TrustLevel, TrustScore, EvaluationPayload } from '../common/types.js';
import { IntentRepository, type IntentEventRecord, type PaginatedResult } from './repository.js';
/**
 * Dependencies for IntentService
 *
 * Use these to inject dependencies for testing or custom configurations.
 * If not provided, defaults to global singletons for backward compatibility.
 */
export interface IntentServiceDependencies {
    /** Intent repository instance */
    repository?: IntentRepository;
    /** Consent service instance */
    consentService?: ConsentService;
    /** Application configuration */
    config?: Config;
    /** Redis client instance */
    redis?: Redis;
    /** Lock service instance */
    lockService?: LockService;
}
import type { IIntentService } from './types.js';
import { ConsentService } from './consent.js';
/** Export constants for use in tests and configuration */
export declare const PAYLOAD_LIMITS: {
    readonly MAX_PAYLOAD_SIZE_BYTES: number;
    readonly MAX_CONTEXT_BYTES: number;
    readonly MAX_CONTEXT_KEYS: 100;
    readonly MAX_STRING_LENGTH: 10000;
};
/**
 * Schema for validating intent payload records with size limits
 */
export declare const intentPayloadSchema: z.ZodEffects<z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodUnknown>, Record<string, unknown>, Record<string, unknown>>, Record<string, unknown>, Record<string, unknown>>;
/**
 * Action type values (aligned with @vorion/contracts ActionType enum)
 */
export declare const ACTION_TYPES: readonly ["read", "write", "delete", "execute", "communicate", "transfer"];
/**
 * Data sensitivity values (aligned with @vorion/contracts DataSensitivity enum)
 */
export declare const DATA_SENSITIVITY_LEVELS: readonly ["PUBLIC", "INTERNAL", "CONFIDENTIAL", "RESTRICTED"];
/**
 * Reversibility values (aligned with @vorion/contracts Reversibility enum)
 */
export declare const REVERSIBILITY_VALUES: readonly ["REVERSIBLE", "PARTIALLY_REVERSIBLE", "IRREVERSIBLE"];
export declare const intentSubmissionSchema: z.ZodEffects<z.ZodObject<{
    entityId: z.ZodString;
    goal: z.ZodString;
    context: z.ZodEffects<z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodUnknown>, Record<string, unknown>, Record<string, unknown>>, Record<string, unknown>, Record<string, unknown>>;
    metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
    intentType: z.ZodOptional<z.ZodString>;
    priority: z.ZodDefault<z.ZodNumber>;
    idempotencyKey: z.ZodOptional<z.ZodString>;
    /** Correlation ID for distributed tracing (auto-generated if not provided) */
    correlationId: z.ZodOptional<z.ZodString>;
    /** Action type category */
    actionType: z.ZodOptional<z.ZodEnum<["read", "write", "delete", "execute", "communicate", "transfer"]>>;
    /** Resources this intent accesses/modifies */
    resourceScope: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
    /** Data sensitivity level */
    dataSensitivity: z.ZodOptional<z.ZodEnum<["PUBLIC", "INTERNAL", "CONFIDENTIAL", "RESTRICTED"]>>;
    /** Whether action can be undone */
    reversibility: z.ZodOptional<z.ZodEnum<["REVERSIBLE", "PARTIALLY_REVERSIBLE", "IRREVERSIBLE"]>>;
    /** When this intent expires (ISO 8601 string or milliseconds from now) */
    expiresIn: z.ZodOptional<z.ZodNumber>;
    /** Source system that generated this intent */
    source: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
    priority?: number;
    intentType?: string;
    metadata?: Record<string, unknown>;
    entityId?: string;
    source?: string;
    reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
    goal?: string;
    context?: Record<string, unknown>;
    correlationId?: string;
    actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
    resourceScope?: string[];
    dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
    idempotencyKey?: string;
    expiresIn?: number;
}, {
    priority?: number;
    intentType?: string;
    metadata?: Record<string, unknown>;
    entityId?: string;
    source?: string;
    reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
    goal?: string;
    context?: Record<string, unknown>;
    correlationId?: string;
    actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
    resourceScope?: string[];
    dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
    idempotencyKey?: string;
    expiresIn?: number;
}>, {
    priority?: number;
    intentType?: string;
    metadata?: Record<string, unknown>;
    entityId?: string;
    source?: string;
    reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
    goal?: string;
    context?: Record<string, unknown>;
    correlationId?: string;
    actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
    resourceScope?: string[];
    dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
    idempotencyKey?: string;
    expiresIn?: number;
}, {
    priority?: number;
    intentType?: string;
    metadata?: Record<string, unknown>;
    entityId?: string;
    source?: string;
    reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
    goal?: string;
    context?: Record<string, unknown>;
    correlationId?: string;
    actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
    resourceScope?: string[];
    dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
    idempotencyKey?: string;
    expiresIn?: number;
}>;
export type IntentSubmission = z.infer<typeof intentSubmissionSchema>;
/**
 * Schema for bulk intent submission options
 */
export declare const bulkIntentOptionsSchema: z.ZodObject<{
    /** Stop processing on first error (default: false - continue processing all items) */
    stopOnError: z.ZodDefault<z.ZodBoolean>;
    /** Return successful items even if some fail (default: true) */
    returnPartial: z.ZodDefault<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
    stopOnError?: boolean;
    returnPartial?: boolean;
}, {
    stopOnError?: boolean;
    returnPartial?: boolean;
}>;
export type BulkIntentOptions = z.infer<typeof bulkIntentOptionsSchema>;
/**
 * Schema for bulk intent submission request
 */
export declare const bulkIntentSubmissionSchema: z.ZodObject<{
    /** Array of intents to submit (1-100 items) */
    intents: z.ZodArray<z.ZodEffects<z.ZodObject<{
        entityId: z.ZodString;
        goal: z.ZodString;
        context: z.ZodEffects<z.ZodEffects<z.ZodRecord<z.ZodString, z.ZodUnknown>, Record<string, unknown>, Record<string, unknown>>, Record<string, unknown>, Record<string, unknown>>;
        metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
        intentType: z.ZodOptional<z.ZodString>;
        priority: z.ZodDefault<z.ZodNumber>;
        idempotencyKey: z.ZodOptional<z.ZodString>;
        /** Correlation ID for distributed tracing (auto-generated if not provided) */
        correlationId: z.ZodOptional<z.ZodString>;
        /** Action type category */
        actionType: z.ZodOptional<z.ZodEnum<["read", "write", "delete", "execute", "communicate", "transfer"]>>;
        /** Resources this intent accesses/modifies */
        resourceScope: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
        /** Data sensitivity level */
        dataSensitivity: z.ZodOptional<z.ZodEnum<["PUBLIC", "INTERNAL", "CONFIDENTIAL", "RESTRICTED"]>>;
        /** Whether action can be undone */
        reversibility: z.ZodOptional<z.ZodEnum<["REVERSIBLE", "PARTIALLY_REVERSIBLE", "IRREVERSIBLE"]>>;
        /** When this intent expires (ISO 8601 string or milliseconds from now) */
        expiresIn: z.ZodOptional<z.ZodNumber>;
        /** Source system that generated this intent */
        source: z.ZodOptional<z.ZodString>;
    }, "strip", z.ZodTypeAny, {
        priority?: number;
        intentType?: string;
        metadata?: Record<string, unknown>;
        entityId?: string;
        source?: string;
        reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
        goal?: string;
        context?: Record<string, unknown>;
        correlationId?: string;
        actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
        resourceScope?: string[];
        dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
        idempotencyKey?: string;
        expiresIn?: number;
    }, {
        priority?: number;
        intentType?: string;
        metadata?: Record<string, unknown>;
        entityId?: string;
        source?: string;
        reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
        goal?: string;
        context?: Record<string, unknown>;
        correlationId?: string;
        actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
        resourceScope?: string[];
        dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
        idempotencyKey?: string;
        expiresIn?: number;
    }>, {
        priority?: number;
        intentType?: string;
        metadata?: Record<string, unknown>;
        entityId?: string;
        source?: string;
        reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
        goal?: string;
        context?: Record<string, unknown>;
        correlationId?: string;
        actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
        resourceScope?: string[];
        dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
        idempotencyKey?: string;
        expiresIn?: number;
    }, {
        priority?: number;
        intentType?: string;
        metadata?: Record<string, unknown>;
        entityId?: string;
        source?: string;
        reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
        goal?: string;
        context?: Record<string, unknown>;
        correlationId?: string;
        actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
        resourceScope?: string[];
        dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
        idempotencyKey?: string;
        expiresIn?: number;
    }>, "many">;
    /** Optional processing options */
    options: z.ZodOptional<z.ZodObject<{
        /** Stop processing on first error (default: false - continue processing all items) */
        stopOnError: z.ZodDefault<z.ZodBoolean>;
        /** Return successful items even if some fail (default: true) */
        returnPartial: z.ZodDefault<z.ZodBoolean>;
    }, "strip", z.ZodTypeAny, {
        stopOnError?: boolean;
        returnPartial?: boolean;
    }, {
        stopOnError?: boolean;
        returnPartial?: boolean;
    }>>;
}, "strip", z.ZodTypeAny, {
    options?: {
        stopOnError?: boolean;
        returnPartial?: boolean;
    };
    intents?: {
        priority?: number;
        intentType?: string;
        metadata?: Record<string, unknown>;
        entityId?: string;
        source?: string;
        reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
        goal?: string;
        context?: Record<string, unknown>;
        correlationId?: string;
        actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
        resourceScope?: string[];
        dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
        idempotencyKey?: string;
        expiresIn?: number;
    }[];
}, {
    options?: {
        stopOnError?: boolean;
        returnPartial?: boolean;
    };
    intents?: {
        priority?: number;
        intentType?: string;
        metadata?: Record<string, unknown>;
        entityId?: string;
        source?: string;
        reversibility?: "REVERSIBLE" | "PARTIALLY_REVERSIBLE" | "IRREVERSIBLE";
        goal?: string;
        context?: Record<string, unknown>;
        correlationId?: string;
        actionType?: "delete" | "read" | "write" | "execute" | "communicate" | "transfer";
        resourceScope?: string[];
        dataSensitivity?: "PUBLIC" | "INTERNAL" | "CONFIDENTIAL" | "RESTRICTED";
        idempotencyKey?: string;
        expiresIn?: number;
    }[];
}>;
export type BulkIntentSubmission = z.infer<typeof bulkIntentSubmissionSchema>;
/**
 * Result for a single failed intent in bulk submission
 */
export interface BulkIntentFailure {
    /** Index of the failed intent in the original array */
    index: number;
    /** The original input that failed */
    input: IntentSubmission;
    /** Error message describing the failure */
    error: string;
}
/**
 * Result of bulk intent submission
 */
export interface BulkIntentResult {
    /** Successfully created intents */
    successful: Intent[];
    /** Failed intents with error details */
    failed: BulkIntentFailure[];
    /** Summary statistics */
    stats: {
        /** Total number of intents in the request */
        total: number;
        /** Number of successfully created intents */
        succeeded: number;
        /** Number of failed intents */
        failed: number;
    };
}
/**
 * User role type for authorization checks
 */
export type UserRole = 'admin' | 'super_admin' | 'system' | 'user' | 'service' | string;
export interface SubmitOptions {
    /**
     * Tenant context from validated JWT.
     * Use TenantContext for secure tenant ID handling.
     */
    ctx: TenantContext;
    trustSnapshot?: Record<string, unknown> | null;
    /** Current trust level of the entity (for trust gate validation) */
    trustLevel?: TrustLevel;
    /**
     * Skip trust gate validation (use with caution)
     * @deprecated This flag is deprecated and will be removed in a future version.
     *             Only 'admin' or 'system' roles can use this flag.
     */
    bypassTrustGate?: boolean;
    /**
     * Skip consent validation (use with caution - only for system intents)
     * @deprecated This flag is deprecated and will be removed in a future version.
     *             Only 'admin' or 'system' roles can use this flag.
     */
    bypassConsentCheck?: boolean;
}
export interface ListOptions {
    /**
     * Tenant context from validated JWT.
     * Use TenantContext for secure tenant ID handling.
     */
    ctx: TenantContext;
    entityId?: ID;
    status?: IntentStatus;
    /** Page size limit (default: 50, max: 1000) */
    limit?: number;
    /** Offset for pagination (default: 0) */
    offset?: number;
    /** Cursor for pagination (last intent ID from previous page) - mutually exclusive with offset */
    cursor?: ID;
    /**
     * If true, throw an error when limit exceeds MAX_PAGE_SIZE instead of silently capping.
     * Default: false (silently cap to MAX_PAGE_SIZE for backwards compatibility)
     */
    strictLimitValidation?: boolean;
}
export interface CancelOptions {
    /**
     * Tenant context from validated JWT.
     * Use TenantContext for secure tenant ID handling.
     */
    ctx: TenantContext;
    reason: string;
    cancelledBy?: string;
}
export interface IntentWithEvents {
    intent: Intent;
    events: IntentEventRecord[];
    evaluations?: IntentEvaluationRecord[];
}
/**
 * Intent service for managing intent lifecycle
 */
export declare class IntentService implements IIntentService {
    private config;
    private redis;
    private lockService;
    private consentService;
    private repository;
    /**
     * Create a new IntentService instance.
     *
     * @param deps - Optional dependencies for dependency injection.
     *               If not provided, uses global singletons (backward compatible).
     *
     * @example
     * // Default usage (backward compatible)
     * const service = new IntentService();
     *
     * @example
     * // With dependency injection (for testing)
     * const service = new IntentService({
     *   repository: mockRepository,
     *   consentService: mockConsentService,
     *   config: testConfig,
     *   redis: mockRedis,
     *   lockService: mockLockService,
     * });
     */
    constructor(deps?: IntentServiceDependencies);
    /**
     * Check if user has a privileged role that allows bypass flags
     */
    private hasPrivilegedRole;
    /**
     * Validate and authorize bypass flag usage
     * Returns true if bypass is allowed, false otherwise
     */
    private validateBypassAuthorization;
    /**
     * Submit a new intent with trust gate validation and transaction support
     */
    submit(payload: IntentSubmission, options: SubmitOptions): Promise<Intent>;
    get(ctx: TenantContext, id: ID): Promise<Intent | null>;
    getWithEvents(ctx: TenantContext, id: ID): Promise<IntentWithEvents | null>;
    updateStatus(ctx: TenantContext, id: ID, status: IntentStatus, previousStatus?: IntentStatus, options?: {
        skipValidation?: boolean;
        hasReason?: boolean;
        hasPermission?: boolean;
    }): Promise<Intent | null>;
    /**
     * Cancel an in-flight intent
     */
    cancel(id: ID, options: CancelOptions): Promise<Intent | null>;
    /**
     * Soft delete an intent (GDPR compliant)
     */
    delete(ctx: TenantContext, id: ID): Promise<Intent | null>;
    /**
     * List intents with pagination.
     * Returns paginated results with metadata for cursor/offset-based pagination.
     *
     * @param options - List options including pagination parameters
     * @returns Paginated result with intents and pagination metadata
     */
    list(options: ListOptions): Promise<PaginatedResult<Intent>>;
    /**
     * Submit multiple intents in bulk for batch processing efficiency.
     *
     * This method processes intents sequentially, recording success/failure for each.
     * By default, it continues processing even if some intents fail.
     *
     * @param submissions - Array of intent submissions to process
     * @param options - Bulk submission options including tenantId and stopOnError flag
     * @returns BulkIntentResult with successful intents, failed intents, and statistics
     *
     * @example
     * ```typescript
     * const result = await intentService.submitBulk(
     *   [
     *     { entityId: 'uuid1', goal: 'Goal 1', context: {} },
     *     { entityId: 'uuid2', goal: 'Goal 2', context: {} },
     *   ],
     *   { ctx: tenantContext, stopOnError: false }
     * );
     * // result.stats.succeeded === 2
     * ```
     */
    submitBulk(submissions: IntentSubmission[], options: {
        ctx: TenantContext;
        stopOnError?: boolean;
        trustSnapshot?: Record<string, unknown> | null;
        trustLevel?: TrustLevel;
        bypassTrustGate?: boolean;
        bypassConsentCheck?: boolean;
    }): Promise<BulkIntentResult>;
    updateTrustMetadata(ctx: TenantContext, id: ID, trustSnapshot: Record<string, unknown> | null, trustLevel?: TrustLevel, trustScore?: TrustScore): Promise<Intent | null>;
    recordEvaluation(ctx: TenantContext, intentId: ID, payload: EvaluationPayload): Promise<IntentEvaluationRecord>;
    /**
     * Verify event chain integrity for an intent
     */
    verifyEventChain(intentId: ID): Promise<{
        valid: boolean;
        invalidAt?: number;
        error?: string;
    }>;
    /**
     * Get minimum required trust level for an intent type
     */
    getRequiredTrustLevel(intentType?: string | null): TrustLevel;
    /**
     * Validate trust gate for intent submission
     */
    private validateTrustGate;
    /**
     * Validate data processing consent for a user
     * Required for GDPR/SOC2 compliance before processing any intent
     */
    private validateDataProcessingConsent;
    /**
     * Get the consent service instance for direct consent management
     */
    getConsentService(): ConsentService;
    private enforceTenantLimits;
    /**
     * Reserve dedupe key with proper distributed locking.
     * Uses exponential backoff and proper lock semantics to handle race conditions.
     * Returns null if reservation succeeded, or an existing Intent if found after conflict.
     */
    private reserveDedupeKey;
    private resolveNamespace;
    private redactStructure;
    private applyRedaction;
    /**
     * Compute a secure deduplication hash using HMAC-SHA256.
     *
     * Security features:
     * - Uses HMAC with a secret key to prevent hash prediction attacks
     * - Includes a timestamp bucket to limit replay window
     * - Falls back to plain SHA-256 only in development (with warning)
     *
     * @param tenantId - The tenant identifier
     * @param payload - The intent submission payload
     * @returns A hex-encoded HMAC digest for deduplication
     */
    private computeDedupeHash;
    private warnedAboutMissingDedupeSecret;
}
/**
 * Create a new intent service instance with dependency injection.
 *
 * This is the preferred way to create services in production code
 * as it makes dependencies explicit and testable.
 *
 * @param deps - Optional dependencies. If not provided, uses global singletons.
 * @returns Configured IntentService instance
 *
 * @example
 * // Default usage (backward compatible)
 * const service = createIntentService();
 *
 * @example
 * // With custom dependencies
 * const service = createIntentService({
 *   repository: customRepository,
 *   config: customConfig,
 *   redis: customRedis,
 * });
 */
export declare function createIntentService(deps?: IntentServiceDependencies): IntentService;
export { ConsentService, ConsentRequiredError, ConsentPolicyNotFoundError, createConsentService, type ConsentType, type ConsentMetadata, type UserConsent, type ConsentPolicy, type ConsentHistoryEntry, type ConsentValidationResult, } from './consent.js';
export { intentOpenApiSpec, getOpenApiSpec, getOpenApiSpecJson, } from './openapi.js';
export { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE, type PaginatedResult, } from './repository.js';
export { IntentClassifier, createIntentClassifier, RiskAssessor, createRiskAssessor, type Classification, type IntentClassifierConfig, type CreateIntent, type RiskAssessment, type HistoricalPattern, type RiskAssessorConfig, type RiskFactor, type RequiredApprovals, type ApprovalType, type IntentCategory, type RiskTier, type ActionPattern, type ResourceSensitivity, ACTION_PATTERNS, RESOURCE_SENSITIVITY, matchActionPattern, matchResourceSensitivity, getResourceSensitivityLevel, getResourceRiskTier, inferCategoryFromAction, scoreToTier, tierToMinScore, requiresApproval, } from './classifier/index.js';
export type { IIntentService } from './types.js';
//# sourceMappingURL=index.d.ts.map