> ## 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.

# Custom Rules

> Writing custom validation rules and combining built-in rules

ast-guard allows you to write custom validation rules and combine built-in rules to match your specific security requirements.

## Combining Built-in Rules

Create a custom validator by combining built-in rules:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import {
  JSAstValidator,
  DisallowedIdentifierRule,
  ForbiddenLoopRule,
  RequiredFunctionCallRule,
  UnknownGlobalRule,
} from '@enclave-vm/ast';

const customValidator = new JSAstValidator([
  new DisallowedIdentifierRule({
    disallowed: ['eval', 'Function', 'process', 'require'],
  }),
  new ForbiddenLoopRule({
    allowFor: true,
    allowWhile: false,
  }),
  new RequiredFunctionCallRule({
    required: ['callTool'],
    minCalls: 1,
  }),
  new UnknownGlobalRule({
    allowedGlobals: ['callTool', 'Math', 'JSON', 'Array', 'Object'],
    allowStandardGlobals: true,
  }),
]);

const result = await customValidator.validate(code);
```

## Security Presets

ast-guard includes pre-built security presets:

| Preset | Use Case | Security Level |
| - | - | - |
| **AgentScript** | LLM-generated code | Highest - whitelist-only |
| **STRICT** | Untrusted guest code | High - no loops, no async |
| **SECURE** | Automation scripts | Medium - bounded loops only |
| **STANDARD** | Trusted scripts | Low - basic guardrails |
| **PERMISSIVE** | Internal/test code | Minimal - eval blocked |

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

// AgentScript (recommended for LLM code)
const agentScript = new JSAstValidator(createAgentScriptPreset());

// STRICT preset
const strict = new JSAstValidator(Presets.strict({
  requiredFunctions: ['callTool'],
  minFunctionCalls: 1,
}));

// SECURE preset
const secure = new JSAstValidator(Presets.secure({
  allowedLoops: { allowForOf: true },
}));

// STANDARD preset
const standard = new JSAstValidator(Presets.standard());
```

## Writing Custom Rules

### Rule Interface

A rule has a name, a description, a default severity and a `validate` method. It reports what it finds through `context.report`; it does not return a list.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ValidationRule {
  readonly name: string;                       // Unique identifier
  readonly description: string;
  readonly defaultSeverity: ValidationSeverity;
  readonly enabledByDefault: boolean;
  validate(context: ValidationContext): void | Promise<void>;
}

interface ValidationContext {
  ast: acorn.Node;           // Parsed AST (acorn)
  source: string;            // Original source code
  config: ValidationConfig;  // The options of this validation
  report(issue: {
    code: string;
    message: string;
    severity?: ValidationSeverity; // Default: the rule's (or the one configured for it)
    location?: { line: number; column: number };
    data?: Record<string, unknown>;
  }): void;
}
```

A rule passed to the `JSAstValidator` constructor runs in every validation that does not switch it off by name (`rules: { 'rule-name': false }`). The validator collects at most `maxIssues` issues (100 by default), so a rule that reports once per node cannot make the result grow with the source.

### Example: Custom Rule

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, ValidationSeverity, createAgentScriptPreset } from '@enclave-vm/ast';
import type { ValidationRule, ValidationContext } from '@enclave-vm/ast';
import * as walk from 'acorn-walk';

class NoMagicNumbersRule implements ValidationRule {
  readonly name = 'no-magic-numbers';
  readonly description = 'Numbers other than the allowed ones should be named constants';
  readonly defaultSeverity = ValidationSeverity.WARNING;
  readonly enabledByDefault = true;
  private allowedNumbers: number[];

  constructor(options: { allowed?: number[] } = {}) {
    this.allowedNumbers = options.allowed || [0, 1, -1];
  }

  validate(context: ValidationContext): void {
    walk.simple(context.ast as any, {
      Literal: (node: any) => {
        if (typeof node.value === 'number' && !this.allowedNumbers.includes(node.value)) {
          context.report({
            code: 'NO_MAGIC_NUMBERS',
            message: `Magic number ${node.value} should be a named constant`,
            location: node.loc ? { line: node.loc.start.line, column: node.loc.start.column } : undefined,
          });
        }
      },
    });
  }
}

// Usage: a preset is an array of rules
const validator = new JSAstValidator([
  ...createAgentScriptPreset(),
  new NoMagicNumbersRule({ allowed: [0, 1, -1, 10, 100] }),
]);
```

