// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Vorion LLC
/**
 * Semantic Governance Types - Layer 5
 *
 * Core types for semantic governance addressing the "confused deputy" problem
 * where authenticated agents can be manipulated via prompt injection.
 *
 * This module provides:
 * - Instruction Integrity (binding agents to approved prompts)
 * - Output Schema Binding (constraining agent output)
 * - Inference Scope Controls (limiting derived knowledge)
 * - Context Authentication (securing the data plane)
 * - Dual-Channel Authorization (separating control from data)
 *
 * @packageDocumentation
 * @module @vorionsys/semantic-governance
 */
import { z } from 'zod';
export const DomainCodeSchema = z.enum(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'S']);
/**
 * Trust tiers indicating verification level
 */
export var TrustTier;
(function (TrustTier) {
    /** Sandbox — isolated testing */
    TrustTier[TrustTier["T0_SANDBOX"] = 0] = "T0_SANDBOX";
    /** Observed — read-only, monitored */
    TrustTier[TrustTier["T1_OBSERVED"] = 1] = "T1_OBSERVED";
    /** Provisional — basic operations, heavy supervision */
    TrustTier[TrustTier["T2_PROVISIONAL"] = 2] = "T2_PROVISIONAL";
    /** Monitored — standard operations, continuous monitoring */
    TrustTier[TrustTier["T3_MONITORED"] = 3] = "T3_MONITORED";
    /** Standard — external API access, policy-governed */
    TrustTier[TrustTier["T4_STANDARD"] = 4] = "T4_STANDARD";
    /** Trusted — cross-agent communication, delegated tasks */
    TrustTier[TrustTier["T5_TRUSTED"] = 5] = "T5_TRUSTED";
    /** Certified — admin tasks, agent spawning, minimal oversight */
    TrustTier[TrustTier["T6_CERTIFIED"] = 6] = "T6_CERTIFIED";
    /** Autonomous — full autonomy, self-governance */
    TrustTier[TrustTier["T7_AUTONOMOUS"] = 7] = "T7_AUTONOMOUS";
})(TrustTier || (TrustTier = {}));
export const TrustTierSchema = z.nativeEnum(TrustTier);
export const InstructionTemplateSchema = z.object({
    id: z.string().min(1),
    hash: z.string().regex(/^sha256:[a-f0-9]{64}$/, 'Must be a valid SHA-256 hash'),
    description: z.string(),
    parameterSchema: z.record(z.unknown()),
});
export const InstructionSourceSchema = z.object({
    allowedSources: z.array(z.string()),
    requireSignature: z.boolean(),
});
export const InstructionIntegritySchema = z.object({
    allowedInstructionHashes: z.array(z.string().regex(/^sha256:[a-f0-9]{64}$/, 'Must be a valid SHA-256 hash')),
    instructionTemplates: z.array(InstructionTemplateSchema),
    instructionSource: InstructionSourceSchema,
});
export const InstructionValidationResultSchema = z.object({
    valid: z.boolean(),
    method: z.enum(['exact-match', 'template-match', 'signed-source']).optional(),
    templateId: z.string().optional(),
    reason: z.string().optional(),
    instructionHash: z.string().optional(),
    extractedParams: z.record(z.unknown()).optional(),
});
export const TemplateMatchResultSchema = z.object({
    matches: z.boolean(),
    templateId: z.string().optional(),
    extractedParams: z.record(z.unknown()).optional(),
    confidence: z.number().min(0).max(1).optional(),
});
export const OutputSchemaSchema = z.object({
    id: z.string().min(1),
    description: z.string(),
    jsonSchema: z.record(z.unknown()),
});
export const ProhibitedPatternSchema = z.object({
    type: z.enum(['regex', 'keyword', 'semantic']),
    pattern: z.string().min(1),
    description: z.string(),
    severity: z.enum(['low', 'medium', 'high', 'critical']).optional(),
});
export const OutputBindingSchema = z.object({
    allowedSchemas: z.array(OutputSchemaSchema),
    prohibitedPatterns: z.array(ProhibitedPatternSchema),
    allowedExternalEndpoints: z.array(z.string()),
    blockedExternalEndpoints: z.array(z.string()),
});
export const PatternScanResultSchema = z.object({
    detected: z.boolean(),
    patterns: z.array(z.object({
        type: z.enum(['regex', 'keyword', 'semantic']),
        pattern: z.string(),
        description: z.string(),
        matches: z.array(z.string()),
        severity: z.enum(['low', 'medium', 'high', 'critical']).optional(),
    })),
    severity: z.enum(['low', 'medium', 'high', 'critical']).optional(),
});
export const OutputValidationResultSchema = z.object({
    valid: z.boolean(),
    modified: z.boolean().optional(),
    output: z.unknown().optional(),
    schemaId: z.string().optional(),
    reason: z.string().optional(),
    patternScan: PatternScanResultSchema.optional(),
});
export const SanitizedOutputSchema = z.object({
    content: z.unknown(),
    modified: z.boolean(),
    redactions: z.array(z.object({
        type: z.string(),
        description: z.string(),
        count: z.number(),
    })),
});
// =============================================================================
// INFERENCE SCOPE TYPES
// =============================================================================
/**
 * Inference scope levels
 */
