# How the Neural Attestation System Detects Behavioral Drift in ClosedClaw

> Discover how the Neural Attestation system in ClosedClaw detects behavioral drift. Learn about activation vector comparison and cosine similarity for LLM integrity.

- Repository: [aSafeLobotomy/closedclaw](https://github.com/asafelobotomy/closedclaw)
- Tags: deep-dive
- Published: 2026-02-25

---

**The Neural Attestation system detects behavioral drift by comparing live LLM activation vectors against a stored Neural Fingerprint using cosine similarity, triggering protective actions when similarity drops below configurable thresholds.**

The Neural Attestation system for detecting behavioral drift is a runtime security mechanism implemented in the `asafelobotomy/closedclaw` repository. It continuously validates that an agent’s internal state matches its originally calibrated neural signature, preventing compromised or altered behaviors from executing sensitive operations.

## Core Mechanism: Cosine Similarity Against Neural Fingerprints

At the heart of the system lies a mathematical comparison between two vectors: the **live activation state** captured during tool invocation and the **Neural Fingerprint** recorded during initial calibration.

The system computes **cosine similarity** between these vectors using the formula implemented in `cosineSimilarity(a, b)`:

- Dot product of the two vectors divided by the product of their magnitudes
- Resulting value bounded between `0` and `1`

Based on this similarity score, the system classifies drift severity using two configurable thresholds:

| Similarity Range | Drift Severity | System Action |
|------------------|----------------|---------------|
| ≥ 0.94 (soft-drift threshold) | **None** | Allow execution |
| ≥ 0.85 & < 0.94 (hard-drift threshold) | **Soft drift** | Log event / throttle execution |
| < 0.85 | **Hard drift** | Block execution (integrity shutdown) |

## Architectural Components

The implementation splits responsibilities between a stateful runtime monitor and a pure functional interface used by the security kernel.

### AttestationMonitor (Stateful Runtime)

Located in [`src/agents/clawtalk/neural-attestation.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/src/agents/clawtalk/neural-attestation.ts), the `AttestationMonitor` class maintains the baseline fingerprint and manages the complete attestation lifecycle:

- Stores the `neuralDigest` (baseline fingerprint array) parsed from Block 9 of `.claws` files
- Applies configurable `softDriftThreshold` (default 0.94) and `hardDriftThreshold` (default 0.85)
- Records drift events via `recordEvent()` for audit trails
- Automatically quarantines tools exhibiting hard drift by adding them to `_quarantinedTools`
- Supports refingerprinting workflows when intentional behavioral updates occur

### checkAttestation (Kernel Shield Layer 3)

Found in [`src/agents/clawtalk/kernel-shield.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/src/agents/clawtalk/kernel-shield.ts), the `checkAttestation()` function provides a pure, stateless interface for the Kernel Shield’s Layer 3:

- Accepts a `ClawsNeuralFingerprint` (which may be null) and a `liveActivation` vector
- Returns an `AttestationResult` with `action` fields: `"allow"`, `"log"`, or `"block"`
- Uses identical cosine similarity logic as `AttestationMonitor` but without maintaining state
- Enables the Kernel Shield to merge Layer 3 results with Layers 1 and 2, applying the strictest action

## The Eight-Step Drift Detection Workflow

The Neural Attestation system executes the following sequence during every tool invocation:

1. **Baseline capture** – When parsing a `.claws` file, Block 9 contains the `neuralDigest` as a comma-separated list of floats. The `parseDigest` helper converts this string into a numeric array.

2. **Live activation extraction** – Each tool call supplies a dense float array (`liveActivation`) representing the LLM’s hidden state at the moment of invocation.

3. **Cosine similarity computation** – The system calculates similarity between the live vector and stored fingerprint using `cosineSimilarity(a, b)`.

4. **Threshold selection** – Default thresholds (`softDriftThreshold = 0.94`, `hardDriftThreshold = 0.85`) from `DEFAULT_CONFIG` are applied, unless overridden by the fingerprint’s optional `driftThresholds` field.

5. **Drift classification** – The similarity score maps to a `DriftSeverity` enum: `none`, `soft_drift`, or `hard_drift`.

6. **Action determination** – 
   - `AttestationMonitor.check()` returns an `AttestationCheck` with boolean flags (`allow`, `throttle`, `shutdown`)
   - `checkAttestation()` returns an `AttestationResult` with `action` strings (`allow`, `log`, `block`)

7. **Kernel integration** – Layer 3’s result merges with Layers 1 and 2; the strictest action wins, ensuring hard drift immediately blocks execution.

8. **Audit and quarantine** – `AttestationMonitor` logs each event via `recordEvent()` and automatically adds hard-drift tools to `_quarantinedTools`, requiring manual review before reactivation.

## Implementation Examples

### Using AttestationMonitor for Stateful Monitoring

The following example demonstrates runtime monitoring with automatic quarantine capabilities:

```typescript
import { AttestationMonitor } from "./neural-attestation.js";
import type { ClawsNeuralFingerprint } from "./claws-parser.js";

// Parse fingerprint from .claws file Block 9
const fingerprint: ClawsNeuralFingerprint = {
  neuralDigest: [0.12, -0.45, 0.89, /* ... 512 dimensions ... */],
  driftThresholds: { soft: 0.95, hard: 0.87 }
};

// Initialize monitor with custom soft threshold
const monitor = new AttestationMonitor(fingerprint, { 
  softDriftThreshold: 0.95 
});

// During tool execution
const liveActivation: number[] = getLiveActivationVector();
const result = monitor.check("httpFetch", liveActivation);

if (!result.allow) {
  console.warn(`Attestation failed: ${result.message}`);
  // Tool automatically quarantined if hard drift detected
  if (result.shutdown) {
    abortToolExecution();
  }
}

```

### Direct Integration with Kernel Shield

For lightweight, stateless checks within the security kernel:

```typescript
import { checkAttestation } from "./kernel-shield.js";

const fingerprint = parsedClaws.neuralFingerprint; // may be null
const liveActivation = captureNeuralState();

const attestation = checkAttestation(fingerprint, liveActivation);

switch (attestation.action) {
  case "allow":
    executeTool();
    break;
  case "log":
    console.info(`Soft drift detected (similarity=${attestation.similarity})`);
    executeToolWithThrottle();
    break;
  case "block":
    console.error(`Hard drift! Blocking execution (similarity=${attestation.similarity})`);
    triggerIntegrityShutdown();
    break;
}

```

## Key Source Files

| File | Role |
|------|------|
| [`src/agents/clawtalk/neural-attestation.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/src/agents/clawtalk/neural-attestation.ts) | Implements `AttestationMonitor`, configuration, event logging, and refingerprinting workflow |
| [`src/agents/clawtalk/kernel-shield.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/src/agents/clawtalk/kernel-shield.ts) | Provides the pure `checkAttestation` function and integrates Layer 3 into the overall Shield verdict |
| [`src/agents/clawtalk/claws-parser.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/src/agents/clawtalk/claws-parser.ts) | Defines `ClawsNeuralFingerprint` (Block 9) and parses the fingerprint from `.claws` files |
| [`src/config/types.security.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/src/config/types.security.ts) | Documents the security layers, mentioning Neural Attestation as Layer 3 |
| [`CLOSEDCLAW-PLAN.md`](https://github.com/asafelobotomy/closedclaw/blob/main/CLOSEDCLAW-PLAN.md) | Lists Block 9 (Neural Fingerprint) and the drift-detection policy |

## Summary

- The Neural Attestation system detects behavioral drift by computing **cosine similarity** between live LLM activation vectors and a stored **Neural Fingerprint** captured during calibration.
- **Threshold-based classification** uses default values of 0.94 (soft drift) and 0.85 (hard drift) to determine severity and response.
- **`AttestationMonitor`** in [`neural-attestation.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/neural-attestation.ts) provides stateful monitoring with automatic quarantine capabilities for hard drift events.
- **`checkAttestation`** in [`kernel-shield.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/kernel-shield.ts) offers a pure functional interface for Layer 3 security integration.
- The system **quarantines** tools exhibiting hard drift, requiring manual review before reactivation, while soft drift events are logged and throttled.

## Frequently Asked Questions

### What triggers a hard drift shutdown in the Neural Attestation system?

A hard drift shutdown triggers when the cosine similarity between the live activation vector and the stored Neural Fingerprint drops below the hard drift threshold, typically set to 0.85. When this occurs, the `AttestationMonitor` automatically blocks execution, logs the event via `recordEvent()`, and adds the offending tool to `_quarantinedTools` pending manual review.

### How does the system handle soft drift versus hard drift?

Soft drift occurs when similarity falls between the soft threshold (0.94) and hard threshold (0.85), indicating minor behavioral deviations. The system logs these events and may throttle execution rather than blocking entirely. Hard drift, occurring below 0.85 similarity, represents significant behavioral anomalies and triggers immediate execution blocking and tool quarantine through the integrity shutdown mechanism.

### Where is the Neural Fingerprint stored in a .claws file?

The Neural Fingerprint resides in Block 9 of the `.claws` file format, stored as a comma-separated list of floating-point numbers representing the `neuralDigest`. The [`claws-parser.ts`](https://github.com/asafelobotomy/closedclaw/blob/main/claws-parser.ts) module extracts this data using the `parseDigest` helper function, converting the string representation into a numeric array used for subsequent cosine similarity comparisons during attestation checks.

### Can attestation thresholds be customized per agent?

Yes, attestation thresholds are configurable both globally and per-fingerprint. The `DEFAULT_CONFIG` defines system-wide defaults (soft: 0.94, hard: 0.85), but individual `ClawsNeuralFingerprint` objects can override these via the optional `driftThresholds` field. When initializing an `AttestationMonitor`, developers can also pass custom threshold values in the constructor options to tailor sensitivity for specific agent deployments.