{
  "component_id": "src_vault.rs",
  "contract_version": 1,
  "test_cases": [
    {
      "id": "test_now_epoch_returns_monotonic_timestamp",
      "description": "Verify now_epoch returns monotonically increasing timestamps",
      "function": "now_epoch",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result is f64",
        "result > 0",
        "subsequent call >= previous"
      ]
    },
    {
      "id": "test_random_hex_id_returns_32_char_hex",
      "description": "Verify random_hex_id returns 32-character lowercase hex string",
      "function": "random_hex_id",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "len(result) == 32",
        "all chars in [0-9a-f]"
      ]
    },
    {
      "id": "test_random_hex_id_uniqueness",
      "description": "Verify random_hex_id produces unique values with high probability",
      "function": "random_hex_id",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "1000 calls produce 1000 unique values"
      ]
    },
    {
      "id": "test_derive_master_key_deterministic",
      "description": "Verify derive_master_key returns same key for same passphrase and salt",
      "function": "derive_master_key",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "passphrase": "test_password",
        "salt": "32_bytes_salt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "len(result) == 32",
        "two calls with same inputs return identical keys"
      ]
    },
    {
      "id": "test_derive_master_key_different_passphrase",
      "description": "Verify different passphrases produce different keys",
      "function": "derive_master_key",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "passphrase1": "password1",
        "passphrase2": "password2",
        "salt": "same_salt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "keys are different"
      ]
    },
    {
      "id": "test_derive_master_key_different_salt",
      "description": "Verify different salts produce different keys",
      "function": "derive_master_key",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "passphrase": "same_password",
        "salt1": "salt_a",
        "salt2": "salt_b"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "keys are different"
      ]
    },
    {
      "id": "test_derive_subkey_deterministic",
      "description": "Verify derive_subkey returns same subkey for same master and purpose",
      "function": "derive_subkey",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "master": "32_byte_key",
        "purpose": "session"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "len(result) == 32",
        "two calls return identical subkeys"
      ]
    },
    {
      "id": "test_derive_subkey_different_purposes",
      "description": "Verify different purposes produce cryptographically independent subkeys",
      "function": "derive_subkey",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "master": "same_master",
        "purpose1": "session",
        "purpose2": "compartment"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "subkeys are different"
      ]
    },
    {
      "id": "test_make_key_check_deterministic",
      "description": "Verify make_key_check returns deterministic check value",
      "function": "make_key_check",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "master": "32_byte_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "two calls return identical check values"
      ]
    },
    {
      "id": "test_make_key_check_different_keys",
      "description": "Verify different master keys produce different check values",
      "function": "make_key_check",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "master1": "key_a",
        "master2": "key_b"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "check values are different"
      ]
    },
    {
      "id": "test_encrypt_decrypt_round_trip",
      "description": "Verify encrypt then decrypt returns original plaintext",
      "function": "encrypt",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "key": "32_byte_key",
        "plaintext": "test_data"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "ciphertext starts with 12-byte nonce",
        "decrypt(key, ciphertext) == plaintext"
      ]
    },
    {
      "id": "test_encrypt_produces_different_ciphertext",
      "description": "Verify encrypt produces different ciphertext each time due to random nonce",
      "function": "encrypt",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "key": "32_byte_key",
        "plaintext": "same_data"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "two encryptions of same plaintext differ"
      ]
    },
    {
      "id": "test_decrypt_data_too_short",
      "description": "Verify decrypt fails when data length < 12",
      "function": "decrypt",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "key": "32_byte_key",
        "data": "short"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "data_too_short",
      "assertions": []
    },
    {
      "id": "test_decrypt_authentication_failure",
      "description": "Verify decrypt fails when ciphertext is tampered",
      "function": "decrypt",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "key": "32_byte_key",
        "data": "tampered_ciphertext_with_nonce"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "decryption_failure",
      "assertions": []
    },
    {
      "id": "test_decrypt_wrong_key",
      "description": "Verify decrypt fails when using wrong key",
      "function": "decrypt",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "encrypt_key": "key_a",
        "decrypt_key": "key_b",
        "plaintext": "data"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "decryption_failure",
      "assertions": []
    },
    {
      "id": "test_policy_hmac_deterministic",
      "description": "Verify policy_hmac returns deterministic base64 HMAC",
      "function": "policy_hmac",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_content": "policy_text"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "two calls return identical HMAC",
        "result is base64"
      ]
    },
    {
      "id": "test_verify_policy_integrity_valid",
      "description": "Verify verify_policy_integrity returns true for valid policy",
      "function": "verify_policy_integrity",
      "category": "happy_path",
      "setup_description": "Create policy file and valid .hmac file",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_path": "test_policy.txt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == true"
      ]
    },
    {
      "id": "test_verify_policy_integrity_missing_policy",
      "description": "Verify verify_policy_integrity returns true when policy absent",
      "function": "verify_policy_integrity",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_path": "nonexistent.txt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == true"
      ]
    },
    {
      "id": "test_verify_policy_integrity_missing_hmac",
      "description": "Verify verify_policy_integrity returns false when HMAC missing but vault exists",
      "function": "verify_policy_integrity",
      "category": "error_case",
      "setup_description": "Create policy file without .hmac, ensure vault exists",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_path": "policy_no_hmac.txt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "HMAC missing",
      "assertions": [
        "result == false"
      ]
    },
    {
      "id": "test_verify_policy_integrity_mismatched_hmac",
      "description": "Verify verify_policy_integrity returns false when HMAC mismatched",
      "function": "verify_policy_integrity",
      "category": "error_case",
      "setup_description": "Create policy file with wrong HMAC",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_path": "policy_tampered.txt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == false"
      ]
    },
    {
      "id": "test_sign_policy_success",
      "description": "Verify sign_policy creates .hmac file alongside policy",
      "function": "sign_policy",
      "category": "happy_path",
      "setup_description": "Create policy file",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_path": "policy.txt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        ".hmac file created",
        "verify_policy_integrity returns true"
      ]
    },
    {
      "id": "test_sign_policy_read_error",
      "description": "Verify sign_policy fails when policy file unreadable",
      "function": "sign_policy",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "session_key": "32_byte_key",
        "policy_path": "nonexistent.txt"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "read_policy_error",
      "assertions": []
    },
    {
      "id": "test_vault_new_initializes_schema",
      "description": "Verify new creates Vault with initialized database schema",
      "function": "new",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "master_key": "32_byte_key",
        "db_path": "test.db"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "vault created",
        "tables exist",
        "session_start loaded"
      ]
    },
    {
      "id": "test_vault_session_key",
      "description": "Verify session_key returns immutable reference to session key",
      "function": "session_key",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returned key matches vault.session_key"
      ]
    },
    {
      "id": "test_init_db_creates_tables",
      "description": "Verify init_db creates all required tables and indexes",
      "function": "init_db",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "ledger table exists",
        "credentials table exists",
        "session_state table exists",
        "preflights table exists",
        "preflight_violations table exists"
      ]
    },
    {
      "id": "test_load_or_create_session_start_creates_new",
      "description": "Verify load_or_create_session_start creates new timestamp when missing",
      "function": "load_or_create_session_start",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "timestamp > 0",
        "timestamp written to database"
      ]
    },
    {
      "id": "test_load_or_create_session_start_loads_existing",
      "description": "Verify load_or_create_session_start loads existing valid timestamp",
      "function": "load_or_create_session_start",
      "category": "happy_path",
      "setup_description": "Insert session_start in database",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "loaded timestamp matches stored value"
      ]
    },
    {
      "id": "test_load_or_create_session_start_expired",
      "description": "Verify load_or_create_session_start creates new timestamp when expired",
      "function": "load_or_create_session_start",
      "category": "edge_case",
      "setup_description": "Insert old session_start beyond SESSION_TTL_SECS",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "new timestamp created",
        "new timestamp > old timestamp"
      ]
    },
    {
      "id": "test_reset_session_updates_timestamp",
      "description": "Verify reset_session sets session_start to current time",
      "function": "reset_session",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "session_start updated",
        "database contains new timestamp"
      ]
    },
    {
      "id": "test_log_action_writes_ledger",
      "description": "Verify log_action writes action to ledger table",
      "function": "log_action",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "tool": "test_tool",
        "decision": "ALLOW",
        "category": "api",
        "amount": "10.5",
        "detail": "test detail"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "ledger row created",
        "timestamp set"
      ]
    },
    {
      "id": "test_session_spend_calculates_allowed_total",
      "description": "Verify session_spend returns sum of allowed amounts since session_start",
      "function": "session_spend",
      "category": "happy_path",
      "setup_description": "Log multiple ALLOW actions with amounts",
      "mock_dependencies": {},
      "input_values": {
        "category": "api"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "sum matches expected total"
      ]
    },
    {
      "id": "test_session_spend_excludes_deny",
      "description": "Verify session_spend excludes DENY decisions",
      "function": "session_spend",
      "category": "edge_case",
      "setup_description": "Log ALLOW and DENY actions",
      "mock_dependencies": {},
      "input_values": {
        "category": "api"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "sum includes only ALLOW amounts"
      ]
    },
    {
      "id": "test_session_spend_filters_by_session_start",
      "description": "Verify session_spend filters by session_start timestamp",
      "function": "session_spend",
      "category": "edge_case",
      "setup_description": "Log actions before and after session_start",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "sum includes only actions after session_start"
      ]
    },
    {
      "id": "test_total_spend_since_timestamp",
      "description": "Verify total_spend returns sum since given timestamp",
      "function": "total_spend",
      "category": "happy_path",
      "setup_description": "Log actions at various timestamps",
      "mock_dependencies": {},
      "input_values": {
        "category": "api",
        "since": "timestamp"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "sum includes only actions after since timestamp"
      ]
    },
    {
      "id": "test_recent_actions_returns_limit",
      "description": "Verify recent_actions returns up to limit actions in reverse chronological order",
      "function": "recent_actions",
      "category": "happy_path",
      "setup_description": "Log 10 actions",
      "mock_dependencies": {},
      "input_values": {
        "limit": "5"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns 5 actions",
        "ordered by id DESC"
      ]
    },
    {
      "id": "test_recent_actions_empty_ledger",
      "description": "Verify recent_actions returns empty array when ledger empty",
      "function": "recent_actions",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "limit": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns empty array"
      ]
    },
    {
      "id": "test_has_recent_allowed_action_found",
      "description": "Verify has_recent_allowed_action returns true when match found",
      "function": "has_recent_allowed_action",
      "category": "happy_path",
      "setup_description": "Log allowed action with test_tool",
      "mock_dependencies": {},
      "input_values": {
        "search": "test_tool",
        "within": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == true"
      ]
    },
    {
      "id": "test_has_recent_allowed_action_not_found",
      "description": "Verify has_recent_allowed_action returns false when no match",
      "function": "has_recent_allowed_action",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "search": "nonexistent",
        "within": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == false"
      ]
    },
    {
      "id": "test_has_recent_allowed_action_pipe_delimited",
      "description": "Verify has_recent_allowed_action supports pipe-delimited OR search",
      "function": "has_recent_allowed_action",
      "category": "happy_path",
      "setup_description": "Log action with tool_b",
      "mock_dependencies": {},
      "input_values": {
        "search": "tool_a|tool_b",
        "within": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == true"
      ]
    },
    {
      "id": "test_has_recent_allowed_action_empty_search",
      "description": "Verify has_recent_allowed_action returns false for empty search",
      "function": "has_recent_allowed_action",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "search": "",
        "within": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result == false"
      ]
    },
    {
      "id": "test_store_credential_tier2",
      "description": "Verify store_credential stores encrypted credential with session_key (tier 2)",
      "function": "store_credential",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key",
        "value": "secret123",
        "tier": "2"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential stored",
        "value encrypted"
      ]
    },
    {
      "id": "test_store_credential_tier3",
      "description": "Verify store_credential stores encrypted credential with compartment_key (tier 3)",
      "function": "store_credential",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "master_token",
        "value": "secret456",
        "tier": "3"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential stored",
        "value encrypted with compartment_key"
      ]
    },
    {
      "id": "test_store_credential_replaces_existing",
      "description": "Verify store_credential replaces existing credential with same name",
      "function": "store_credential",
      "category": "edge_case",
      "setup_description": "Store credential, then store again with same name",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key",
        "value1": "old",
        "value2": "new",
        "tier": "2"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential updated",
        "get_credential returns new value"
      ]
    },
    {
      "id": "test_store_credential_with_expiry",
      "description": "Verify store_credential_with_expiry stores credential with expiry timestamp",
      "function": "store_credential_with_expiry",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "temp_token",
        "value": "secret",
        "tier": "2",
        "expires_at": "future_timestamp"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential stored",
        "expires_at set"
      ]
    },
    {
      "id": "test_store_credential_with_expiry_none",
      "description": "Verify store_credential_with_expiry accepts None expiry",
      "function": "store_credential_with_expiry",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "permanent_key",
        "value": "secret",
        "tier": "2",
        "expires_at": "None"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential stored",
        "expires_at is null"
      ]
    },
    {
      "id": "test_store_credential_full_with_metadata",
      "description": "Verify store_credential_full stores credential with full metadata",
      "function": "store_credential_full",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "scoped_key",
        "value": "secret",
        "tier": "2",
        "expires_at": "None",
        "metadata": "CredentialMeta with domain and purpose"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential stored",
        "metadata serialized as JSON"
      ]
    },
    {
      "id": "test_get_credential_success",
      "description": "Verify get_credential retrieves and decrypts credential",
      "function": "get_credential",
      "category": "happy_path",
      "setup_description": "Store credential",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Some(value)",
        "value matches original"
      ]
    },
    {
      "id": "test_get_credential_not_found",
      "description": "Verify get_credential returns None when credential not found",
      "function": "get_credential",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "nonexistent"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_get_credential_expired",
      "description": "Verify get_credential returns None when credential expired",
      "function": "get_credential",
      "category": "edge_case",
      "setup_description": "Store credential with past expiry",
      "mock_dependencies": {},
      "input_values": {
        "name": "expired_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_get_credential_decryption_failure",
      "description": "Verify get_credential returns None when decryption fails",
      "function": "get_credential",
      "category": "error_case",
      "setup_description": "Store credential, then corrupt ciphertext in database",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_get_credential_meta_success",
      "description": "Verify get_credential_meta returns deserialized metadata",
      "function": "get_credential_meta",
      "category": "happy_path",
      "setup_description": "Store credential with metadata",
      "mock_dependencies": {},
      "input_values": {
        "name": "scoped_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Some(CredentialMeta)",
        "fields match stored metadata"
      ]
    },
    {
      "id": "test_get_credential_meta_not_found",
      "description": "Verify get_credential_meta returns None when credential not found",
      "function": "get_credential_meta",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "nonexistent"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_request_capability_success",
      "description": "Verify request_capability returns credential value when constraints satisfied",
      "function": "request_capability",
      "category": "happy_path",
      "setup_description": "Store credential with matching metadata",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key",
        "domain": "example.com",
        "amount": "5.0",
        "purpose": "payment"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Ok(value)",
        "action logged"
      ]
    },
    {
      "id": "test_request_capability_domain_mismatch",
      "description": "Verify request_capability fails when domain constraint violated",
      "function": "request_capability",
      "category": "error_case",
      "setup_description": "Store credential with domain=example.com",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key",
        "domain": "wrong.com",
        "amount": "5.0",
        "purpose": "payment"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "domain_mismatch",
      "assertions": []
    },
    {
      "id": "test_request_capability_purpose_mismatch",
      "description": "Verify request_capability fails when purpose constraint violated",
      "function": "request_capability",
      "category": "error_case",
      "setup_description": "Store credential with purpose=payment",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key",
        "domain": "example.com",
        "amount": "5.0",
        "purpose": "wrong_purpose"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "purpose_mismatch",
      "assertions": []
    },
    {
      "id": "test_request_capability_amount_exceeded",
      "description": "Verify request_capability fails when amount exceeds max_amount",
      "function": "request_capability",
      "category": "error_case",
      "setup_description": "Store credential with max_amount=10.0",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key",
        "domain": "example.com",
        "amount": "100.0",
        "purpose": "payment"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "amount_exceeded",
      "assertions": []
    },
    {
      "id": "test_request_capability_not_found",
      "description": "Verify request_capability fails when credential not found",
      "function": "request_capability",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "nonexistent",
        "domain": "example.com",
        "amount": "5.0",
        "purpose": "payment"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "not_found_or_expired",
      "assertions": []
    },
    {
      "id": "test_request_capability_one_time_deletion",
      "description": "Verify request_capability deletes one-time credential after use",
      "function": "request_capability",
      "category": "happy_path",
      "setup_description": "Store credential with one_time=true",
      "mock_dependencies": {},
      "input_values": {
        "name": "one_time_token",
        "domain": "example.com",
        "amount": "5.0",
        "purpose": "payment"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Ok(value)",
        "credential deleted",
        "subsequent get_credential returns None"
      ]
    },
    {
      "id": "test_delete_credential_success",
      "description": "Verify delete_credential returns true when credential deleted",
      "function": "delete_credential",
      "category": "happy_path",
      "setup_description": "Store credential",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns true",
        "credential no longer exists"
      ]
    },
    {
      "id": "test_delete_credential_not_found",
      "description": "Verify delete_credential returns false when credential not found",
      "function": "delete_credential",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "nonexistent"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns false"
      ]
    },
    {
      "id": "test_credential_exists_true",
      "description": "Verify credential_exists returns true when credential found",
      "function": "credential_exists",
      "category": "happy_path",
      "setup_description": "Store credential",
      "mock_dependencies": {},
      "input_values": {
        "name": "api_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns true"
      ]
    },
    {
      "id": "test_credential_exists_false",
      "description": "Verify credential_exists returns false when credential not found",
      "function": "credential_exists",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "name": "nonexistent"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns false"
      ]
    },
    {
      "id": "test_list_credentials_returns_metadata",
      "description": "Verify list_credentials returns array of credential info objects without values",
      "function": "list_credentials",
      "category": "happy_path",
      "setup_description": "Store multiple credentials with metadata",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns array",
        "each object has name and metadata",
        "no values included"
      ]
    },
    {
      "id": "test_list_credentials_empty",
      "description": "Verify list_credentials returns empty array when no credentials",
      "function": "list_credentials",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns empty array"
      ]
    },
    {
      "id": "test_store_preflight_success",
      "description": "Verify store_preflight stores preflight with HMAC signature",
      "function": "store_preflight",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "preflight": "valid Preflight"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Ok()",
        "preflight stored as active",
        "previous preflight deactivated",
        "HMAC computed"
      ]
    },
    {
      "id": "test_store_preflight_too_many_constraints",
      "description": "Verify store_preflight fails when constraints exceed MAX_PREFLIGHT_CONSTRAINTS",
      "function": "store_preflight",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "preflight": "Preflight with 21 constraints"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "too_many_constraints",
      "assertions": []
    },
    {
      "id": "test_store_preflight_empty_alternative",
      "description": "Verify store_preflight fails when any constraint has empty alternative",
      "function": "store_preflight",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "preflight": "Preflight with empty alternative"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "empty_alternative",
      "assertions": []
    },
    {
      "id": "test_store_preflight_invalid_action",
      "description": "Verify store_preflight fails when action not DENY or ASK",
      "function": "store_preflight",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "preflight": "Preflight with action=INVALID"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "invalid_action",
      "assertions": []
    },
    {
      "id": "test_active_preflight_returns_valid",
      "description": "Verify active_preflight returns preflight when active and HMAC valid",
      "function": "active_preflight",
      "category": "happy_path",
      "setup_description": "Store preflight",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Some(Preflight)",
        "HMAC verified"
      ]
    },
    {
      "id": "test_active_preflight_none_when_not_found",
      "description": "Verify active_preflight returns None when no active preflight",
      "function": "active_preflight",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_active_preflight_none_when_expired",
      "description": "Verify active_preflight returns None and deactivates when lockout expired",
      "function": "active_preflight",
      "category": "edge_case",
      "setup_description": "Store preflight with lockout_until in past",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None",
        "preflight deactivated"
      ]
    },
    {
      "id": "test_active_preflight_hmac_mismatch",
      "description": "Verify active_preflight returns None and logs warning when HMAC mismatched",
      "function": "active_preflight",
      "category": "error_case",
      "setup_description": "Store preflight, then tamper with stored data",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None",
        "warning logged"
      ]
    },
    {
      "id": "test_is_preflight_locked_true",
      "description": "Verify is_preflight_locked returns true when lockout_until > now",
      "function": "is_preflight_locked",
      "category": "happy_path",
      "setup_description": "Store preflight with lockout_until in future",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns true"
      ]
    },
    {
      "id": "test_is_preflight_locked_false",
      "description": "Verify is_preflight_locked returns false when lockout expired",
      "function": "is_preflight_locked",
      "category": "edge_case",
      "setup_description": "Store preflight with lockout_until in past",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns false"
      ]
    },
    {
      "id": "test_log_preflight_violation_increments_count",
      "description": "Verify log_preflight_violation records violation and increments count",
      "function": "log_preflight_violation",
      "category": "happy_path",
      "setup_description": "Store active preflight",
      "mock_dependencies": {},
      "input_values": {
        "violation": "PreflightViolation"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "violation logged",
        "violation_count incremented"
      ]
    },
    {
      "id": "test_log_preflight_violation_escalates_at_threshold",
      "description": "Verify log_preflight_violation sets escalated flag when count >= DEFAULT_VIOLATION_THRESHOLD",
      "function": "log_preflight_violation",
      "category": "edge_case",
      "setup_description": "Store preflight with 4 existing violations",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "5th violation logged",
        "escalated set to true"
      ]
    },
    {
      "id": "test_preflight_violations_returns_list",
      "description": "Verify preflight_violations returns violations in reverse chronological order",
      "function": "preflight_violations",
      "category": "happy_path",
      "setup_description": "Log multiple violations for preflight",
      "mock_dependencies": {},
      "input_values": {
        "preflight_id": "test_id"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns violations",
        "ordered by timestamp DESC"
      ]
    },
    {
      "id": "test_preflight_violations_empty",
      "description": "Verify preflight_violations returns empty array when no violations",
      "function": "preflight_violations",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "preflight_id": "test_id"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns empty array"
      ]
    },
    {
      "id": "test_preflight_history_returns_list",
      "description": "Verify preflight_history returns preflights in reverse chronological order",
      "function": "preflight_history",
      "category": "happy_path",
      "setup_description": "Store multiple preflights",
      "mock_dependencies": {},
      "input_values": {
        "limit": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns up to limit preflights",
        "ordered by submitted_at DESC"
      ]
    },
    {
      "id": "test_preflight_history_empty",
      "description": "Verify preflight_history returns empty array when no preflights",
      "function": "preflight_history",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "limit": "10"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns empty array"
      ]
    },
    {
      "id": "test_override_preflight_success",
      "description": "Verify override_preflight deactivates active preflight",
      "function": "override_preflight",
      "category": "happy_path",
      "setup_description": "Store active preflight",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Ok()",
        "preflight deactivated"
      ]
    },
    {
      "id": "test_override_preflight_no_active",
      "description": "Verify override_preflight fails when no active preflight",
      "function": "override_preflight",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "no_active_preflight",
      "assertions": []
    },
    {
      "id": "test_preflight_hmac_returns_prefixed_hmac",
      "description": "Verify preflight_hmac returns base64 HMAC with signet-preflight: prefix",
      "function": "preflight_hmac",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "payload": "test_payload"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "result starts with 'signet-preflight:'",
        "deterministic"
      ]
    },
    {
      "id": "test_signet_dir_uses_env_var",
      "description": "Verify signet_dir returns SIGNET_DIR env var if set",
      "function": "signet_dir",
      "category": "happy_path",
      "setup_description": "Set SIGNET_DIR env var",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns SIGNET_DIR path"
      ]
    },
    {
      "id": "test_signet_dir_defaults_to_home_signet",
      "description": "Verify signet_dir returns ~/.signet when SIGNET_DIR not set",
      "function": "signet_dir",
      "category": "edge_case",
      "setup_description": "Unset SIGNET_DIR",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns HOME/.signet"
      ]
    },
    {
      "id": "test_dirs_returns_home",
      "description": "Verify dirs returns user home directory",
      "function": "dirs",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns path from HOME env var"
      ]
    },
    {
      "id": "test_dirs_fallback_to_current",
      "description": "Verify dirs returns current directory when HOME not set",
      "function": "dirs",
      "category": "edge_case",
      "setup_description": "Unset HOME env var",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns '.'"
      ]
    },
    {
      "id": "test_meta_path_returns_vault_meta",
      "description": "Verify meta_path returns {signet_dir}/vault.meta",
      "function": "meta_path",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "path ends with vault.meta"
      ]
    },
    {
      "id": "test_db_path_returns_state_db",
      "description": "Verify db_path returns {signet_dir}/state.db",
      "function": "db_path",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "path ends with state.db"
      ]
    },
    {
      "id": "test_session_key_path_returns_session_key",
      "description": "Verify session_key_path returns {signet_dir}/.session_key",
      "function": "session_key_path",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "path ends with .session_key"
      ]
    },
    {
      "id": "test_vault_exists_true",
      "description": "Verify vault_exists returns true when vault.meta file exists",
      "function": "vault_exists",
      "category": "happy_path",
      "setup_description": "Create vault.meta file",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns true"
      ]
    },
    {
      "id": "test_vault_exists_false",
      "description": "Verify vault_exists returns false when vault.meta not found",
      "function": "vault_exists",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns false"
      ]
    },
    {
      "id": "test_pause_path_returns_pause_until",
      "description": "Verify pause_path returns {signet_dir}/pause_until",
      "function": "pause_path",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "path ends with pause_until"
      ]
    },
    {
      "id": "test_set_pause_file_creates_file",
      "description": "Verify set_pause_file creates pause_until file with timestamp",
      "function": "set_pause_file",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "pause_until": "12345"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "pause_until file created",
        "contains timestamp"
      ]
    },
    {
      "id": "test_is_paused_file_true",
      "description": "Verify is_paused_file returns true when current time < pause_until",
      "function": "is_paused_file",
      "category": "happy_path",
      "setup_description": "Set pause_until to future timestamp",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns true"
      ]
    },
    {
      "id": "test_is_paused_file_false",
      "description": "Verify is_paused_file returns false when pause expired",
      "function": "is_paused_file",
      "category": "edge_case",
      "setup_description": "Set pause_until to past timestamp",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns false",
        "pause file deleted"
      ]
    },
    {
      "id": "test_clear_pause_file_deletes_file",
      "description": "Verify clear_pause_file removes pause_until file",
      "function": "clear_pause_file",
      "category": "happy_path",
      "setup_description": "Create pause_until file",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "file deleted"
      ]
    },
    {
      "id": "test_pause_until_file_returns_timestamp",
      "description": "Verify pause_until_file returns pause timestamp from file",
      "function": "pause_until_file",
      "category": "happy_path",
      "setup_description": "Set pause_until to 12345",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns 12345"
      ]
    },
    {
      "id": "test_pause_until_file_returns_zero_when_not_paused",
      "description": "Verify pause_until_file returns 0 when not paused",
      "function": "pause_until_file",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns 0"
      ]
    },
    {
      "id": "test_disabled_path_returns_disabled",
      "description": "Verify disabled_path returns {signet_dir}/disabled",
      "function": "disabled_path",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "path ends with disabled"
      ]
    },
    {
      "id": "test_set_disabled_file_creates_file",
      "description": "Verify set_disabled_file creates disabled flag file",
      "function": "set_disabled_file",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "disabled file created"
      ]
    },
    {
      "id": "test_is_disabled_file_true",
      "description": "Verify is_disabled_file returns true when disabled file exists",
      "function": "is_disabled_file",
      "category": "happy_path",
      "setup_description": "Create disabled file",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns true"
      ]
    },
    {
      "id": "test_is_disabled_file_false",
      "description": "Verify is_disabled_file returns false when disabled file not found",
      "function": "is_disabled_file",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns false"
      ]
    },
    {
      "id": "test_clear_disabled_file_deletes_file",
      "description": "Verify clear_disabled_file removes disabled file",
      "function": "clear_disabled_file",
      "category": "happy_path",
      "setup_description": "Create disabled file",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "file deleted"
      ]
    },
    {
      "id": "test_device_key_deterministic",
      "description": "Verify device_key returns deterministic key for this device+user",
      "function": "device_key",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "len(result) == 32",
        "two calls return same key"
      ]
    },
    {
      "id": "test_device_key_fallback_when_machine_id_unavailable",
      "description": "Verify device_key falls back to default when machine ID unavailable",
      "function": "device_key",
      "category": "edge_case",
      "setup_description": "Mock machine_id unavailable",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns key",
        "uses fallback"
      ]
    },
    {
      "id": "test_encrypt_session_key_round_trip",
      "description": "Verify encrypt_session_key and decrypt_session_key round trip",
      "function": "encrypt_session_key",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "master_key": "32_byte_key"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "encrypted != master_key",
        "decrypt_session_key(encrypted) == master_key"
      ]
    },
    {
      "id": "test_decrypt_session_key_failure",
      "description": "Verify decrypt_session_key returns None on decryption failure",
      "function": "decrypt_session_key",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "encrypted": "invalid_data"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_setup_vault_success",
      "description": "Verify setup_vault initializes new vault with passphrase",
      "function": "setup_vault",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "passphrase": "strong_password"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Ok(Vault)",
        "vault.meta created",
        ".session_key created",
        "database initialized"
      ]
    },
    {
      "id": "test_setup_vault_creates_directory",
      "description": "Verify setup_vault creates signet directory if not exists",
      "function": "setup_vault",
      "category": "happy_path",
      "setup_description": "Ensure signet directory does not exist",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "directory created"
      ]
    },
    {
      "id": "test_unlock_vault_success",
      "description": "Verify unlock_vault opens existing vault with correct passphrase",
      "function": "unlock_vault",
      "category": "happy_path",
      "setup_description": "Setup vault with passphrase",
      "mock_dependencies": {},
      "input_values": {
        "passphrase": "correct_password"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Ok(Vault)",
        "failed_attempts reset to 0",
        ".session_key updated"
      ]
    },
    {
      "id": "test_unlock_vault_no_vault",
      "description": "Verify unlock_vault fails when vault.meta not found",
      "function": "unlock_vault",
      "category": "error_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "passphrase": "password"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "no_vault",
      "assertions": []
    },
    {
      "id": "test_unlock_vault_wrong_passphrase",
      "description": "Verify unlock_vault fails and increments failed_attempts on wrong passphrase",
      "function": "unlock_vault",
      "category": "error_case",
      "setup_description": "Setup vault with different passphrase",
      "mock_dependencies": {},
      "input_values": {
        "passphrase": "wrong_password"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "wrong_passphrase",
      "assertions": [
        "failed_attempts incremented"
      ]
    },
    {
      "id": "test_unlock_vault_lockout_triggered",
      "description": "Verify unlock_vault triggers lockout at MAX_FAILED_ATTEMPTS",
      "function": "unlock_vault",
      "category": "error_case",
      "setup_description": "Setup vault, fail 4 times, then fail 5th time",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "locked_out",
      "assertions": [
        "locked_until set to now + LOCKOUT_SECS"
      ]
    },
    {
      "id": "test_unlock_vault_lockout_active",
      "description": "Verify unlock_vault fails when lockout active",
      "function": "unlock_vault",
      "category": "error_case",
      "setup_description": "Setup vault with active lockout",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "locked_out",
      "assertions": []
    },
    {
      "id": "test_unlock_vault_lockout_expired",
      "description": "Verify unlock_vault allows attempt after lockout expired",
      "function": "unlock_vault",
      "category": "edge_case",
      "setup_description": "Setup vault with expired lockout",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "unlock succeeds with correct passphrase"
      ]
    },
    {
      "id": "test_try_load_vault_success",
      "description": "Verify try_load_vault loads vault from cached session key",
      "function": "try_load_vault",
      "category": "happy_path",
      "setup_description": "Setup vault and unlock to cache session key",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Some(Vault)",
        "vault operational"
      ]
    },
    {
      "id": "test_try_load_vault_cache_missing",
      "description": "Verify try_load_vault returns None when session key cache missing",
      "function": "try_load_vault",
      "category": "edge_case",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_try_load_vault_invalid_cache",
      "description": "Verify try_load_vault returns None when session key cache invalid",
      "function": "try_load_vault",
      "category": "edge_case",
      "setup_description": "Create corrupted .session_key file",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_try_load_vault_verification_failure",
      "description": "Verify try_load_vault returns None when key verification fails",
      "function": "try_load_vault",
      "category": "error_case",
      "setup_description": "Setup vault, then tamper with vault.meta",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns None"
      ]
    },
    {
      "id": "test_make_test_vault_creates_temp_vault",
      "description": "Verify make_test_vault creates vault in temp directory for testing",
      "function": "make_test_vault",
      "category": "happy_path",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "dir": "temp_dir",
        "passphrase": "test_pass"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "returns Vault",
        "vault operational",
        "database in temp dir"
      ]
    },
    {
      "id": "test_invariant_salt_len_32",
      "description": "Verify SALT_LEN constant is 32 bytes",
      "function": "setup_vault",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "generated salt is 32 bytes"
      ]
    },
    {
      "id": "test_invariant_key_len_32",
      "description": "Verify KEY_LEN constant is 32 bytes (AES-256)",
      "function": "derive_master_key",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "derived key is 32 bytes"
      ]
    },
    {
      "id": "test_invariant_nonce_len_12",
      "description": "Verify NONCE_LEN constant is 12 bytes (AES-GCM)",
      "function": "encrypt",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "nonce prefix is 12 bytes"
      ]
    },
    {
      "id": "test_invariant_session_ttl_1800",
      "description": "Verify SESSION_TTL_SECS is 1800.0 (30 minutes)",
      "function": "load_or_create_session_start",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "session expires after 1800 seconds"
      ]
    },
    {
      "id": "test_invariant_max_failed_attempts_5",
      "description": "Verify MAX_FAILED_ATTEMPTS is 5",
      "function": "unlock_vault",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "lockout triggers at 5 failed attempts"
      ]
    },
    {
      "id": "test_invariant_lockout_secs_300",
      "description": "Verify LOCKOUT_SECS is 300.0 (5 minutes)",
      "function": "unlock_vault",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "lockout duration is 300 seconds"
      ]
    },
    {
      "id": "test_invariant_max_preflight_constraints_20",
      "description": "Verify MAX_PREFLIGHT_CONSTRAINTS is 20",
      "function": "store_preflight",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "preflight with 21 constraints fails"
      ]
    },
    {
      "id": "test_invariant_violation_threshold_5",
      "description": "Verify DEFAULT_VIOLATION_THRESHOLD is 5",
      "function": "log_preflight_violation",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "escalated flag set at 5 violations"
      ]
    },
    {
      "id": "test_invariant_tier2_session_key",
      "description": "Verify tier 2 credentials encrypted with session_key",
      "function": "store_credential",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "tier": "2"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential encrypted with session_key"
      ]
    },
    {
      "id": "test_invariant_tier3_compartment_key",
      "description": "Verify tier 3 credentials encrypted with compartment_key",
      "function": "store_credential",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "tier": "3"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "credential encrypted with compartment_key"
      ]
    },
    {
      "id": "test_invariant_session_spend_only_allowed",
      "description": "Verify session_spend counts only decision=ALLOW",
      "function": "session_spend",
      "category": "invariant",
      "setup_description": "Log ALLOW and DENY actions",
      "mock_dependencies": {},
      "input_values": {},
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "",
      "assertions": [
        "sum excludes DENY amounts"
      ]
    },
    {
      "id": "test_invariant_preflight_constraints_non_empty_alternative",
      "description": "Verify preflight constraints must have non-empty alternatives",
      "function": "store_preflight",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "constraint_alternative": ""
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "empty_alternative",
      "assertions": []
    },
    {
      "id": "test_invariant_preflight_action_deny_or_ask",
      "description": "Verify constraint action must be DENY or ASK",
      "function": "store_preflight",
      "category": "invariant",
      "setup_description": "",
      "mock_dependencies": {},
      "input_values": {
        "constraint_action": "ALLOW"
      },
      "input_description": "",
      "expected_output_description": "",
      "expected_error": "invalid_action",
      "assertions": []
    }
  ],
  "test_language": "rust",
  "generated_code": "\"\"\"\nContract Test Suite for Signet Vault - Encrypted Local State with Tiered Access\nComponent: src_vault.rs\nContract Version: 1\n\nThis test suite provides comprehensive coverage of the Signet Vault contract,\nincluding:\n- Unit tests for crypto functions (KATs, round-trip verification)\n- Integration tests for Vault lifecycle operations\n- Error injection tests for all defined error paths\n- Temporal tests for expiry, lockout, and session timeout\n- Policy enforcement tests for preflight constraints\n- Persistence tests across reload cycles\n- Boundary tests for limits and constraints\n- Invariant tests for constants and behavioral properties\n\nAll dependencies are mocked using unittest.mock.\n\"\"\"\n\nimport pytest\nfrom unittest.mock import Mock, MagicMock, patch, mock_open, call\nimport tempfile\nimport os\nimport json\nimport time\nfrom pathlib import Path\n\n# Import component (adjust path as needed)\n# Assuming the Rust module is exposed via Python bindings\ntry:\n    from src_vault import *\nexcept ImportError:\n    # Mock module for testing if actual bindings not available\n    pass\n\n\n# ============================================================================\n# TEST FIXTURES AND HELPERS\n# ============================================================================\n\n@pytest.fixture\ndef temp_dir():\n    \"\"\"Create temporary directory for test isolation\"\"\"\n    with tempfile.TemporaryDirectory() as tmpdir:\n        yield Path(tmpdir)\n\n\n@pytest.fixture\ndef mock_time():\n    \"\"\"Mock time for temporal tests\"\"\"\n    with patch('src_vault.now_epoch') as mock:\n        mock.return_value = 1234567890.0\n        yield mock\n\n\n@pytest.fixture\ndef test_vault(temp_dir):\n    \"\"\"Create test vault instance\"\"\"\n    vault = make_test_vault(str(temp_dir), \"test_passphrase\")\n    yield vault\n\n\n@pytest.fixture\ndef mock_vault():\n    \"\"\"Mock Vault for unit tests\"\"\"\n    vault = Mock(spec=Vault)\n    vault.master_key = b'0' * 32\n    vault.session_key = b'1' * 32\n    vault.compartment_key = b'2' * 32\n    vault.session_start = 1234567890.0\n    return vault\n\n\n# ============================================================================\n# UTILITY FUNCTION TESTS\n# ============================================================================\n\nclass TestNowEpoch:\n    \"\"\"Tests for now_epoch() function\"\"\"\n\n    def test_now_epoch_returns_monotonic_timestamp(self):\n        \"\"\"Verify now_epoch returns monotonically increasing timestamps\"\"\"\n        t1 = now_epoch()\n        t2 = now_epoch()\n        \n        assert isinstance(t1, float), \"Timestamp should be f64\"\n        assert t1 > 0, \"Timestamp should be positive\"\n        assert t2 >= t1, \"Subsequent call should be >= previous\"\n\n    def test_now_epoch_reasonable_value(self):\n        \"\"\"Verify now_epoch returns reasonable current time\"\"\"\n        t = now_epoch()\n        # Should be after 2020-01-01 and before 2100-01-01\n        assert 1577836800.0 < t < 4102444800.0\n\n\nclass TestRandomHexId:\n    \"\"\"Tests for random_hex_id() function\"\"\"\n\n    def test_random_hex_id_returns_32_char_hex(self):\n        \"\"\"Verify random_hex_id returns 32-character lowercase hex string\"\"\"\n        hex_id = random_hex_id()\n        \n        assert isinstance(hex_id, str), \"Should return string\"\n        assert len(hex_id) == 32, \"Should be 32 characters\"\n        assert all(c in '0123456789abcdef' for c in hex_id), \"Should only contain hex chars\"\n\n    def test_random_hex_id_uniqueness(self):\n        \"\"\"Verify random_hex_id produces unique values with high probability\"\"\"\n        ids = [random_hex_id() for _ in range(1000)]\n        unique_ids = set(ids)\n        \n        assert len(unique_ids) == 1000, \"1000 calls should produce 1000 unique values\"\n\n\n# ============================================================================\n# CRYPTOGRAPHIC FUNCTION TESTS\n# ============================================================================\n\nclass TestDeriveMasterKey:\n    \"\"\"Tests for derive_master_key() function\"\"\"\n\n    def test_derive_master_key_deterministic(self):\n        \"\"\"Verify derive_master_key returns same key for same passphrase and salt\"\"\"\n        passphrase = \"test_password\"\n        salt = b'a' * 32\n        \n        key1 = derive_master_key(passphrase, salt)\n        key2 = derive_master_key(passphrase, salt)\n        \n        assert len(key1) == 32, \"Key should be 32 bytes\"\n        assert key1 == key2, \"Same inputs should produce same key\"\n\n    def test_derive_master_key_different_passphrase(self):\n        \"\"\"Verify different passphrases produce different keys\"\"\"\n        salt = b'a' * 32\n        key1 = derive_master_key(\"password1\", salt)\n        key2 = derive_master_key(\"password2\", salt)\n        \n        assert key1 != key2, \"Different passphrases should produce different keys\"\n\n    def test_derive_master_key_different_salt(self):\n        \"\"\"Verify different salts produce different keys\"\"\"\n        passphrase = \"same_password\"\n        key1 = derive_master_key(passphrase, b'a' * 32)\n        key2 = derive_master_key(passphrase, b'b' * 32)\n        \n        assert key1 != key2, \"Different salts should produce different keys\"\n\n\nclass TestDeriveSubkey:\n    \"\"\"Tests for derive_subkey() function\"\"\"\n\n    def test_derive_subkey_deterministic(self):\n        \"\"\"Verify derive_subkey returns same subkey for same master and purpose\"\"\"\n        master = b'x' * 32\n        purpose = \"session\"\n        \n        subkey1 = derive_subkey(master, purpose)\n        subkey2 = derive_subkey(master, purpose)\n        \n        assert len(subkey1) == 32, \"Subkey should be 32 bytes\"\n        assert subkey1 == subkey2, \"Same inputs should produce same subkey\"\n\n    def test_derive_subkey_different_purposes(self):\n        \"\"\"Verify different purposes produce cryptographically independent subkeys\"\"\"\n        master = b'x' * 32\n        subkey1 = derive_subkey(master, \"session\")\n        subkey2 = derive_subkey(master, \"compartment\")\n        \n        assert subkey1 != subkey2, \"Different purposes should produce different subkeys\"\n\n\nclass TestMakeKeyCheck:\n    \"\"\"Tests for make_key_check() function\"\"\"\n\n    def test_make_key_check_deterministic(self):\n        \"\"\"Verify make_key_check returns deterministic check value\"\"\"\n        master = b'x' * 32\n        \n        check1 = make_key_check(master)\n        check2 = make_key_check(master)\n        \n        assert check1 == check2, \"Same master key should produce same check value\"\n\n    def test_make_key_check_different_keys(self):\n        \"\"\"Verify different master keys produce different check values\"\"\"\n        check1 = make_key_check(b'a' * 32)\n        check2 = make_key_check(b'b' * 32)\n        \n        assert check1 != check2, \"Different keys should produce different check values\"\n\n\nclass TestEncryptDecrypt:\n    \"\"\"Tests for encrypt() and decrypt() functions\"\"\"\n\n    def test_encrypt_decrypt_round_trip(self):\n        \"\"\"Verify encrypt then decrypt returns original plaintext\"\"\"\n        key = b'k' * 32\n        plaintext = b\"test_data\"\n        \n        ciphertext = encrypt(key, plaintext)\n        \n        assert len(ciphertext) > 12, \"Ciphertext should include nonce\"\n        assert ciphertext[:12] != plaintext[:12], \"Should be encrypted\"\n        \n        result = decrypt(key, ciphertext)\n        assert result.is_ok(), \"Decryption should succeed\"\n        assert result.unwrap() == plaintext, \"Should recover original plaintext\"\n\n    def test_encrypt_produces_different_ciphertext(self):\n        \"\"\"Verify encrypt produces different ciphertext each time due to random nonce\"\"\"\n        key = b'k' * 32\n        plaintext = b\"same_data\"\n        \n        ct1 = encrypt(key, plaintext)\n        ct2 = encrypt(key, plaintext)\n        \n        assert ct1 != ct2, \"Random nonce should make ciphertexts different\"\n\n    def test_decrypt_data_too_short(self):\n        \"\"\"Verify decrypt fails when data length < 12\"\"\"\n        key = b'k' * 32\n        short_data = b\"short\"\n        \n        result = decrypt(key, short_data)\n        assert result.is_err(), \"Should fail on too-short data\"\n        assert \"data_too_short\" in result.unwrap_err()\n\n    def test_decrypt_authentication_failure(self):\n        \"\"\"Verify decrypt fails when ciphertext is tampered\"\"\"\n        key = b'k' * 32\n        plaintext = b\"test\"\n        ciphertext = encrypt(key, plaintext)\n        \n        # Tamper with ciphertext\n        tampered = bytearray(ciphertext)\n        tampered[-1] ^= 0xFF\n        \n        result = decrypt(key, bytes(tampered))\n        assert result.is_err(), \"Should fail on tampered ciphertext\"\n        assert \"decryption_failure\" in result.unwrap_err()\n\n    def test_decrypt_wrong_key(self):\n        \"\"\"Verify decrypt fails when using wrong key\"\"\"\n        key1 = b'a' * 32\n        key2 = b'b' * 32\n        plaintext = b\"data\"\n        \n        ciphertext = encrypt(key1, plaintext)\n        result = decrypt(key2, ciphertext)\n        \n        assert result.is_err(), \"Should fail with wrong key\"\n        assert \"decryption_failure\" in result.unwrap_err()\n\n\n# ============================================================================\n# POLICY HMAC TESTS\n# ============================================================================\n\nclass TestPolicyHmac:\n    \"\"\"Tests for policy_hmac() and related functions\"\"\"\n\n    def test_policy_hmac_deterministic(self):\n        \"\"\"Verify policy_hmac returns deterministic base64 HMAC\"\"\"\n        session_key = b's' * 32\n        policy_content = \"policy_text\"\n        \n        hmac1 = policy_hmac(session_key, policy_content)\n        hmac2 = policy_hmac(session_key, policy_content)\n        \n        assert hmac1 == hmac2, \"Should be deterministic\"\n        # Check base64 encoding (basic check)\n        assert all(c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' for c in hmac1)\n\n    @patch('builtins.open', new_callable=mock_open, read_data='policy content')\n    @patch('os.path.exists')\n    def test_verify_policy_integrity_valid(self, mock_exists, mock_file):\n        \"\"\"Verify verify_policy_integrity returns true for valid policy\"\"\"\n        mock_exists.return_value = True\n        session_key = b's' * 32\n        \n        # Mock HMAC file with correct HMAC\n        correct_hmac = policy_hmac(session_key, \"policy content\")\n        mock_file.side_effect = [\n            mock_open(read_data='policy content').return_value,\n            mock_open(read_data=correct_hmac).return_value\n        ]\n        \n        result = verify_policy_integrity(session_key, Path(\"test_policy.txt\"))\n        assert result is True, \"Should return true for valid policy\"\n\n    @patch('os.path.exists')\n    def test_verify_policy_integrity_missing_policy(self, mock_exists):\n        \"\"\"Verify verify_policy_integrity returns true when policy absent\"\"\"\n        mock_exists.return_value = False\n        session_key = b's' * 32\n        \n        result = verify_policy_integrity(session_key, Path(\"nonexistent.txt\"))\n        assert result is True, \"Should return true when policy absent\"\n\n    @patch('builtins.open', new_callable=mock_open, read_data='policy content')\n    @patch('os.path.exists')\n    def test_verify_policy_integrity_missing_hmac(self, mock_exists, mock_file):\n        \"\"\"Verify verify_policy_integrity returns false when HMAC missing but vault exists\"\"\"\n        def exists_side_effect(path):\n            if 'policy_no_hmac.txt' in str(path):\n                return True\n            if '.hmac' in str(path):\n                return False\n            if 'vault.meta' in str(path):\n                return True  # Vault exists\n            return False\n        \n        mock_exists.side_effect = exists_side_effect\n        session_key = b's' * 32\n        \n        result = verify_policy_integrity(session_key, Path(\"policy_no_hmac.txt\"))\n        assert result is False, \"Should return false when HMAC missing and vault exists\"\n\n    @patch('builtins.open', new_callable=mock_open)\n    @patch('os.path.exists')\n    def test_verify_policy_integrity_mismatched_hmac(self, mock_exists, mock_file):\n        \"\"\"Verify verify_policy_integrity returns false when HMAC mismatched\"\"\"\n        mock_exists.return_value = True\n        \n        mock_file.side_effect = [\n            mock_open(read_data='policy content').return_value,\n            mock_open(read_data='wrong_hmac').return_value\n        ]\n        \n        session_key = b's' * 32\n        result = verify_policy_integrity(session_key, Path(\"policy_tampered.txt\"))\n        assert result is False, \"Should return false for mismatched HMAC\"\n\n    @patch('builtins.open', new_callable=mock_open, read_data='policy content')\n    @patch('os.path.exists')\n    def test_sign_policy_success(self, mock_exists, mock_file):\n        \"\"\"Verify sign_policy creates .hmac file alongside policy\"\"\"\n        mock_exists.return_value = True\n        session_key = b's' * 32\n        policy_path = Path(\"policy.txt\")\n        \n        result = sign_policy(session_key, policy_path)\n        assert result.is_ok(), \"Should succeed\"\n        \n        # Verify HMAC file would be written\n        mock_file.assert_called()\n\n    @patch('os.path.exists')\n    def test_sign_policy_read_error(self, mock_exists):\n        \"\"\"Verify sign_policy fails when policy file unreadable\"\"\"\n        mock_exists.return_value = False\n        session_key = b's' * 32\n        \n        result = sign_policy(session_key, Path(\"nonexistent.txt\"))\n        assert result.is_err(), \"Should fail when policy unreadable\"\n        assert \"read_policy_error\" in result.unwrap_err()\n\n\n# ============================================================================\n# VAULT LIFECYCLE TESTS\n# ============================================================================\n\nclass TestVaultNew:\n    \"\"\"Tests for Vault::new() constructor\"\"\"\n\n    def test_vault_new_initializes_schema(self, temp_dir):\n        \"\"\"Verify new creates Vault with initialized database schema\"\"\"\n        master_key = b'm' * 32\n        db_path = temp_dir / \"test.db\"\n        \n        vault = Vault.new(master_key, db_path)\n        \n        assert vault is not None, \"Vault should be created\"\n        # Verify tables exist (implementation-dependent check)\n        # This would require querying the database\n        \n    def test_vault_session_key(self, mock_vault):\n        \"\"\"Verify session_key returns immutable reference to session key\"\"\"\n        session_key_ref = mock_vault.session_key()\n        \n        assert session_key_ref == mock_vault.session_key, \"Should return session key\"\n\n\nclass TestInitDb:\n    \"\"\"Tests for init_db() method\"\"\"\n\n    def test_init_db_creates_tables(self, test_vault):\n        \"\"\"Verify init_db creates all required tables and indexes\"\"\"\n        test_vault.init_db()\n        \n        # Query to check tables exist (implementation-dependent)\n        # Would need to query sqlite_master table\n        # For now, verify no exception raised\n        assert True\n\n\nclass TestSessionManagement:\n    \"\"\"Tests for session start and reset\"\"\"\n\n    def test_load_or_create_session_start_creates_new(self, temp_dir):\n        \"\"\"Verify load_or_create_session_start creates new timestamp when missing\"\"\"\n        vault = make_test_vault(str(temp_dir), \"pass\")\n        \n        timestamp = vault.load_or_create_session_start()\n        \n        assert timestamp > 0, \"Should create valid timestamp\"\n\n    @patch('src_vault.now_epoch')\n    def test_load_or_create_session_start_loads_existing(self, mock_time, test_vault):\n        \"\"\"Verify load_or_create_session_start loads existing valid timestamp\"\"\"\n        mock_time.return_value = 1000.0\n        \n        # First call creates\n        ts1 = test_vault.load_or_create_session_start()\n        \n        # Second call should load same\n        ts2 = test_vault.load_or_create_session_start()\n        \n        assert ts1 == ts2, \"Should load existing timestamp\"\n\n    @patch('src_vault.now_epoch')\n    def test_load_or_create_session_start_expired(self, mock_time, test_vault):\n        \"\"\"Verify load_or_create_session_start creates new timestamp when expired\"\"\"\n        # Create old session\n        mock_time.return_value = 1000.0\n        old_ts = test_vault.load_or_create_session_start()\n        \n        # Advance time beyond SESSION_TTL_SECS (1800)\n        mock_time.return_value = 1000.0 + 2000.0\n        new_ts = test_vault.load_or_create_session_start()\n        \n        assert new_ts > old_ts, \"Should create new timestamp when expired\"\n\n    def test_reset_session_updates_timestamp(self, test_vault):\n        \"\"\"Verify reset_session sets session_start to current time\"\"\"\n        old_start = test_vault.session_start\n        \n        time.sleep(0.01)  # Small delay\n        test_vault.reset_session()\n        \n        assert test_vault.session_start > old_start, \"Session start should be updated\"\n\n\n# ============================================================================\n# LEDGER AND ACTION LOGGING TESTS\n# ============================================================================\n\nclass TestLedger:\n    \"\"\"Tests for ledger operations\"\"\"\n\n    def test_log_action_writes_ledger(self, test_vault):\n        \"\"\"Verify log_action writes action to ledger table\"\"\"\n        test_vault.log_action(\"test_tool\", \"ALLOW\", \"api\", 10.5, \"test detail\")\n        \n        # Verify by reading recent actions\n        actions = test_vault.recent_actions(10)\n        assert len(actions) > 0, \"Should have logged action\"\n        assert actions[0]['tool'] == \"test_tool\"\n\n    def test_session_spend_calculates_allowed_total(self, test_vault):\n        \"\"\"Verify session_spend returns sum of allowed amounts since session_start\"\"\"\n        test_vault.log_action(\"tool1\", \"ALLOW\", \"api\", 5.0, \"detail1\")\n        test_vault.log_action(\"tool2\", \"ALLOW\", \"api\", 7.5, \"detail2\")\n        \n        total = test_vault.session_spend(\"api\")\n        assert total == 12.5, \"Should sum allowed amounts\"\n\n    def test_session_spend_excludes_deny(self, test_vault):\n        \"\"\"Verify session_spend excludes DENY decisions\"\"\"\n        test_vault.log_action(\"tool1\", \"ALLOW\", \"api\", 5.0, \"detail1\")\n        test_vault.log_action(\"tool2\", \"DENY\", \"api\", 100.0, \"detail2\")\n        \n        total = test_vault.session_spend(\"api\")\n        assert total == 5.0, \"Should exclude DENY amounts\"\n\n    @patch('src_vault.now_epoch')\n    def test_session_spend_filters_by_session_start(self, mock_time, test_vault):\n        \"\"\"Verify session_spend filters by session_start timestamp\"\"\"\n        mock_time.return_value = 1000.0\n        test_vault.log_action(\"old\", \"ALLOW\", \"api\", 5.0, \"before session\")\n        \n        # Reset session\n        mock_time.return_value = 2000.0\n        test_vault.reset_session()\n        \n        test_vault.log_action(\"new\", \"ALLOW\", \"api\", 7.0, \"after session\")\n        \n        total = test_vault.session_spend(\"api\")\n        assert total == 7.0, \"Should only include actions after session_start\"\n\n    @patch('src_vault.now_epoch')\n    def test_total_spend_since_timestamp(self, mock_time, test_vault):\n        \"\"\"Verify total_spend returns sum since given timestamp\"\"\"\n        mock_time.return_value = 1000.0\n        test_vault.log_action(\"tool1\", \"ALLOW\", \"api\", 5.0, \"old\")\n        \n        mock_time.return_value = 2000.0\n        test_vault.log_action(\"tool2\", \"ALLOW\", \"api\", 10.0, \"new\")\n        \n        total = test_vault.total_spend(\"api\", 1500.0)\n        assert total == 10.0, \"Should only include actions after since timestamp\"\n\n    def test_recent_actions_returns_limit(self, test_vault):\n        \"\"\"Verify recent_actions returns up to limit actions in reverse chronological order\"\"\"\n        for i in range(10):\n            test_vault.log_action(f\"tool{i}\", \"ALLOW\", \"api\", 1.0, f\"detail{i}\")\n        \n        actions = test_vault.recent_actions(5)\n        assert len(actions) == 5, \"Should return exactly limit actions\"\n        # Verify reverse chronological (most recent first)\n        assert actions[0]['tool'] == \"tool9\"\n\n    def test_recent_actions_empty_ledger(self, test_vault):\n        \"\"\"Verify recent_actions returns empty array when ledger empty\"\"\"\n        actions = test_vault.recent_actions(10)\n        assert actions == [], \"Should return empty array\"\n\n    def test_has_recent_allowed_action_found(self, test_vault):\n        \"\"\"Verify has_recent_allowed_action returns true when match found\"\"\"\n        test_vault.log_action(\"test_tool\", \"ALLOW\", \"api\", 1.0, \"detail\")\n        \n        result = test_vault.has_recent_allowed_action(\"test_tool\", 10)\n        assert result is True, \"Should find matching action\"\n\n    def test_has_recent_allowed_action_not_found(self, test_vault):\n        \"\"\"Verify has_recent_allowed_action returns false when no match\"\"\"\n        test_vault.log_action(\"other_tool\", \"ALLOW\", \"api\", 1.0, \"detail\")\n        \n        result = test_vault.has_recent_allowed_action(\"nonexistent\", 10)\n        assert result is False, \"Should not find non-matching action\"\n\n    def test_has_recent_allowed_action_pipe_delimited(self, test_vault):\n        \"\"\"Verify has_recent_allowed_action supports pipe-delimited OR search\"\"\"\n        test_vault.log_action(\"tool_b\", \"ALLOW\", \"api\", 1.0, \"detail\")\n        \n        result = test_vault.has_recent_allowed_action(\"tool_a|tool_b\", 10)\n        assert result is True, \"Should find match with OR search\"\n\n    def test_has_recent_allowed_action_empty_search(self, test_vault):\n        \"\"\"Verify has_recent_allowed_action returns false for empty search\"\"\"\n        test_vault.log_action(\"tool\", \"ALLOW\", \"api\", 1.0, \"detail\")\n        \n        result = test_vault.has_recent_allowed_action(\"\", 10)\n        assert result is False, \"Should return false for empty search\"\n\n\n# ============================================================================\n# CREDENTIAL STORAGE TESTS\n# ============================================================================\n\nclass TestCredentials:\n    \"\"\"Tests for credential storage and retrieval\"\"\"\n\n    def test_store_credential_tier2(self, test_vault):\n        \"\"\"Verify store_credential stores encrypted credential with session_key (tier 2)\"\"\"\n        test_vault.store_credential(\"api_key\", \"secret123\", 2)\n        \n        retrieved = test_vault.get_credential(\"api_key\")\n        assert retrieved == \"secret123\", \"Should retrieve stored credential\"\n\n    def test_store_credential_tier3(self, test_vault):\n        \"\"\"Verify store_credential stores encrypted credential with compartment_key (tier 3)\"\"\"\n        test_vault.store_credential(\"master_token\", \"secret456\", 3)\n        \n        retrieved = test_vault.get_credential(\"master_token\")\n        assert retrieved == \"secret456\", \"Should retrieve tier 3 credential\"\n\n    def test_store_credential_replaces_existing(self, test_vault):\n        \"\"\"Verify store_credential replaces existing credential with same name\"\"\"\n        test_vault.store_credential(\"api_key\", \"old\", 2)\n        test_vault.store_credential(\"api_key\", \"new\", 2)\n        \n        retrieved = test_vault.get_credential(\"api_key\")\n        assert retrieved == \"new\", \"Should retrieve updated value\"\n\n    def test_store_credential_with_expiry(self, test_vault):\n        \"\"\"Verify store_credential_with_expiry stores credential with expiry timestamp\"\"\"\n        future_time = now_epoch() + 3600.0\n        test_vault.store_credential_with_expiry(\"temp_token\", \"secret\", 2, future_time)\n        \n        retrieved = test_vault.get_credential(\"temp_token\")\n        assert retrieved == \"secret\", \"Should retrieve before expiry\"\n\n    def test_store_credential_with_expiry_none(self, test_vault):\n        \"\"\"Verify store_credential_with_expiry accepts None expiry\"\"\"\n        test_vault.store_credential_with_expiry(\"permanent_key\", \"secret\", 2, None)\n        \n        retrieved = test_vault.get_credential(\"permanent_key\")\n        assert retrieved == \"secret\", \"Should retrieve non-expiring credential\"\n\n    def test_store_credential_full_with_metadata(self, test_vault):\n        \"\"\"Verify store_credential_full stores credential with full metadata\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=100.0,\n            one_time=False,\n            label=\"Test Key\"\n        )\n        \n        test_vault.store_credential_full(\"scoped_key\", \"secret\", 2, None, metadata)\n        \n        retrieved_meta = test_vault.get_credential_meta(\"scoped_key\")\n        assert retrieved_meta.domain == \"example.com\"\n        assert retrieved_meta.purpose == \"payment\"\n\n    def test_get_credential_success(self, test_vault):\n        \"\"\"Verify get_credential retrieves and decrypts credential\"\"\"\n        test_vault.store_credential(\"api_key\", \"secret123\", 2)\n        \n        result = test_vault.get_credential(\"api_key\")\n        assert result == \"secret123\", \"Should decrypt and return value\"\n\n    def test_get_credential_not_found(self, test_vault):\n        \"\"\"Verify get_credential returns None when credential not found\"\"\"\n        result = test_vault.get_credential(\"nonexistent\")\n        assert result is None, \"Should return None for missing credential\"\n\n    @patch('src_vault.now_epoch')\n    def test_get_credential_expired(self, mock_time, test_vault):\n        \"\"\"Verify get_credential returns None when credential expired\"\"\"\n        mock_time.return_value = 1000.0\n        past_time = 500.0\n        \n        test_vault.store_credential_with_expiry(\"expired_key\", \"secret\", 2, past_time)\n        \n        result = test_vault.get_credential(\"expired_key\")\n        assert result is None, \"Should return None for expired credential\"\n\n    def test_get_credential_meta_success(self, test_vault):\n        \"\"\"Verify get_credential_meta returns deserialized metadata\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=50.0,\n            one_time=False,\n            label=\"API Key\"\n        )\n        \n        test_vault.store_credential_full(\"scoped_key\", \"secret\", 2, None, metadata)\n        \n        result = test_vault.get_credential_meta(\"scoped_key\")\n        assert result is not None\n        assert result.domain == \"example.com\"\n\n    def test_get_credential_meta_not_found(self, test_vault):\n        \"\"\"Verify get_credential_meta returns None when credential not found\"\"\"\n        result = test_vault.get_credential_meta(\"nonexistent\")\n        assert result is None\n\n\nclass TestRequestCapability:\n    \"\"\"Tests for request_capability with constraint enforcement\"\"\"\n\n    def test_request_capability_success(self, test_vault):\n        \"\"\"Verify request_capability returns credential value when constraints satisfied\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=10.0,\n            one_time=False,\n            label=None\n        )\n        test_vault.store_credential_full(\"api_key\", \"secret_value\", 2, None, metadata)\n        \n        result = test_vault.request_capability(\"api_key\", \"example.com\", 5.0, \"payment\")\n        assert result.is_ok()\n        assert result.unwrap() == \"secret_value\"\n\n    def test_request_capability_domain_mismatch(self, test_vault):\n        \"\"\"Verify request_capability fails when domain constraint violated\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=10.0,\n            one_time=False,\n            label=None\n        )\n        test_vault.store_credential_full(\"api_key\", \"secret\", 2, None, metadata)\n        \n        result = test_vault.request_capability(\"api_key\", \"wrong.com\", 5.0, \"payment\")\n        assert result.is_err()\n        assert \"domain_mismatch\" in result.unwrap_err()\n\n    def test_request_capability_purpose_mismatch(self, test_vault):\n        \"\"\"Verify request_capability fails when purpose constraint violated\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=10.0,\n            one_time=False,\n            label=None\n        )\n        test_vault.store_credential_full(\"api_key\", \"secret\", 2, None, metadata)\n        \n        result = test_vault.request_capability(\"api_key\", \"example.com\", 5.0, \"wrong_purpose\")\n        assert result.is_err()\n        assert \"purpose_mismatch\" in result.unwrap_err()\n\n    def test_request_capability_amount_exceeded(self, test_vault):\n        \"\"\"Verify request_capability fails when amount exceeds max_amount\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=10.0,\n            one_time=False,\n            label=None\n        )\n        test_vault.store_credential_full(\"api_key\", \"secret\", 2, None, metadata)\n        \n        result = test_vault.request_capability(\"api_key\", \"example.com\", 100.0, \"payment\")\n        assert result.is_err()\n        assert \"amount_exceeded\" in result.unwrap_err()\n\n    def test_request_capability_not_found(self, test_vault):\n        \"\"\"Verify request_capability fails when credential not found\"\"\"\n        result = test_vault.request_capability(\"nonexistent\", \"example.com\", 5.0, \"payment\")\n        assert result.is_err()\n        assert \"not_found_or_expired\" in result.unwrap_err()\n\n    def test_request_capability_one_time_deletion(self, test_vault):\n        \"\"\"Verify request_capability deletes one-time credential after use\"\"\"\n        metadata = CredentialMeta(\n            domain=\"example.com\",\n            purpose=\"payment\",\n            max_amount=10.0,\n            one_time=True,\n            label=None\n        )\n        test_vault.store_credential_full(\"one_time_token\", \"secret\", 2, None, metadata)\n        \n        result = test_vault.request_capability(\"one_time_token\", \"example.com\", 5.0, \"payment\")\n        assert result.is_ok()\n        \n        # Should be deleted after use\n        assert test_vault.get_credential(\"one_time_token\") is None\n\n\nclass TestCredentialManagement:\n    \"\"\"Tests for credential management operations\"\"\"\n\n    def test_delete_credential_success(self, test_vault):\n        \"\"\"Verify delete_credential returns true when credential deleted\"\"\"\n        test_vault.store_credential(\"api_key\", \"secret\", 2)\n        \n        result = test_vault.delete_credential(\"api_key\")\n        assert result is True\n        assert test_vault.get_credential(\"api_key\") is None\n\n    def test_delete_credential_not_found(self, test_vault):\n        \"\"\"Verify delete_credential returns false when credential not found\"\"\"\n        result = test_vault.delete_credential(\"nonexistent\")\n        assert result is False\n\n    def test_credential_exists_true(self, test_vault):\n        \"\"\"Verify credential_exists returns true when credential found\"\"\"\n        test_vault.store_credential(\"api_key\", \"secret\", 2)\n        \n        result = test_vault.credential_exists(\"api_key\")\n        assert result is True\n\n    def test_credential_exists_false(self, test_vault):\n        \"\"\"Verify credential_exists returns false when credential not found\"\"\"\n        result = test_vault.credential_exists(\"nonexistent\")\n        assert result is False\n\n    def test_list_credentials_returns_metadata(self, test_vault):\n        \"\"\"Verify list_credentials returns array of credential info objects without values\"\"\"\n        metadata1 = CredentialMeta(domain=\"a.com\", purpose=None, max_amount=None, one_time=False, label=\"Key1\")\n        metadata2 = CredentialMeta(domain=\"b.com\", purpose=None, max_amount=None, one_time=False, label=\"Key2\")\n        \n        test_vault.store_credential_full(\"key1\", \"secret1\", 2, None, metadata1)\n        test_vault.store_credential_full(\"key2\", \"secret2\", 2, None, metadata2)\n        \n        creds = test_vault.list_credentials()\n        assert len(creds) == 2\n        assert all('name' in c for c in creds)\n        assert all('value' not in c for c in creds)  # Values should not be included\n\n    def test_list_credentials_empty(self, test_vault):\n        \"\"\"Verify list_credentials returns empty array when no credentials\"\"\"\n        creds = test_vault.list_credentials()\n        assert creds == []\n\n\n# ============================================================================\n# PREFLIGHT TESTS\n# ============================================================================\n\nclass TestPreflight:\n    \"\"\"Tests for preflight storage and retrieval\"\"\"\n\n    def test_store_preflight_success(self, test_vault):\n        \"\"\"Verify store_preflight stores preflight with HMAC signature\"\"\"\n        constraint = SoftConstraint(\n            name=\"test_constraint\",\n            tool_pattern=\".*\",\n            conditions=[\"amount > 100\"],\n            action=\"DENY\",\n            reason=\"Test\",\n            alternative=\"Use smaller amount\"\n        )\n        \n        preflight = Preflight(\n            id=\"test_id\",\n            task=\"test task\",\n            risks=[\"risk1\"],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_ok()\n\n    def test_store_preflight_too_many_constraints(self, test_vault):\n        \"\"\"Verify store_preflight fails when constraints exceed MAX_PREFLIGHT_CONSTRAINTS\"\"\"\n        constraints = []\n        for i in range(21):\n            constraints.append(SoftConstraint(\n                name=f\"c{i}\",\n                tool_pattern=\".*\",\n                conditions=[],\n                action=\"DENY\",\n                reason=\"test\",\n                alternative=\"alt\"\n            ))\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=constraints,\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_err()\n        assert \"too_many_constraints\" in result.unwrap_err()\n\n    def test_store_preflight_empty_alternative(self, test_vault):\n        \"\"\"Verify store_preflight fails when any constraint has empty alternative\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"\"  # Empty alternative\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_err()\n        assert \"empty_alternative\" in result.unwrap_err()\n\n    def test_store_preflight_invalid_action(self, test_vault):\n        \"\"\"Verify store_preflight fails when action not DENY or ASK\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"INVALID\",  # Invalid action\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_err()\n        assert \"invalid_action\" in result.unwrap_err()\n\n    def test_active_preflight_returns_valid(self, test_vault):\n        \"\"\"Verify active_preflight returns preflight when active and HMAC valid\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        future_lockout = int(now_epoch()) + 1000\n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=int(now_epoch()),\n            lockout_until=future_lockout,\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        active = test_vault.active_preflight()\n        assert active is not None\n        assert active.id == \"test\"\n\n    def test_active_preflight_none_when_not_found(self, test_vault):\n        \"\"\"Verify active_preflight returns None when no active preflight\"\"\"\n        active = test_vault.active_preflight()\n        assert active is None\n\n    @patch('src_vault.now_epoch')\n    def test_active_preflight_none_when_expired(self, mock_time, test_vault):\n        \"\"\"Verify active_preflight returns None and deactivates when lockout expired\"\"\"\n        mock_time.return_value = 2000.0\n        \n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=1500,  # In the past\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        active = test_vault.active_preflight()\n        assert active is None\n\n    @patch('src_vault.now_epoch')\n    def test_is_preflight_locked_true(self, mock_time, test_vault):\n        \"\"\"Verify is_preflight_locked returns true when lockout_until > now\"\"\"\n        mock_time.return_value = 1000.0\n        \n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=2000,  # In the future\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        assert test_vault.is_preflight_locked() is True\n\n    @patch('src_vault.now_epoch')\n    def test_is_preflight_locked_false(self, mock_time, test_vault):\n        \"\"\"Verify is_preflight_locked returns false when lockout expired\"\"\"\n        mock_time.return_value = 2000.0\n        \n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=1500,  # In the past\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        assert test_vault.is_preflight_locked() is False\n\n\nclass TestPreflightViolations:\n    \"\"\"Tests for preflight violation tracking\"\"\"\n\n    def test_log_preflight_violation_increments_count(self, test_vault):\n        \"\"\"Verify log_preflight_violation records violation and increments count\"\"\"\n        # First create active preflight\n        constraint = SoftConstraint(\n            name=\"test_constraint\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test_id\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=int(now_epoch()),\n            lockout_until=int(now_epoch()) + 1000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        # Log violation\n        violation = PreflightViolation(\n            preflight_id=\"test_id\",\n            constraint_name=\"test_constraint\",\n            tool_name=\"test_tool\",\n            parameters_summary=\"params\",\n            alternative=\"alt\",\n            timestamp=int(now_epoch())\n        )\n        \n        result = test_vault.log_preflight_violation(violation)\n        assert result.is_ok()\n        \n        # Check count incremented\n        active = test_vault.active_preflight()\n        assert active.violation_count == 1\n\n    def test_log_preflight_violation_escalates_at_threshold(self, test_vault):\n        \"\"\"Verify log_preflight_violation sets escalated flag when count >= DEFAULT_VIOLATION_THRESHOLD\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test_id\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=int(now_epoch()),\n            lockout_until=int(now_epoch()) + 1000,\n            violation_count=4,  # 4 existing violations\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        # Log 5th violation\n        violation = PreflightViolation(\n            preflight_id=\"test_id\",\n            constraint_name=\"test\",\n            tool_name=\"tool\",\n            parameters_summary=\"params\",\n            alternative=\"alt\",\n            timestamp=int(now_epoch())\n        )\n        \n        test_vault.log_preflight_violation(violation)\n        \n        # Check escalated\n        active = test_vault.active_preflight()\n        assert active.escalated is True\n\n    def test_preflight_violations_returns_list(self, test_vault):\n        \"\"\"Verify preflight_violations returns violations in reverse chronological order\"\"\"\n        # Setup preflight\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test_id\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=int(now_epoch()),\n            lockout_until=int(now_epoch()) + 1000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        # Log multiple violations\n        for i in range(3):\n            violation = PreflightViolation(\n                preflight_id=\"test_id\",\n                constraint_name=\"test\",\n                tool_name=f\"tool{i}\",\n                parameters_summary=\"params\",\n                alternative=\"alt\",\n                timestamp=int(now_epoch()) + i\n            )\n            test_vault.log_preflight_violation(violation)\n        \n        violations = test_vault.preflight_violations(\"test_id\")\n        assert len(violations) == 3\n        # Most recent first\n        assert violations[0].tool_name == \"tool2\"\n\n    def test_preflight_violations_empty(self, test_vault):\n        \"\"\"Verify preflight_violations returns empty array when no violations\"\"\"\n        violations = test_vault.preflight_violations(\"nonexistent\")\n        assert violations == []\n\n    def test_preflight_history_returns_list(self, test_vault):\n        \"\"\"Verify preflight_history returns preflights in reverse chronological order\"\"\"\n        # Store multiple preflights\n        for i in range(3):\n            constraint = SoftConstraint(\n                name=\"test\",\n                tool_pattern=\".*\",\n                conditions=[],\n                action=\"DENY\",\n                reason=\"test\",\n                alternative=\"alt\"\n            )\n            \n            preflight = Preflight(\n                id=f\"id{i}\",\n                task=f\"task{i}\",\n                risks=[],\n                constraints=[constraint],\n                submitted_at=int(now_epoch()) + i,\n                lockout_until=int(now_epoch()) + 1000 + i,\n                violation_count=0,\n                escalated=False\n            )\n            \n            test_vault.store_preflight(preflight)\n        \n        history = test_vault.preflight_history(10)\n        assert len(history) >= 1  # At least the last active one\n\n    def test_preflight_history_empty(self, test_vault):\n        \"\"\"Verify preflight_history returns empty array when no preflights\"\"\"\n        history = test_vault.preflight_history(10)\n        assert history == []\n\n    def test_override_preflight_success(self, test_vault):\n        \"\"\"Verify override_preflight deactivates active preflight\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=int(now_epoch()),\n            lockout_until=int(now_epoch()) + 1000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        result = test_vault.override_preflight()\n        assert result.is_ok()\n        \n        # Should be deactivated\n        active = test_vault.active_preflight()\n        assert active is None\n\n    def test_override_preflight_no_active(self, test_vault):\n        \"\"\"Verify override_preflight fails when no active preflight\"\"\"\n        result = test_vault.override_preflight()\n        assert result.is_err()\n        assert \"no_active_preflight\" in result.unwrap_err()\n\n    def test_preflight_hmac_returns_prefixed_hmac(self, test_vault):\n        \"\"\"Verify preflight_hmac returns base64 HMAC with signet-preflight: prefix\"\"\"\n        hmac1 = test_vault.preflight_hmac(\"test_payload\")\n        hmac2 = test_vault.preflight_hmac(\"test_payload\")\n        \n        assert hmac1.startswith(\"signet-preflight:\")\n        assert hmac1 == hmac2  # Deterministic\n\n\n# ============================================================================\n# FILE PATH TESTS\n# ============================================================================\n\nclass TestFilePaths:\n    \"\"\"Tests for file path functions\"\"\"\n\n    @patch.dict(os.environ, {'SIGNET_DIR': '/custom/signet'})\n    def test_signet_dir_uses_env_var(self):\n        \"\"\"Verify signet_dir returns SIGNET_DIR env var if set\"\"\"\n        path = signet_dir()\n        assert str(path) == '/custom/signet'\n\n    @patch.dict(os.environ, {}, clear=True)\n    @patch.dict(os.environ, {'HOME': '/home/user'})\n    def test_signet_dir_defaults_to_home_signet(self):\n        \"\"\"Verify signet_dir returns ~/.signet when SIGNET_DIR not set\"\"\"\n        if 'SIGNET_DIR' in os.environ:\n            del os.environ['SIGNET_DIR']\n        \n        path = signet_dir()\n        assert '.signet' in str(path)\n\n    @patch.dict(os.environ, {'HOME': '/home/user'})\n    def test_dirs_returns_home(self):\n        \"\"\"Verify dirs returns user home directory\"\"\"\n        path = dirs()\n        assert str(path) == '/home/user' or str(path).endswith('user')\n\n    @patch.dict(os.environ, {}, clear=True)\n    def test_dirs_fallback_to_current(self):\n        \"\"\"Verify dirs returns current directory when HOME not set\"\"\"\n        if 'HOME' in os.environ:\n            del os.environ['HOME']\n        \n        path = dirs()\n        assert str(path) == '.'\n\n    def test_meta_path_returns_vault_meta(self):\n        \"\"\"Verify meta_path returns {signet_dir}/vault.meta\"\"\"\n        path = meta_path()\n        assert str(path).endswith('vault.meta')\n\n    def test_db_path_returns_state_db(self):\n        \"\"\"Verify db_path returns {signet_dir}/state.db\"\"\"\n        path = db_path()\n        assert str(path).endswith('state.db')\n\n    def test_session_key_path_returns_session_key(self):\n        \"\"\"Verify session_key_path returns {signet_dir}/.session_key\"\"\"\n        path = session_key_path()\n        assert str(path).endswith('.session_key')\n\n    @patch('os.path.exists')\n    def test_vault_exists_true(self, mock_exists):\n        \"\"\"Verify vault_exists returns true when vault.meta file exists\"\"\"\n        mock_exists.return_value = True\n        \n        assert vault_exists() is True\n\n    @patch('os.path.exists')\n    def test_vault_exists_false(self, mock_exists):\n        \"\"\"Verify vault_exists returns false when vault.meta not found\"\"\"\n        mock_exists.return_value = False\n        \n        assert vault_exists() is False\n\n    def test_pause_path_returns_pause_until(self):\n        \"\"\"Verify pause_path returns {signet_dir}/pause_until\"\"\"\n        path = pause_path()\n        assert str(path).endswith('pause_until')\n\n    def test_disabled_path_returns_disabled(self):\n        \"\"\"Verify disabled_path returns {signet_dir}/disabled\"\"\"\n        path = disabled_path()\n        assert str(path).endswith('disabled')\n\n\n# ============================================================================\n# PAUSE/DISABLE MECHANISM TESTS\n# ============================================================================\n\nclass TestPauseDisable:\n    \"\"\"Tests for pause and disable mechanisms\"\"\"\n\n    @patch('builtins.open', new_callable=mock_open)\n    @patch('os.makedirs')\n    def test_set_pause_file_creates_file(self, mock_makedirs, mock_file):\n        \"\"\"Verify set_pause_file creates pause_until file with timestamp\"\"\"\n        set_pause_file(12345)\n        \n        mock_file.assert_called()\n\n    @patch('builtins.open', new_callable=mock_open, read_data='9999999999')\n    @patch('os.path.exists')\n    @patch('src_vault.now_epoch')\n    def test_is_paused_file_true(self, mock_time, mock_exists, mock_file):\n        \"\"\"Verify is_paused_file returns true when current time < pause_until\"\"\"\n        mock_time.return_value = 1000.0\n        mock_exists.return_value = True\n        \n        result = is_paused_file()\n        assert result is True\n\n    @patch('builtins.open', new_callable=mock_open, read_data='500')\n    @patch('os.path.exists')\n    @patch('os.remove')\n    @patch('src_vault.now_epoch')\n    def test_is_paused_file_false(self, mock_time, mock_remove, mock_exists, mock_file):\n        \"\"\"Verify is_paused_file returns false when pause expired\"\"\"\n        mock_time.return_value = 1000.0\n        mock_exists.return_value = True\n        \n        result = is_paused_file()\n        assert result is False\n\n    @patch('os.path.exists')\n    @patch('os.remove')\n    def test_clear_pause_file_deletes_file(self, mock_remove, mock_exists):\n        \"\"\"Verify clear_pause_file removes pause_until file\"\"\"\n        mock_exists.return_value = True\n        \n        clear_pause_file()\n        mock_remove.assert_called()\n\n    @patch('builtins.open', new_callable=mock_open, read_data='12345')\n    @patch('os.path.exists')\n    def test_pause_until_file_returns_timestamp(self, mock_exists, mock_file):\n        \"\"\"Verify pause_until_file returns pause timestamp from file\"\"\"\n        mock_exists.return_value = True\n        \n        timestamp = pause_until_file()\n        assert timestamp == 12345\n\n    @patch('os.path.exists')\n    def test_pause_until_file_returns_zero_when_not_paused(self, mock_exists):\n        \"\"\"Verify pause_until_file returns 0 when not paused\"\"\"\n        mock_exists.return_value = False\n        \n        timestamp = pause_until_file()\n        assert timestamp == 0\n\n    @patch('builtins.open', new_callable=mock_open)\n    @patch('os.makedirs')\n    def test_set_disabled_file_creates_file(self, mock_makedirs, mock_file):\n        \"\"\"Verify set_disabled_file creates disabled flag file\"\"\"\n        set_disabled_file()\n        mock_file.assert_called()\n\n    @patch('os.path.exists')\n    def test_is_disabled_file_true(self, mock_exists):\n        \"\"\"Verify is_disabled_file returns true when disabled file exists\"\"\"\n        mock_exists.return_value = True\n        \n        assert is_disabled_file() is True\n\n    @patch('os.path.exists')\n    def test_is_disabled_file_false(self, mock_exists):\n        \"\"\"Verify is_disabled_file returns false when disabled file not found\"\"\"\n        mock_exists.return_value = False\n        \n        assert is_disabled_file() is False\n\n    @patch('os.path.exists')\n    @patch('os.remove')\n    def test_clear_disabled_file_deletes_file(self, mock_remove, mock_exists):\n        \"\"\"Verify clear_disabled_file removes disabled file\"\"\"\n        mock_exists.return_value = True\n        \n        clear_disabled_file()\n        mock_remove.assert_called()\n\n\n# ============================================================================\n# DEVICE KEY TESTS\n# ============================================================================\n\nclass TestDeviceKey:\n    \"\"\"Tests for device key derivation\"\"\"\n\n    def test_device_key_deterministic(self):\n        \"\"\"Verify device_key returns deterministic key for this device+user\"\"\"\n        key1 = device_key()\n        key2 = device_key()\n        \n        assert len(key1) == 32\n        assert key1 == key2\n\n    @patch('src_vault.get_machine_id')\n    def test_device_key_fallback_when_machine_id_unavailable(self, mock_machine_id):\n        \"\"\"Verify device_key falls back to default when machine ID unavailable\"\"\"\n        mock_machine_id.return_value = None\n        \n        key = device_key()\n        assert len(key) == 32\n\n\nclass TestSessionKeyCache:\n    \"\"\"Tests for session key encryption/decryption\"\"\"\n\n    def test_encrypt_session_key_round_trip(self):\n        \"\"\"Verify encrypt_session_key and decrypt_session_key round trip\"\"\"\n        master_key = b'm' * 32\n        \n        encrypted = encrypt_session_key(master_key)\n        assert encrypted != master_key\n        \n        decrypted = decrypt_session_key(encrypted)\n        assert decrypted == master_key\n\n    def test_decrypt_session_key_failure(self):\n        \"\"\"Verify decrypt_session_key returns None on decryption failure\"\"\"\n        invalid_data = b'invalid'\n        \n        result = decrypt_session_key(invalid_data)\n        assert result is None\n\n\n# ============================================================================\n# VAULT SETUP AND UNLOCK TESTS\n# ============================================================================\n\nclass TestSetupVault:\n    \"\"\"Tests for setup_vault function\"\"\"\n\n    def test_setup_vault_success(self, temp_dir):\n        \"\"\"Verify setup_vault initializes new vault with passphrase\"\"\"\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            result = setup_vault(\"strong_password\")\n            \n            assert result.is_ok()\n            vault = result.unwrap()\n            assert vault is not None\n\n    def test_setup_vault_creates_directory(self, temp_dir):\n        \"\"\"Verify setup_vault creates signet directory if not exists\"\"\"\n        test_dir = temp_dir / \"new_signet\"\n        \n        with patch('src_vault.signet_dir', return_value=test_dir):\n            setup_vault(\"password\")\n            \n            assert test_dir.exists()\n\n\nclass TestUnlockVault:\n    \"\"\"Tests for unlock_vault function\"\"\"\n\n    def test_unlock_vault_success(self, temp_dir):\n        \"\"\"Verify unlock_vault opens existing vault with correct passphrase\"\"\"\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            setup_result = setup_vault(\"correct_password\")\n            assert setup_result.is_ok()\n            \n            unlock_result = unlock_vault(\"correct_password\")\n            assert unlock_result.is_ok()\n\n    @patch('os.path.exists')\n    def test_unlock_vault_no_vault(self, mock_exists):\n        \"\"\"Verify unlock_vault fails when vault.meta not found\"\"\"\n        mock_exists.return_value = False\n        \n        result = unlock_vault(\"password\")\n        assert result.is_err()\n        assert \"no_vault\" in result.unwrap_err()\n\n    def test_unlock_vault_wrong_passphrase(self, temp_dir):\n        \"\"\"Verify unlock_vault fails and increments failed_attempts on wrong passphrase\"\"\"\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            setup_vault(\"correct_password\")\n            \n            result = unlock_vault(\"wrong_password\")\n            assert result.is_err()\n            assert \"wrong_passphrase\" in result.unwrap_err()\n\n    def test_unlock_vault_lockout_triggered(self, temp_dir):\n        \"\"\"Verify unlock_vault triggers lockout at MAX_FAILED_ATTEMPTS\"\"\"\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            setup_vault(\"correct_password\")\n            \n            # Fail 5 times\n            for i in range(5):\n                unlock_vault(\"wrong\")\n            \n            # 5th attempt should trigger lockout\n            result = unlock_vault(\"wrong\")\n            assert result.is_err()\n            # Either wrong_passphrase or locked_out\n\n\nclass TestTryLoadVault:\n    \"\"\"Tests for try_load_vault function\"\"\"\n\n    def test_try_load_vault_success(self, temp_dir):\n        \"\"\"Verify try_load_vault loads vault from cached session key\"\"\"\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            setup_result = setup_vault(\"password\")\n            assert setup_result.is_ok()\n            \n            unlock_result = unlock_vault(\"password\")\n            assert unlock_result.is_ok()\n            \n            # Now try_load should work\n            loaded = try_load_vault()\n            # May return None if cache doesn't persist in test\n\n    @patch('os.path.exists')\n    def test_try_load_vault_cache_missing(self, mock_exists):\n        \"\"\"Verify try_load_vault returns None when session key cache missing\"\"\"\n        mock_exists.return_value = False\n        \n        result = try_load_vault()\n        assert result is None\n\n\nclass TestMakeTestVault:\n    \"\"\"Tests for make_test_vault helper\"\"\"\n\n    def test_make_test_vault_creates_temp_vault(self, temp_dir):\n        \"\"\"Verify make_test_vault creates vault in temp directory for testing\"\"\"\n        vault = make_test_vault(str(temp_dir), \"test_pass\")\n        \n        assert vault is not None\n        # Verify vault is operational\n        vault.log_action(\"test\", \"ALLOW\", \"api\", 1.0, \"test\")\n\n\n# ============================================================================\n# INVARIANT TESTS\n# ============================================================================\n\nclass TestInvariants:\n    \"\"\"Tests for contract invariants\"\"\"\n\n    def test_invariant_salt_len_32(self, temp_dir):\n        \"\"\"Verify SALT_LEN constant is 32 bytes\"\"\"\n        # Check during setup\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            # Mock to capture salt generation\n            with patch('src_vault.random.bytes') as mock_random:\n                mock_random.return_value = b'0' * 32\n                setup_vault(\"password\")\n                \n                # Verify 32 bytes requested\n                # mock_random.assert_called_with(32)\n\n    def test_invariant_key_len_32(self):\n        \"\"\"Verify KEY_LEN constant is 32 bytes (AES-256)\"\"\"\n        key = derive_master_key(\"password\", b'salt' * 8)\n        assert len(key) == 32\n\n    def test_invariant_nonce_len_12(self):\n        \"\"\"Verify NONCE_LEN constant is 12 bytes (AES-GCM)\"\"\"\n        key = b'k' * 32\n        ciphertext = encrypt(key, b'data')\n        # First 12 bytes should be nonce\n        assert len(ciphertext) >= 12\n\n    @patch('src_vault.now_epoch')\n    def test_invariant_session_ttl_1800(self, mock_time, test_vault):\n        \"\"\"Verify SESSION_TTL_SECS is 1800.0 (30 minutes)\"\"\"\n        mock_time.return_value = 1000.0\n        test_vault.load_or_create_session_start()\n        \n        # Advance 1801 seconds\n        mock_time.return_value = 1000.0 + 1801.0\n        new_ts = test_vault.load_or_create_session_start()\n        \n        # Should create new session (expired)\n        assert new_ts > 1000.0\n\n    def test_invariant_max_failed_attempts_5(self, temp_dir):\n        \"\"\"Verify MAX_FAILED_ATTEMPTS is 5\"\"\"\n        with patch('src_vault.signet_dir', return_value=temp_dir):\n            setup_vault(\"password\")\n            \n            # 5 failures should trigger lockout\n            for i in range(6):\n                result = unlock_vault(\"wrong\")\n                if i >= 4:\n                    # Should be locked after 5 attempts\n                    assert result.is_err()\n\n    def test_invariant_lockout_secs_300(self, temp_dir):\n        \"\"\"Verify LOCKOUT_SECS is 300.0 (5 minutes)\"\"\"\n        # Lockout duration check (implementation-dependent)\n        pass\n\n    def test_invariant_max_preflight_constraints_20(self, test_vault):\n        \"\"\"Verify MAX_PREFLIGHT_CONSTRAINTS is 20\"\"\"\n        constraints = [\n            SoftConstraint(\n                name=f\"c{i}\",\n                tool_pattern=\".*\",\n                conditions=[],\n                action=\"DENY\",\n                reason=\"test\",\n                alternative=\"alt\"\n            )\n            for i in range(21)\n        ]\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=constraints,\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_err()\n\n    def test_invariant_violation_threshold_5(self, test_vault):\n        \"\"\"Verify DEFAULT_VIOLATION_THRESHOLD is 5\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test_id\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=int(now_epoch()),\n            lockout_until=int(now_epoch()) + 1000,\n            violation_count=4,\n            escalated=False\n        )\n        \n        test_vault.store_preflight(preflight)\n        \n        # 5th violation should escalate\n        violation = PreflightViolation(\n            preflight_id=\"test_id\",\n            constraint_name=\"test\",\n            tool_name=\"tool\",\n            parameters_summary=\"params\",\n            alternative=\"alt\",\n            timestamp=int(now_epoch())\n        )\n        \n        test_vault.log_preflight_violation(violation)\n        \n        active = test_vault.active_preflight()\n        assert active.escalated is True\n\n    def test_invariant_tier2_session_key(self, test_vault):\n        \"\"\"Verify tier 2 credentials encrypted with session_key\"\"\"\n        test_vault.store_credential(\"key\", \"value\", 2)\n        # Implementation detail - tier 2 uses session_key\n        # Verified through successful retrieval\n\n    def test_invariant_tier3_compartment_key(self, test_vault):\n        \"\"\"Verify tier 3 credentials encrypted with compartment_key\"\"\"\n        test_vault.store_credential(\"key\", \"value\", 3)\n        # Implementation detail - tier 3 uses compartment_key\n        # Verified through successful retrieval\n\n    def test_invariant_session_spend_only_allowed(self, test_vault):\n        \"\"\"Verify session_spend counts only decision=ALLOW\"\"\"\n        test_vault.log_action(\"tool1\", \"ALLOW\", \"api\", 5.0, \"detail\")\n        test_vault.log_action(\"tool2\", \"DENY\", \"api\", 100.0, \"detail\")\n        \n        total = test_vault.session_spend(\"api\")\n        assert total == 5.0\n\n    def test_invariant_preflight_constraints_non_empty_alternative(self, test_vault):\n        \"\"\"Verify preflight constraints must have non-empty alternatives\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"DENY\",\n            reason=\"test\",\n            alternative=\"\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_err()\n\n    def test_invariant_preflight_action_deny_or_ask(self, test_vault):\n        \"\"\"Verify constraint action must be DENY or ASK\"\"\"\n        constraint = SoftConstraint(\n            name=\"test\",\n            tool_pattern=\".*\",\n            conditions=[],\n            action=\"ALLOW\",  # Invalid\n            reason=\"test\",\n            alternative=\"alt\"\n        )\n        \n        preflight = Preflight(\n            id=\"test\",\n            task=\"task\",\n            risks=[],\n            constraints=[constraint],\n            submitted_at=1000,\n            lockout_until=2000,\n            violation_count=0,\n            escalated=False\n        )\n        \n        result = test_vault.store_preflight(preflight)\n        assert result.is_err()\n\n\nif __name__ == '__main__':\n    pytest.main([__file__, '-v'])\n"
}