export var InferenceLevel;
(function (InferenceLevel) {
    /** No inference; raw data passthrough only */
    InferenceLevel[InferenceLevel["NONE"] = 0] = "NONE";
    /** Aggregates, counts, averages */
    InferenceLevel[InferenceLevel["STATISTICAL"] = 1] = "STATISTICAL";
    /** Named entity extraction */
    InferenceLevel[InferenceLevel["ENTITY"] = 2] = "ENTITY";
    /** Relationship inference */
    InferenceLevel[InferenceLevel["RELATIONAL"] = 3] = "RELATIONAL";
    /** Pattern prediction */
    InferenceLevel[InferenceLevel["PREDICTIVE"] = 4] = "PREDICTIVE";
    /** Full inference capability */
    InferenceLevel[InferenceLevel["UNRESTRICTED"] = 5] = "UNRESTRICTED";
})(InferenceLevel || (InferenceLevel = {}));
export const InferenceLevelSchema = z.nativeEnum(InferenceLevel);
/**
 * Inference level names for display
 */
export const INFERENCE_LEVEL_NAMES = {
    [InferenceLevel.NONE]: 'None',
    [InferenceLevel.STATISTICAL]: 'Statistical',
    [InferenceLevel.ENTITY]: 'Entity',
    [InferenceLevel.RELATIONAL]: 'Relational',
    [InferenceLevel.PREDICTIVE]: 'Predictive',
    [InferenceLevel.UNRESTRICTED]: 'Unrestricted',
};
export const DomainInferenceOverrideSchema = z.object({
    domain: DomainCodeSchema,
    level: InferenceLevelSchema,
    reason: z.string(),
});
export const DerivedKnowledgeHandlingSchema = z.object({
    retention: z.enum(['none', 'session', 'persistent']),
    allowedRecipients: z.array(z.string()),
    crossContextSharing: z.boolean(),
});
export const PIIInferenceConfigSchema = z.object({
    allowed: z.boolean(),
    handling: z.enum(['block', 'redact', 'hash']),
});
export const InferenceScopeSchema = z.object({
    globalLevel: InferenceLevelSchema,
    domainOverrides: z.array(DomainInferenceOverrideSchema),
    derivedKnowledgeHandling: DerivedKnowledgeHandlingSchema,
    piiInference: PIIInferenceConfigSchema,
});
export const InferenceOperationTypeSchema = z.enum([
    'aggregate',
    'count',
    'average',
    'entity-extraction',
    'relationship-inference',
    'pattern-prediction',
    'sentiment-analysis',
    'classification',
    'summarization',
    'custom',
]);
export const InferenceOperationSchema = z.object({
    type: InferenceOperationTypeSchema,
    sourceDomains: z.array(DomainCodeSchema),
    description: z.string().optional(),
    customLevel: InferenceLevelSchema.optional(),
});
export const DerivedKnowledgeSchema = z.object({
    id: z.string(),
    type: InferenceOperationTypeSchema,
    sourceIds: z.array(z.string()),
    sourceDomains: z.array(DomainCodeSchema),
    content: z.unknown(),
    createdAt: z.date(),
    inferenceLevel: InferenceLevelSchema,
});
export const InferenceValidationResultSchema = z.object({
    valid: z.boolean(),
    reason: z.string().optional(),
    requiredLevel: InferenceLevelSchema.optional(),
    agentLevel: InferenceLevelSchema.optional(),
    restrictedDomain: DomainCodeSchema.optional(),
});
export const HandlingResultSchema = z.object({
    action: z.enum(['stored', 'discarded', 'shared', 'redacted']),
    reason: z.string(),
    modifiedKnowledge: DerivedKnowledgeSchema.optional(),
});
export const PIICheckResultSchema = z.object({
    containsPII: z.boolean(),
    piiTypes: z.array(z.string()),
    action: z.enum(['allowed', 'blocked', 'redacted', 'hashed']),
    modifiedData: z.unknown().optional(),
});
export const ContentIntegritySchema = z.object({
    signatureRequired: z.boolean(),
    maxAge: z.number().positive(),
    allowedFormats: z.array(z.string()),
});
export const ContextAuthenticationRequirementsSchema = z.object({
    required: z.boolean(),
    minTrustTier: TrustTierSchema,
    requiredDomains: z.array(DomainCodeSchema).optional(),
    allowedProviders: z.array(z.string()),
    blockedProviders: z.array(z.string()),
    contentIntegrity: ContentIntegritySchema,
});
export const TrustProfileSchema = z.object({
    did: z.string(),
    trustTier: TrustTierSchema,
    domains: z.array(DomainCodeSchema),
    trustScore: z.number().min(0).max(1000),
    attestations: z.array(z.string()).optional(),
});
export const ProviderValidationResultSchema = z.object({
    valid: z.boolean(),
    providerId: z.string(),
    trustTier: TrustTierSchema.optional(),
    reason: z.string().optional(),
    blocked: z.boolean().optional(),
});
export const ContentValidationResultSchema = z.object({
    valid: z.boolean(),
    signatureValid: z.boolean().optional(),
    ageSeconds: z.number().optional(),
    format: z.string().optional(),
    reason: z.string().optional(),
});
export const InjectionScanResultSchema = z.object({
    detected: z.boolean(),
    patterns: z.array(z.string()),
    severity: z.enum(['low', 'medium', 'high', 'critical']).optional(),
    descriptions: z.array(z.string()).optional(),
});
export const ContextValidationResultSchema = z.object({
    valid: z.boolean(),
    reason: z.string().optional(),
    providerValidation: ProviderValidationResultSchema.optional(),
    contentValidation: ContentValidationResultSchema.optional(),
    injectionScan: InjectionScanResultSchema.optional(),
});
export const MessageChannelSchema = z.enum(['control', 'data']);
export const DualChannelConfigSchema = z.object({
    enforced: z.boolean(),
    controlPlaneSources: z.array(z.string()),
    dataPlaneTreatment: z.enum(['block', 'sanitize', 'warn']),
});
export const MessageClassificationSchema = z.object({
    channel: MessageChannelSchema,
    source: z.string(),
    authenticated: z.boolean(),
    instructionAllowed: z.boolean(),
    confidence: z.number().min(0).max(1).optional(),
});
export const EnforcementResultSchema = z.object({
    allowed: z.boolean(),
    action: z.enum(['pass', 'block', 'sanitize', 'warn']),
    reason: z.string().optional(),
    sanitizedContent: z.string().optional(),
    strippedInstructions: z.array(z.string()).optional(),
});
export const SemanticGovernanceCredentialSchema = z.object({
    id: z.string().min(1),
    carId: z.string().min(1),
    instructionIntegrity: InstructionIntegritySchema,
    outputBinding: OutputBindingSchema,
    inferenceScope: InferenceScopeSchema,
    contextAuthentication: ContextAuthenticationRequirementsSchema,
    dualChannel: DualChannelConfigSchema,
    metadata: z
        .object({
        issuer: z.string().optional(),
        issuedAt: z.date().optional(),
        expiresAt: z.date().optional(),
        version: z.string().optional(),
    })
        .optional(),
});
export const AgentIdentitySchema = z.object({
    did: z.string(),
    carId: z.string(),
    trustTier: TrustTierSchema,
    domains: z.array(DomainCodeSchema),
    serviceEndpoint: z.string().url().optional(),
});
export const ActionRequestSchema = z.object({
    type: z.string(),
    target: z.string().optional(),
    params: z.record(z.unknown()).optional(),
    instruction: z.string().optional(),
    contextSources: z
        .array(z.object({
        providerId: z.string(),
        content: z.unknown(),
        signature: z.string().optional(),
    }))
        .optional(),
    inferenceOperations: z.array(InferenceOperationSchema).optional(),
});
export const ActionRecordSchema = z.object({
    type: z.string(),
    target: z.string().optional(),
    output: z.unknown(),
    derivedKnowledge: z.array(DerivedKnowledgeSchema).optional(),
    externalEndpoints: z.array(z.string()).optional(),
    durationMs: z.number().optional(),
});
export const AgentInteractionSchema = z.object({
    id: z.string(),
    agent: AgentIdentitySchema,
    message: z.object({
        source: z.string(),
        content: z.string(),
        authenticated: z.boolean(),
        timestamp: z.date(),
    }),
    instruction: z.string().optional(),
    context: z
        .array(z.object({
        providerId: z.string(),
        content: z.unknown(),
        signature: z.string().optional(),
        timestamp: z.date().optional(),
    }))
        .optional(),
    action: z.union([ActionRequestSchema, ActionRecordSchema]).optional(),
});
export const PreActionResultSchema = z.object({
    allowed: z.boolean(),
    reason: z.string().optional(),
    instructionValidation: InstructionValidationResultSchema.optional(),
    contextValidations: z.array(ContextValidationResultSchema).optional(),
    inferenceValidations: z.array(InferenceValidationResultSchema).optional(),
    channelEnforcement: EnforcementResultSchema.optional(),
    warnings: z.array(z.string()).optional(),
});
export const PostActionResultSchema = z.object({
    valid: z.boolean(),
    reason: z.string().optional(),
    outputValidation: OutputValidationResultSchema.optional(),
    inferenceValidations: z.array(InferenceValidationResultSchema).optional(),
    piiChecks: z.array(PIICheckResultSchema).optional(),
    sanitizedOutput: z.unknown().optional(),
    warnings: z.array(z.string()).optional(),
});
export const SemanticValidationResultSchema = z.object({
    valid: z.boolean(),
    interactionId: z.string(),
    agentDid: z.string(),
    preAction: PreActionResultSchema.optional(),
    postAction: PostActionResultSchema.optional(),
    reason: z.string().optional(),
    validatedAt: z.date(),
    durationMs: z.number(),
});
export const SemanticGovernanceConfigSchema = z.object({
    instructionIntegrity: InstructionIntegritySchema.partial().optional(),
    outputBinding: OutputBindingSchema.partial().optional(),
    inferenceScope: InferenceScopeSchema.partial().optional(),
    contextAuthentication: ContextAuthenticationRequirementsSchema.partial().optional(),
    dualChannel: DualChannelConfigSchema.partial().optional(),
});
// =============================================================================
// DEFAULT CONFIGURATIONS
// =============================================================================
/**
 * Default instruction integrity configuration
 */
