> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentfront.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Debugging

> Techniques for debugging Enclave code execution

This page covers techniques for debugging issues with Enclave code execution.

## Validation Debugging

### Pre-validate Code

To see why a script is refused, run the steps of the enclave yourself: pre-scan the script as it was written, transform it, then validate the transformed code. (AgentScript allows a top-level `return` and `await`, which only parse once the script is wrapped.)

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, PreScanner, createAgentScriptPreset, transformAgentScript } from '@enclave-vm/ast';

async function debugValidation(code: string) {
  // Step 1: Pre-scan the script as written. 'agentscript' is the preset of an enclave
  // with the default AST preset; an enclave with a `preScan` option uses that instead.
  const scan = new PreScanner({ preset: 'agentscript' }).scan(code);
  if (!scan.success) {
    console.log('Pre-scan failed:', scan.fatalIssue?.code, scan.fatalIssue?.message);
    return;
  }

  // Step 2: Transform, as the enclave does before it validates
  let transformed: string;
  try {
    transformed = transformAgentScript(code, { maxIterations: 10000 });
  } catch (error) {
    console.log('Transform failed:', (error as Error).message);
    return;
  }

  // Step 3: AST validation of the transformed code. The pre-scan is done (step 1).
  const validator = new JSAstValidator(createAgentScriptPreset());
  const result = await validator.validate(transformed, { preScan: { enabled: false } });

  if (!result.valid) {
    console.log('Validation failed:');
    for (const issue of result.issues) {
      console.log(`  [${issue.code}] ${issue.message}`);
      if (issue.location) {
        console.log(`    Line ${issue.location.line}, Column ${issue.location.column}`);
      }
    }
  } else {
    console.log('Validation passed!');
  }
}
```

The enclave validates with its own list of allowed globals (your `globals` and `toolNamespaces` included), so a script that uses them is refused by this stand-alone validator and accepted by `run()`. The issues `run()` itself found are in `result.error.data.issues`.

### View Transformed Code

See what the code looks like after transformation:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { transformAgentScript } from '@enclave-vm/ast';

const original = `
  const users = await callTool('users:list', {});
  return users.length;
`;

const transformed = transformAgentScript(original, {
  wrapInMain: true,
  transformCallTool: true,
  transformLoops: true,
});

console.log('Transformed code:');
console.log(transformed);
```

## Runtime Debugging

### Use Console Logging

A script may use `console` when the enclave has a `consoleHandler`, which receives each call as `(level, message)`. The result has no captured output: collect the lines in the handler.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const lines: string[] = [];

const enclave = new Enclave({
  consoleHandler: (level, message) => {
    lines.push(`[${level}] ${message}`);
  },
  toolHandler: async (name, args) => executeTool(name, args),
});

const code = `
  console.log('Starting execution');
  const users = await callTool('users:list', {});
  console.log('Got', users.length, 'users');

  for (const user of users) {
    console.log('Processing:', user.name);
  }

  console.log('Done!');
  return users.length;
`;

const result = await enclave.run(code);

console.log('Script output:', lines);
```

Without a `consoleHandler`, `console` is allowed only at `PERMISSIVE` and writes to the host process console.

### Track Tool Calls

Log all tool calls in your handler:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  toolHandler: async (name, args) => {
    console.log(`[Tool] ${name}`, JSON.stringify(args));

    const start = Date.now();
    const result = await executeTool(name, args);
    const duration = Date.now() - start;

    console.log(`[Tool] ${name} completed in ${duration}ms`);
    return result;
  },
});
```

### Inspect Execution Stats

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await enclave.run(code);

console.log('Execution stats:', {
  success: result.success,
  duration: `${result.stats.duration}ms`,
  toolCalls: result.stats.toolCallCount,
  iterations: result.stats.iterationCount,
  memoryUsed: result.stats.memoryUsage
    ? `${Math.round(result.stats.memoryUsage / 1024)}KB`
    : 'not tracked',
});
```

## Error Debugging

### Detailed Error Information

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await enclave.run(code);

if (!result.success) {
  console.log('Execution failed:');
  console.log('  Code:', result.error?.code);
  console.log('  Name:', result.error?.name);
  console.log('  Message:', result.error?.message);

  // Only errors made outside the sandbox have a stack: an error a script threw has none
  if (result.error?.stack) {
    console.log('  Stack:', result.error.stack);
  }

  if (result.error?.data) {
    console.log('  Additional data:', result.error.data);
  }
}
```

