agentleFS
CloudflareKnown publishercloudflare/ai-search-snippet/AGENTS.md

ai-search-snippet

AGENTS.md30 starsChanged 5 months agoMITView on GitHub

This document provides guidelines for AI coding agents working in this repository. ai-search-snippet is a pnpm monorepo containing a zero-dependency TypeScript Web Component library for search and chat interfaces with streaming support, along with a Cloudflare Workers demo site and framework integration demos.

  • Installs packages
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

The file

We split this AGENTS.md into the rules it gives an agent

12 rules. About 0 are common, 3 are distinctive, and 9 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 9

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Always include .ts extension in imports

    line 93
  2. Very specific:

    Use try-catch with typed errors: (error as Error).message

    line 115
  3. Very specific:

    Check for AbortError before showing error states

    line 116
  4. Distinctive:

    Always guard against duplicate registration:

    line 123
  5. Very specific:

    Use the createCustomEvent utility for Shadow DOM compatibility:

    line 151
  6. Distinctive:

    Always sanitize user content before rendering:

    line 159
  7. Distinctive:

    Use AbortController for cancellable requests:

    line 186
  8. Very specific:

    Missing .ts extension: Always include in imports

    line 234
  9. Very specific:

    Unescaped HTML: Always use escapeHTML() for user content

    line 236
  10. Very specific:

    Type-only imports: Use import type for interfaces/types

    line 238
  11. Very specific:

    CSS variable prefix: Always use --search-snippet- or --chat-bubble-

    line 239
  12. Very specific:

    Workspace dependencies: Use workspace:* for internal package references

    line 240

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

AGENTS.md - Agentic Coding Guide

This document provides guidelines for AI coding agents working in this repository.

Project Overview

ai-search-snippet is a pnpm monorepo containing a zero-dependency TypeScript Web Component library for search and chat interfaces with streaming support, along with a Cloudflare Workers demo site and framework integration demos.

Monorepo Structure

/
├── packages/
│   └── snippet/           # @cloudflare/ai-search-snippet (publishable library)
│       └── src/           # Library source code
├── apps/
│   ├── workers/           # Cloudflare Workers demo site (search.ai.cloudflare.com)
│   ├── demo-react/        # React integration demo
│   └── demo-vue/          # Vue integration demo
├── pnpm-workspace.yaml    # Workspace configuration
├── tsconfig.base.json     # Shared TypeScript base config
└── biome.json             # Shared linting/formatting config

Commands

Root (all packages)

pnpm install                # Install all workspace dependencies
pnpm run build              # Build all packages
pnpm run lint               # Lint all packages
pnpm run check              # Full Biome check with auto-fix (recommended)
pnpm run typecheck          # Type check all packages
pnpm run test               # Run all tests

Library (packages/snippet)

pnpm --filter @cloudflare/ai-search-snippet run build       # Build library (outputs to dist/)
pnpm --filter @cloudflare/ai-search-snippet run typecheck   # Type check library

Workers App (apps/workers)

pnpm --filter ai-search-snippet-workers run dev      # Start Vite dev server
pnpm --filter ai-search-snippet-workers run build    # Build for deployment
pnpm --filter ai-search-snippet-workers run deploy   # Deploy to Cloudflare Workers

Demo Apps

pnpm --filter demo-react run dev     # Start React demo dev server
pnpm --filter demo-vue run dev       # Start Vue demo dev server

Code Quality

pnpm run lint             # Run Biome linter
pnpm run lint:fix         # Auto-fix lint issues
pnpm run format           # Format code with Biome
pnpm run format:check     # Check formatting without changes
pnpm run check            # Full Biome check with auto-fix (recommended)
pnpm run typecheck        # Type check all packages

Testing

pnpm run test                          # Run all tests across workspace
pnpm --filter @cloudflare/ai-search-snippet exec vitest        # Run snippet tests
pnpm --filter @cloudflare/ai-search-snippet exec vitest run    # Run tests once (CI mode)

Code Style

Formatting (Biome)

  • Indent: 2 spaces
  • Quotes: Single quotes ('string')
  • Semicolons: Always required
  • Trailing commas: ES5 style (in objects/arrays, not function params)
  • Line width: 100 characters max

TypeScript

  • Target: ES2022
  • Strict mode: Enabled (all strict flags)
  • No unused variables: Enforced (noUnusedLocals, noUnusedParameters)
  • Use satisfies: For type validation without widening
  • Use import type: For type-only imports (enforced by verbatimModuleSyntax)