export const DEFAULT_INSTRUCTION_INTEGRITY = {
    allowedInstructionHashes: [],
    instructionTemplates: [],
    instructionSource: {
        allowedSources: [],
        requireSignature: false,
    },
};
/**
 * Default output binding configuration
 */
export const DEFAULT_OUTPUT_BINDING = {
    allowedSchemas: [],
    prohibitedPatterns: [
        {
            type: 'regex',
            pattern: '\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b',
            description: 'Email addresses',
            severity: 'medium',
        },
        {
            type: 'regex',
            pattern: '\\b\\d{3}-\\d{2}-\\d{4}\\b',
            description: 'Social Security Numbers',
            severity: 'critical',
        },
        {
            type: 'regex',
            pattern: '\\b\\d{16}\\b',
            description: 'Credit card numbers (basic)',
            severity: 'critical',
        },
    ],
    allowedExternalEndpoints: [],
    blockedExternalEndpoints: ['*'],
};
/**
 * Default inference scope configuration
 */
export const DEFAULT_INFERENCE_SCOPE = {
    globalLevel: InferenceLevel.ENTITY,
    domainOverrides: [],
    derivedKnowledgeHandling: {
        retention: 'session',
        allowedRecipients: [],
        crossContextSharing: false,
    },
    piiInference: {
        allowed: false,
        handling: 'redact',
    },
};
/**
 * Default context authentication configuration
 */
export const DEFAULT_CONTEXT_AUTHENTICATION = {
    required: true,
    minTrustTier: TrustTier.T2_PROVISIONAL,
    allowedProviders: [],
    blockedProviders: [],
    contentIntegrity: {
        signatureRequired: false,
        maxAge: 300,
        allowedFormats: ['application/json', 'text/plain'],
    },
};
/**
 * Default dual-channel configuration
 */
export const DEFAULT_DUAL_CHANNEL = {
    enforced: true,
    controlPlaneSources: ['user-direct-input', 'signed-system-instruction', 'authenticated-api-command'],
    dataPlaneTreatment: 'sanitize',
};
//# sourceMappingURL=types.js.map