### Example: Block Specific API Calls

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
class BlockedApiCallsRule implements ValidationRule {
  readonly name = 'blocked-api-calls';
  readonly description = 'Blocks tool calls by name prefix';
  readonly defaultSeverity = ValidationSeverity.ERROR;
  readonly enabledByDefault = true;
  private blockedApis: string[];

  constructor(options: { blocked: string[] }) {
    this.blockedApis = options.blocked;
  }

  validate(context: ValidationContext): void {
    walk.simple(context.ast as any, {
      CallExpression: (node: any) => {
        if (node.callee.type !== 'Identifier' || node.callee.name !== 'callTool') return;
        const firstArg = node.arguments[0];
        if (firstArg?.type === 'Literal' && typeof firstArg.value === 'string') {
          if (this.blockedApis.some((api) => firstArg.value.startsWith(api))) {
            context.report({
              code: 'BLOCKED_API_CALL',
              message: `API "${firstArg.value}" is blocked`,
              location: node.loc ? { line: node.loc.start.line, column: node.loc.start.column } : undefined,
            });
          }
        }
      },
    });
  }
}

// Usage
const validator = new JSAstValidator([
  ...createAgentScriptPreset(),
  new BlockedApiCallsRule({
    blocked: ['admin:', 'system:', 'internal:'],
  }),
]);
```

This rule sees a tool name only where `callTool` is called directly with a string literal. The AgentScript preset already requires exactly that form (`staticCallTarget`), and its `allowedToolNames` option restricts the names; a rule like this one adds to it and does not stand alone.

## Extending Presets

A preset function returns an array of rules. Add rules to it:

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

const validator = new JSAstValidator([
  ...createAgentScriptPreset(),
  new CustomRule1(),
  new CustomRule2(),
]);
```

## Removing Rules from Presets

Filter out rules you don't need:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator(
  createAgentScriptPreset().filter((rule) => rule.name !== 'no-regex-literal'),
);
```

> [!WARNING]
>
> The rules of the AgentScript preset depend on each other: several of them are only sound because another one refuses a construct. Removing a rule can open more than that rule's name suggests. Do it only for a host that does not run untrusted code.

## Rule Ordering

Rules are executed in array order. For performance, order rules by:

1. **Fast rejections first** - Rules that quickly identify invalid code
2. **Complex analysis last** - Rules that traverse the entire AST

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator([
  // Fast: Check for blocked identifiers
  new DisallowedIdentifierRule({ disallowed: ['eval'] }),

  // Medium: Check call structure
  new RequiredFunctionCallRule({ required: ['callTool'] }),

  // Slower: Full AST traversal
  new UnknownGlobalRule({ allowedGlobals: ['Math', 'JSON', 'console', 'callTool'] }),
]);
```

## Testing Custom Rules

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator } from '@enclave-vm/ast';
import { describe, it, expect } from 'vitest';

describe('CustomRule', () => {
  const validator = new JSAstValidator([new CustomRule()]);

  it('should block dangerous pattern', async () => {
    const result = await validator.validate('dangerous code');
    expect(result.valid).toBe(false);
    expect(result.issues[0].code).toBe('CUSTOM_RULE');
  });

  it('should allow safe pattern', async () => {
    const result = await validator.validate('safe code');
    expect(result.valid).toBe(true);
  });
});
```

## Related

* [Security Rules](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/security-rules.md) - Built-in rules reference
* [AgentScript Preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/agentscript-preset.md) - Default preset
* [Overview](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/overview.md) - Getting started


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