Import Organization

  1. Type imports first (using import type)
  2. External dependencies (none in this project)
  3. Internal modules by path depth (deepest last)
  4. Always include .ts extension in imports
// Correct import style
import type { SearchResult, SearchOptions } from '../types/index.ts';
import { baseStyles } from '../styles/theme.ts';
import { escapeHTML, createCustomEvent } from '../utils/index.ts';

Naming Conventions

TypeConventionExample
ClassesPascalCaseSearchBarSnippet
Interfaces/TypesPascalCaseSearchResult
Functions/MethodscamelCaseperformSearch()
VariablescamelCaseresultsContainer
ConstantsUPPER_SNAKE_CASECOMPONENT_NAME
HTML attributeskebab-caseapi-url, max-results
CSS variableskebab-case with prefix--search-snippet-primary-color
Custom eventskebab-casesearch-complete

Error Handling

  • Use try-catch with typed errors: (error as Error).message
  • Check for AbortError before showing error states
  • Log errors with component prefix: console.error('ComponentName:', error)
  • Throw descriptive errors: throw new Error('API URL is required')

Architectural Patterns

Web Component Registration

Always guard against duplicate registration:

const COMPONENT_NAME = 'my-component';

if (!customElements.get(COMPONENT_NAME)) {
  customElements.define(COMPONENT_NAME, MyComponent);
}

Event Handler Cleanup

Store handler references for proper cleanup in disconnectedCallback:

private handleClick: ((e: Event) => void) | null = null;

private attachEventListeners(): void {
  this.handleClick = (e: Event) => { /* ... */ };
  this.element.addEventListener('click', this.handleClick);
}

private cleanup(): void {
  if (this.handleClick) {
    this.element.removeEventListener('click', this.handleClick);
  }
  this.handleClick = null;
}

Custom Events

Use the createCustomEvent utility for Shadow DOM compatibility:

import { createCustomEvent } from '../utils/index.ts';

this.dispatchEvent(createCustomEvent('search-complete', { results }));

Security - XSS Prevention

Always sanitize user content before rendering:

import { escapeHTML } from '../utils/index.ts';

element.innerHTML = `<div>${escapeHTML(userInput)}</div>`;

CSS-in-JS Pattern

Styles are template literals exported from src/styles/ modules:

import { baseStyles } from '../styles/theme.ts';
import { searchStyles } from '../styles/search.ts';

const style = document.createElement('style');
style.textContent = `${baseStyles}\n${searchStyles}`;
this.shadow.appendChild(style);

Async Generators for Streaming

async *chat(query: string): AsyncGenerator<ChatTypes, void, undefined> {
  const response = await this.request(/* ... */);
  yield { type: 'text', message: content };
}

Request Cancellation

Use AbortController for cancellable requests:

private currentController: AbortController | null = null;

private async performRequest(): Promise<void> {
  if (this.currentController) {
    this.currentController.abort();
  }
  this.currentController = new AbortController();
  
  try {
    await fetch(url, { signal: this.currentController.signal });
  } catch (error) {
    if ((error as Error).name === 'AbortError') return;
    throw error;
  }
}

File Organization

Library (packages/snippet/)

packages/snippet/
├── src/
│   ├── api/           # API clients (abstract Client, AISearchClient)
│   ├── components/    # Web Components (one per file)
│   ├── styles/        # CSS-in-JS theme and component styles
│   ├── types/         # TypeScript interfaces and types
│   ├── utils/         # Utility functions (debounce, sanitize, etc.)
│   └── main.ts        # Library entry point and exports
├── package.json       # @cloudflare/ai-search-snippet
├── tsconfig.json      # Extends ../../tsconfig.base.json
└── vite.config.ts     # Library build config

Workers App (apps/workers/)

apps/workers/
├── index.html         # Demo landing page
├── worker.js          # Cloudflare Worker entrypoint
├── wrangler.jsonc     # Cloudflare Workers config
├── vite.config.ts     # App build config (Cloudflare plugin)
└── public/            # Static assets

Common Pitfalls

  1. Missing .ts extension: Always include in imports
  2. Forgetting event cleanup: Store handler refs, clean in disconnectedCallback
  3. Unescaped HTML: Always use escapeHTML() for user content
  4. Duplicate registration: Guard customElements.define() calls
  5. Type-only imports: Use import type for interfaces/types
  6. CSS variable prefix: Always use --search-snippet- or --chat-bubble-
  7. Workspace dependencies: Use workspace:* for internal package references
  8. Build order: Library must build before apps that depend on it (pnpm run build handles this)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.