### Error Code Reference

| Code | Meaning | Debug Steps |
| - | - | - |
| `VALIDATION_ERROR` | AST validation failed | Check `error.data.issues` |
| `DOUBLE_VM_EXECUTION_ERROR` | The script failed while it ran: read `error.message` | See below |
| - `Script execution timed out ...` | Exceeded timeout | Profile slow operations |
| - `Maximum tool call limit exceeded ...` | Too many tool calls | Review call patterns |
| - `Maximum iteration limit exceeded ...` | Loop limit hit | Check loop bounds |
| - any other message | The script threw, or a tool handler did | Debug the script or the tool handler |
| `MEMORY_LIMIT_EXCEEDED` | Memory limit | Profile memory usage (`error.data`) |
| `SCORING_BLOCKED` | Refused by the scoring gate | Read `error.data.signals` |
| `ENCLAVE_ERROR` | Failure before the script ran, such as a syntax error | Read `error.message` |

With `doubleVm: { enabled: false }` the code of a failing script is `VM_EXECUTION_ERROR`. See [Error Codes](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/configuration.md#error-codes).

## Scoring Gate Debugging

### Log Score Details

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  scoringGate: {
    scorer: 'rule-based',
    blockThreshold: 70,
    warnThreshold: 40,
    verbose: true, // Log every score and its signals to the console
  },
});

const result = await enclave.run(code);

// The gate has no callback: the score is in the result
console.log('Scoring result:', {
  score: result.scoringResult?.totalScore,
  signals: result.scoringResult?.signals,
  allowed: result.scoringResult?.allowed,
});
```

### Test Scoring Separately

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { ScoringGate } from '@enclave-vm/core';

const gate = new ScoringGate({ scorer: 'rule-based', blockThreshold: 70 });
const result = await gate.evaluate(code);

console.log('Score:', result.totalScore);
console.log('Signals:', result.signals);
console.log('Allowed:', result.allowed);

gate.dispose();
```

The gate of an enclave scores the transformed script and knows the enclave's tool namespaces; a gate you create yourself sees `callTool` calls only, unless you pass it `toolNamespaces`.

## Performance Debugging

### Measure Tool Call Latency

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const toolMetrics: Map<string, number[]> = new Map();

const enclave = new Enclave({
  toolHandler: async (name, args) => {
    const start = performance.now();
    const result = await executeTool(name, args);
    const duration = performance.now() - start;

    const metrics = toolMetrics.get(name) || [];
    metrics.push(duration);
    toolMetrics.set(name, metrics);

    return result;
  },
});

// After execution
for (const [name, durations] of toolMetrics) {
  const avg = durations.reduce((a, b) => a + b, 0) / durations.length;
  console.log(`${name}: ${durations.length} calls, avg ${avg.toFixed(2)}ms`);
}
```

### Profile Memory Usage

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  memoryLimit: 64 * 1024 * 1024,
});

const result = await enclave.run(code);

if (result.stats.memoryUsage) {
  const mb = result.stats.memoryUsage / (1024 * 1024);
  console.log(`Peak memory: ${mb.toFixed(2)}MB`);
}
```

## Testing Scripts

### Create a Test Harness

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
async function testScript(
  code: string,
  expectedResult: unknown,
  tools: Record<string, Function>
) {
  const enclave = new Enclave({
    securityLevel: 'SECURE',
    toolHandler: async (name, args) => {
      const tool = tools[name];
      if (!tool) throw new Error(`Unknown tool: ${name}`);
      return tool(...Object.values(args));
    },
  });

  const result = await enclave.run(code);
  enclave.dispose();

  if (!result.success) {
    throw new Error(`Script failed: ${result.error?.message}`);
  }

  expect(result.value).toEqual(expectedResult);
}

// Usage
await testScript(
  `return await callTool('add', { a: 1, b: 2 })`,
  3,
  { add: (a: number, b: number) => a + b }
);
```

## Related

* [Common Errors](https://docs.agentfront.dev/enclave/troubleshooting/common-errors.md) - Error reference
* [FAQ](https://docs.agentfront.dev/enclave/troubleshooting/faq.md) - Frequently asked questions


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.