## Build & Verification
After modifying any `.ss` (Gerbil Scheme) source files, always run the build command and fix any errors before moving on. Common issues include: missing imports, wrong function names, and duplicate definitions.
## Gerbil MCP Tools — MANDATORY Usage
When a Gerbil MCP server is available, you MUST use its tools extensively instead of guessing about Gerbil APIs, syntax, or behavior. Gerbil is a niche Scheme dialect with limited training data — always verify with live tools rather than relying on memory.
### Before Writing Code — Cookbook First!
- **`gerbil_howto`** (**MUST call FIRST**): Before writing ANY non-trivial Gerbil code, search the cookbook for relevant patterns. The cookbook contains verified, working examples with correct imports, arities, and keyword conventions — accumulated from real debugging sessions. Many bugs (wrong arity, missing parent arg, keyword vs positional) are already documented here. Search with the widget/module/task name (e.g., `"dialog create"`, `"layout parent"`, `"shortcut keyboard"`, `"hash iterate"`). **Skipping this step has repeatedly caused bugs that were already solved in the cookbook.**
- **`gerbil_security_scan`** (**MUST run on new/modified code**): Before finalizing ANY Gerbil code that involves FFI, shell commands, file I/O, or C shims, run the security scanner. It checks for known vulnerability patterns (shell injection, FFI type mismatches, resource leaks, unsafe C patterns) and reports findings with severity and remediation guidance. Run on a single file or an entire project. **Skipping this step risks shipping code with known vulnerability patterns that the scanner would have caught.**
- **`gerbil_module_exports`**: Check what a module actually exports before using it. Never guess function names. Handles modules with Gambit `(declare ...)` forms by falling back to compiled `.scm` artifacts.
- **`gerbil_function_signature`**: Check procedure arities and keyword arguments before calling functions. Prevents wrong-number-of-arguments errors. Falls back to scanning compiled `.scm` artifacts for `keyword-dispatch` patterns when source is unavailable. Shows positional vs keyword args for keyword-dispatch functions.
- **`gerbil_check_syntax`**: Validate syntax of any code you write before presenting it.
- **`gerbil_batch_syntax_check`**: Check multiple Gerbil code snippets for syntax validity in a single call. Accepts an array of `{id, code}` objects and returns per-snippet pass/fail results. Much more efficient than individual `gerbil_check_syntax` calls when verifying many functions at once.
- **`gerbil_compile_check`**: Run the full compiler (`gxc -S`) to catch unbound identifiers and type issues beyond syntax. Combines stdout/stderr for complete error output.
- **`gerbil_doc`**: Look up any symbol for type, arity, qualified name, and related symbols.
### When Exploring or Debugging
- **`gerbil_eval`**: Test expressions interactively to verify assumptions and reproduce issues. Cleanly captures stdout output separately from the return value using `parameterize`. Use `env` parameter for FFI library paths (e.g. `DYLD_LIBRARY_PATH`, `LD_LIBRARY_PATH`).
- **`gerbil_apropos`**: Search for symbols by substring when you're unsure of exact names.
- **`gerbil_list_std_modules`**: Discover available standard library modules, optionally filtered by prefix.
- **`gerbil_find_definition`**: Locate where a symbol is defined (source file, module, kind, arity). Use `source_preview: true` to include a code preview. Automatically resolves standard library source files via the Gerbil installation's `src/` tree (`lib/` → `src/` path rewrite).
- **`gerbil_smart_complete`**: Context-aware symbol completion for partial identifiers. Optionally scope completions to specific modules.
- **`gerbil_explain_error`**: Classify Gerbil/Gambit error messages with likely causes, suggested fixes, and relevant cookbook recipes.
- **`gerbil_load_file`**: Parse a `.ss` file to extract its imports, exports, and definitions without executing it.
- **`gerbil_module_deps`**: See what a module imports. Use `transitive: true` for full dependency tree.
- **`gerbil_demangle`**: Decode Gambit-mangled C symbol names from GDB backtraces or core dumps back to readable Gerbil module/function paths. Recognizes prefixes like `___H_` (module init), `___G_` (global).
- **`gerbil_bisect_crash`**: Binary-search a crashing Gerbil file to find the minimal set of top-level forms that reproduce the crash. Keeps preamble (imports, exports, declarations) and bisects body forms. Useful for isolating segfaults and uncaught exceptions in FFI code.
- **`gerbil_describe`**: Evaluate an expression and describe the resulting value's type, structure, and contents. Shows hash table entries, list length, vector elements, string length, number type, etc. Useful for understanding what a function returns.
- **`gerbil_stack_trace_decode`**: Parse GDB/Gambit stack traces and decode mangled C symbol names to readable Gerbil module/function paths. Complements `gerbil_demangle` for full backtrace analysis.
- **`gerbil_function_behavior`**: Behavior card showing return values for normal/edge/error cases. ~50 built-in cards (hash, sort, list, JSON, path, alist, control flow). Dynamic probing for unknown functions.
- **`gerbil_error_fix_lookup`**: Look up known fixes for error messages (~20 built-in mappings: wrong arity, unbound ids, import conflicts, segfaults). Returns explanations, fixes, and related recipes.
- **`gerbil_stdlib_source`**: Read the source code of any standard library module. Resolves module paths to source files via lib→src path rewrite. Useful for understanding internal implementations.
- **`gerbil_trace_eval`**: Step through `let*/let/letrec/letrec*` bindings, showing each variable's name, type, and value as it is bound. Useful for understanding complex binding sequences.
- **`gerbil_sxml_inspect`**: Parse XML text or evaluate an SXML expression and display the tree structure with labeled node types (DOCUMENT, PI, ELEMENT, ATTR, TEXT).
- **`gerbil_port_fd_inspector`**: Extract the internal file descriptor number and properties from a Gambit port object. Evaluates an expression that returns a port and reports fd number, fd type, input/output direction, and tty status. Useful for debugging fd/port dual-layer issues (redirect offsets, pipe lifecycle, dup2). Parameters: `expression` (required), `imports`, `loadpath`, `project_path`, `env`.
### When Understanding Macros
- **`gerbil_expand_macro`**: See the fully expanded core form of a macro expression.
- **`gerbil_trace_macro`**: Step-by-step expansion showing each transformation level.
### When Working with Types and FFI
- **`gerbil_class_info`**: Inspect defclass/defstruct types — slots, fields, inheritance, precedence list, and exact constructor signature with positional argument order (annotates inherited fields).
- **`gerbil_ffi_inspect`**: Classify a module's FFI exports (C constants, C functions, Gerbil wrappers).
- **`gerbil_ffi_scaffold`**: Parse a C header file and generate Gambit FFI binding code with `c-define-type`, `c-lambda`, and `define-const` declarations. Recognizes create/destroy pairs for automatic GC cleanup.
- **`gerbil_ffi_callback_debug`**: Static analysis of FFI `c-define`/`extern` linkage in `.ss` files. Detects orphan callbacks (c-define without matching extern), missing callbacks (extern without c-define), duplicate C names, and c-define outside `begin-foreign` blocks.
- **`gerbil_ffi_type_check`**: Detect FFI type mismatches between `c-lambda`/`define-c-lambda` declarations and call sites. Flags known incompatible combinations like u8vector passed to `(pointer void)`, string passed to int. Static analysis, no subprocess.
- **`gerbil_ffi_null_safety`**: Static analysis of `.scm` FFI files to find `c-lambda` declarations that dereference pointer arguments without null checks. Cross-references with `.ss` wrapper files to check for guards.
- **`gerbil_ffi_buffer_size_audit`**: Cross-reference C function output buffer sizes with Scheme-side `make-u8vector` allocations. Detects potential buffer overflow mismatches.
- **`gerbil_ffi_link_check`**: Cross-reference C function calls in `c-declare` against linked `.a` library symbols via `nm`. Catches missing library links before build.
- **`gerbil_detect_ifdef_stubs`**: Scan `c-declare` blocks for `#ifdef`/`#else` stub patterns (NULL/0 returns) that cause segfaults in exe builds. Scans single file or project.
- **`gerbil_error_hierarchy`**: View the full exception/error class hierarchy tree.
- **`gerbil_gambit_source_extract`**: Identify the exact Gambit commit Gerbil was built with (from `gsc -v`) and optionally extract matching source files from a Gambit git repo. Reports version, commit hash, build date, and architecture. When `gambit_repo_path` is provided, extracts source subdirectories matching the commit. Critical for embedding `gambitgsc` modules. Parameters: `gambit_repo_path`, `output_dir`, `subdirs` (all optional).
### For Multi-Step Exploration
- **`gerbil_repl_session`**: Maintain persistent state across evaluations. Define functions, import modules, test incrementally. Use `preload_file` to load a file's imports into the session automatically. Use `env` parameter for FFI library paths.
### For Building and Testing
- **`gerbil_build_project`**: Compile or clean a project directory using gxpkg.
- **`gerbil_build_and_report`**: Run `gerbil build` with structured diagnostics (file, line, column). Auto-detects `GERBIL_LOADPATH` from `gerbil.pkg`. Auto-retries on lock errors or missing exe C files. Detects missing C headers. Use `modules_only: true` to skip exe targets (faster iteration). Use `loadpath` to override.
- **`gerbil_build_conflict_check`**: Detect when multiple gerbil build processes are running on the same project directory. Checks for running processes via ps, lock files in .gerbil/, and matching working directories. Warns about potential conflicts with suggestions to kill old builds.
- **`gerbil_build_progress`**: Monitor build output from a background task. Shows current phase (compile/link/install/clean), modules compiled, errors, warnings, and whether the build is still running. Pass `output_file` for background task output or `build_output` for direct text.
- **`gerbil_check_c_library`**: Check if C libraries from build.ss `-lXXX` flags are installed (pkg-config/ldconfig). Reports missing with apt install suggestions. Accepts `project_path`, `build_file`, or `libraries`.
- **`gerbil_build_chain`**: Build dependent projects in dependency order (reads `gerbil.pkg` + Makefile LOADPATH). Checks if upstream needs rebuilding. Use `dry_run: true` to preview.
- **`gerbil_run_tests`**: Execute a single `:std/test` file (`file_path`) or project-wide tests (`directory`). Options: `filter` (match test names), `quiet` (errors-only), `clean_stale` (remove stale artifacts), `verbose` (trace check expressions with line numbers), `env` (FFI library paths). Auto-detects `GERBIL_LOADPATH` from `gerbil.pkg`.
- **`gerbil_dispatch_coverage_analysis`**: Find command interaction coverage gaps in test files. Identifies commands tested individually but never in combination.
- **`gerbil_package_info`**: List installed packages, search the package directory, or view metadata.
- **`gerbil_package_manage`**: Install, update, or uninstall Gerbil packages. Automatically defaults to `$HOME` as working directory when in a project directory (with `gerbil.pkg`) to prevent destructive operations on local package context.
- **`gerbil_scaffold`**: Create a new Gerbil project from a template using gxpkg new.
- **`gerbil_stale_static`**: Compare compiled artifacts in global `$GERBIL_PATH/lib/static/` vs project-local `.gerbil/lib/static/` to detect stale global copies that could shadow the current build. Common cause of segfaults and `#!unbound` errors in compiled executables.
- **`gerbil_stale_linked_pkg`**: Detect stale linked packages (via `gerbil pkg link`) whose source `.ss` files are newer than compiled `.ssi`/`.scm` artifacts. Reports which packages need rebuilding with `gerbil pkg build`.
- **`gerbil_build_linkage_diagnostic`**: Trace transitive FFI link deps in `build.ss` exe targets. Catches missing `-L`/`-l` flags that cause broken binaries. Use `exe_target` to check a specific target.
- **`gerbil_qt_test_runner`**: Build and run a Qt FFI test executable in one step. Handles build, patchelf rpath, and QT_QPA_PLATFORM=offscreen automatically. Use `skip_build` to rerun without rebuilding. Use `rpath` to override auto-detected rpath values.
- **`gerbil_pkg_link_sync`**: Detect and sync stale linked-package artifacts (.ssi, .so, .scm) between a package's local build and global ~/.gerbil/lib/. Dry-run by default. Use `sync: true` to copy stale artifacts. Complements `gerbil_stale_linked_pkg` with actual sync capability.
- **`gerbil_make`**: Run Makefile targets in a Gerbil project directory. Useful for projects that use `make build` instead of `gerbil build` directly.
- **`gerbil_check_arity`**: Detect functions called with the wrong number of arguments across a project. Compares call sites against known arities from local definitions and standard library introspection.
- **`gerbil_check_test_arity`**: Scan `*-test.ss` files for calls to a specific function and check if call-site arities match the function's signature. Useful when changing a function's parameters to find affected tests.
- **`gerbil_signature_impact`**: Pre-signature-change impact report — finds all call sites (source + tests) in one call. Use `new_arity` to preview breaking changes.
- **`gerbil_test_assertion_audit`**: Detect :std/test assertion mistakes that silently pass (`check ? #f`, `check ? values`, type mismatches, missing operators). Scans file or directory.
### For Performance Analysis
- **`gerbil_profile`**: Instrument specific functions with call counting and timing. Reports per-function stats (calls, time, avg, %) plus overall wall/CPU/GC time and allocation.
- **`gerbil_heap_profile`**: Capture GC heap metrics before/after an expression. Reports heap size, allocation, live/movable/still objects with deltas.
- **`gerbil_trace_calls`**: Lightweight call counting (no timing overhead). Count how many times specified functions are called.
- **`gerbil_benchmark_compare`**: Run benchmarks, save as named baseline (`save_as`), compare with previous runs (`compare_with`). Shows percentage changes.
### For Code Quality
- **`gerbil_lint`**: Static analysis: unused imports, duplicate defs, shadowed bindings, hash literal keys, channel anti-patterns, missing exports (re-export aware), port-type mismatches, pregexp inline flags, macro suggestions, and compilation errors.
- **`gerbil_diagnostics`**: Run `gxc -S` on a file or project and get structured diagnostics with file, line, column, severity, and message. Use `loadpath` to resolve project-local module imports.
- **`gerbil_check_exports`**: Cross-module export/import consistency checker. Detects symbols exported but not defined, and cross-module import mismatches across a project.
- **`gerbil_check_import_conflicts`**: Detect import conflicts before build. Finds local-def vs import conflicts, cross-import collisions, and cross-module export collisions. Suggests `(only-in)`/`(except-in)` fixes. Supports `project_path` for batch checking.
- **`gerbil_dead_code`**: Detect unexported, uncalled definitions across a project. Finds functions/values that are defined but never referenced from other files and not exported.
- **`gerbil_dependency_cycles`**: Detect circular module dependencies in a project using DFS cycle detection. Reports all unique cycles found.
- **`gerbil_migration_check`**: Scan Gerbil source files for v0.18 → v0.19 migration issues. Detects deprecated patterns (e.g. `define` → `def`, `hash-ref` → `hash-get`, getopt module rename) with severity levels and suggested fixes.
- **`gerbil_diff_modules`**: Compare exports between two modules, showing added, removed, and shared symbols. Useful for understanding API differences between module versions.
- **`gerbil_cross_package_diff`**: Compare function signatures (arity, kind) between two Gerbil modules from potentially different packages. Shows symbols only in each module and shared symbols with different arities. Critical for debugging wrapper/wrapped function mismatches (e.g. a shim with different parameter defaults). Use `show_shared: true` to also show matching signatures.
- **`gerbil_format`**: Pretty-print Gerbil expressions using Gambit's pretty-print.
- **`gerbil_benchmark`**: Measure wall-clock time, CPU time, GC stats, and memory allocation.
- **`gerbil_tail_position_check`**: Analyze whether recursive calls in a function are in tail position. Detects non-tail calls wrapped in forms like `+`, `cons`, `let`.
- **`gerbil_return_type_analysis`**: Detect gotcha return values: `hash-ref` returning `#!void`, `when`/`unless` returning `#<void>`, and other common Gerbil return value pitfalls.
- **`gerbil_method_dispatch_audit`**: Detect `{method-name obj}` dispatch calls and cross-reference with `defmethod` declarations to find potential dispatch mismatches.
- **`gerbil_macro_hygiene_check`**: Detect free variable capture in `defrule`/`defsyntax` macro definitions — a common source of subtle bugs.
- **`gerbil_interface_compliance_check`**: Verify that struct/class types implement all required interface methods by cross-referencing type definitions with interface declarations.
- **`gerbil_concurrent_plan_validate`**: Validate DAG-based execution plans (step dependencies). Detects circular dependencies, missing steps, and unreachable steps.
- **`gerbil_project_health_check`**: Composite project audit that runs lint, dead code detection, dependency cycle checking, and export consistency in a single call.
- **`gerbil_check_duplicates`**: Fast pre-build check for duplicate top-level defs. Catches "Bad binding; rebind conflict" before compilation. No subprocess.
- **`gerbil_verify`**: Combined syntax + compile + lint + arity + duplicate check in one pass. Returns unified issue list. Skips syntax for FFI code to avoid false errors.
- **`gerbil_cross_module_check`**: Detect cross-module unbound symbols before compilation. Catches all unbound identifier errors in one pass — invaluable when splitting modules. Use `files` to limit scope.
- **`gerbil_pattern_cache_check`**: Detect regex compilation anti-patterns (pregexp in loops, dynamic pattern building, duplicate patterns). Suggests hoisting to module level.
- **`gerbil_sigchld_check`**: Detect SIGCHLD/process-status incompatibility (`add-signal-handler!` blocks SIGCHLD, causing `process-status` to hang). Suggests FFI waitpid polling.
### For Security Auditing
- **`gerbil_security_scan`**: Static security scanner for `.ss` and C files. Detects shell injection, FFI type mismatches, missing `unwind-protect`, unsafe C patterns, and more. Reports severity, line, and remediation. Scans single file (`file_path`) or project (`project_path`). Filter by `severity_threshold`. Supports inline suppression: `; gerbil-security: suppress <rule-id>`.
- **`gerbil_security_pattern_add`**: Add custom security detection rules. Requires `id`, `title`, `severity`, `scope`, `pattern` (regex), `message`, and `remediation`. Update semantics (replaces existing same-id rules).
### For Macro Development and Refactoring
- **`gerbil_macro_pattern_detector`**: Analyze Gerbil source files for repetitive code patterns that could be replaced with macros. Detects: (1) repeated function definitions with similar structure, (2) repeated hash-ref accessors, (3) repeated method wrappers. For each pattern, suggests a macro definition and shows potential code size reduction.
- **`gerbil_boilerplate_converter`**: Convert repetitive code blocks into macro definitions automatically. Given 2+ similar Scheme expressions, extracts the common pattern and generates a `defrule` macro with appropriate pattern variables. Returns both the macro definition and replacement invocations, showing code reduction.
- **`gerbil_signal_trace`**: Generate Gerbil code for debugging signal handling. Creates an instrumentation module that logs when signals are received, when handlers execute, and whether exceptions occur. Outputs timestamped trace log. Useful for debugging unresponsive CTRL-C, trap execution failures, or process hangs.
- **`gerbil_macro_expansion_size`**: Analyze macro expansion size to detect accidentally explosive macros. Expands a macro invocation and compares the number of forms/tokens in the source vs expanded output. Reports expansion ratio and warning level (ok/large/explosive). Helps catch macros that expand recursively, generate more code than expected, or should be functions instead.
- **`gerbil_macro_template_library`**: Generate reusable macro templates for common patterns. Supports: hash-accessors, method-delegation, validation-guards, enum-constants, event-handlers, type-setters. Returns working `defrule` definitions with example invocations and expansions, customized with project-specific naming. Ready to copy into your project.
### For Navigation and Discovery
- **`gerbil_document_symbols`**: List all definitions in a file with name, kind, and line number.
- **`gerbil_workspace_symbols`**: Search for symbol definitions across all `.ss` files in a project directory.
- **`gerbil_find_callers`**: Find all files in a directory that reference a given symbol, with line numbers.
- **`gerbil_suggest_imports`**: Discover which standard library module exports a given symbol.
- **`gerbil_call_graph`**: Static call graph analysis — see which functions call which in a source file.
- **`gerbil_check_balance`**: Fast paren/bracket/brace balance checking without spawning a subprocess. Handles `#!` reader directives and suggests cross-checking with `gerbil_read_forms` on errors.
- **`gerbil_read_forms`**: Read a file with the actual Gerbil reader and see each form's line range and summary.
- **`gerbil_version`**: Check Gerbil/Gambit versions, installation path, and system type.
- **`gerbil_preflight_check`**: Diagnostic tool that verifies MCP server prerequisites and Gerbil environment health. Checks gxi/gxc/gerbil availability, Gerbil version, `GERBIL_HOME`/`GERBIL_PATH`, basic eval functionality, and optionally checks a TypeScript MCP server project (dist/, node_modules). Use when tools are not working or to verify the environment.
### For Refactoring and Code Generation
- **`gerbil_rename_symbol`**: Rename a symbol across all `.ss` files in a project directory or in a single file. Uses word-boundary detection to avoid partial matches. Dry-run by default. Use `file_path` for single-file local renames.
- **`gerbil_generate_module_stub`**: Generate a module skeleton matching another module's exported signatures.
- **`gerbil_generate_module`**: Create new modules by applying word-boundary-aware substitutions to a template file. Useful for mechanical variations of an existing module pattern.
- **`gerbil_scaffold_test`**: Generate a `:std/test` skeleton from a module's exports.
- **`gerbil_balanced_replace`**: Like Edit/string-replace but validates delimiter balance before and after. Rejects edits that would break balance, but tolerates matching imbalance where old and new fragments have the same net delimiter change. Dry-run by default.
- **`gerbil_wrap_form`**: Wrap lines in a new Scheme form (e.g. `when`, `let`, `begin`) with guaranteed matching parentheses. Auto-detects form boundaries when `end_line` is omitted. Dry-run by default.
- **`gerbil_splice_form`**: Remove a wrapper form while keeping selected children (inverse of wrap). Child indices are 1-based. Default: keep all children except the head. Dry-run by default.
- **`gerbil_generate_api_docs`**: Generate markdown API documentation from a module's exports. Introspects procedures (with arities), macros, and values to produce a complete API reference.
- **`gerbil_httpd_handler_scaffold`**: Generate HTTP server code from route specifications. Produces handler functions, routing setup, and middleware patterns for `:std/net/httpd`.
- **`gerbil_parser_grammar_scaffold`**: Generate `deflexer`/`defparser` skeleton from token and rule specifications for `:std/parser`.
- **`gerbil_actor_ensemble_scaffold`**: Generate distributed actor project template with multiple actor types, message protocols, and supervision trees.
- **`gerbil_test_fixture_gen`**: Generate mock modules, factory functions, and `parameterize`-based test setup/teardown patterns for `:std/test`.
- **`gerbil_db_pattern_scaffold`**: Generate database CRUD patterns with connection pooling for SQLite (`:std/db/sqlite`) or PostgreSQL (`:std/db/postgresql`).
- **`gerbil_graceful_shutdown_scaffold`**: Generate signal handling and cleanup patterns with optional actor system integration.
- **`gerbil_translate_scheme`**: Translate R7RS or Racket code to idiomatic Gerbil (~40 rules: syntax transforms, function renames, import mapping, exception handling). Returns translated code plus semantic warnings.
- **`gerbil_project_template`**: Generate a complete Gerbil project from 8 templates (cli, http-api, library, actor-service, db-crud, parser, ffi-wrapper, test-project). Creates gerbil.pkg, build.ss, Makefile, source modules, and test files.
- **`gerbil_resolve_imports`**: Analyze a Gerbil source file for unbound identifiers and generate a suggested import block. Useful when creating new modules or splitting existing ones — automatically discovers which standard library modules export the symbols you need.
### For Project Context
- **`gerbil_project_info`**: Single-call project summary: package name, build targets, source files, and external dependencies.
- **`gerbil_project_map`**: Complete view of all modules with their exports, definitions by kind, and import dependencies.
- **`gerbil_project_dep_graph`**: Visualize project module dependency graph as an ASCII tree. Shows which project modules import from which others. External dependencies listed separately.
- **`gerbil_test_coverage`**: Compare a module's exports against its test file to identify untested symbols. Auto-discovers `*-test.ss` files. Reports coverage percentage.
- **`gerbil_module_catalog`**: Compact reference of all exports from a module with kind, arity, and brief descriptions. Has curated descriptions for `:std/sugar`, `:std/iter`. Replaces multiple `gerbil_doc` calls.
- **`gerbil_example_api_coverage`**: Check which module exports are referenced in example/doc files. Scans a directory of `.ss` files and reports per-export coverage with file references and overall coverage percentage.
- **`gerbil_validate_example_imports`**: Validate that imported modules actually export the symbols used in a Gerbil source file. Hybrid static+runtime analysis that detects symbols used but not available from any import or local definition.
- **`gerbil_module_quickstart`**: Generate a working example file that exercises a module's main exports. Introspects exports, arities, and types, then produces a runnable `.ss` file. Useful for undocumented stdlib modules.
- **`gerbil_dynamic_reference`**: Auto-generate reference documentation for any Gerbil module on demand. Introspects all exports, classifies them (procedure/macro/value/type), and formats as markdown. Not limited to hardcoded reference docs.
- **`gerbil_event_system_guide`**: Interactive guide for `:std/event` patterns (sync, select, choice, wrap, handle, timeout, channels). Topic-based exploration with live module introspection.
### For Recipes and Idioms
- **`gerbil_howto`**: Search curated Gerbil idioms by keyword with synonym expansion and fuzzy matching. Returns verified, working examples with correct imports. Use **before writing Gerbil code**. Example queries: `"json parse"`, `"hash iterate"`, `"channel thread"`. Use `compact: true` then `gerbil_howto_get` by id to save tokens.
- **`gerbil_howto_get`**: Fetch a single cookbook recipe by its ID. Returns the full recipe with code, imports, notes, and related recipes. Use after `gerbil_howto` with `compact: true` to retrieve only the recipes you need.
- **`gerbil_howto_add`**: Save recipes to the server's cookbook (available across all sessions/projects). Requires `id`, `title`, `tags`, `imports`, `code`. Optional: `notes`, `related`, `supersedes` (deprecates old recipe), `valid_for` (version strings). Same-id replaces existing.
- **`gerbil_howto_run`**: Compile-check and optionally execute a cookbook recipe by ID. Validates that the recipe's code and imports produce valid Gerbil before running. Reports PASS/FAIL with output.
- **`gerbil_howto_verify`**: Batch-verify cookbook recipes for syntax and optionally compilation validity. Use to maintain cookbook quality.
- **`gerbil_error_fix_add`**: Add new error→fix mappings to the error fix database. Each entry needs an `id`, `pattern` (regex), `message`, `explanation`, `fix`, and optional `related_recipe`.
- **`gerbil_file_summary`**: Quick structural overview of a `.ss` file — imports, exports, and definitions grouped by kind — without reading the entire file. Faster than `gerbil_load_file` when you only need the shape of a module.
### For Feature Suggestions
- **`gerbil_list_features`**: Search or list existing feature suggestions for the gerbil-mcp toolset. Use before suggesting a new feature to check for duplicates. Shows vote counts for each feature. Use `gerbil_version` to filter by Gerbil version — excludes version-tagged features that don't match, while untagged features always pass through.
- **`gerbil_suggest_feature`**: Submit a feature suggestion. Requires `id`, `title`, `description`, `impact`, `tags`, `use_case`, `example_scenario`, `estimated_token_reduction`. Use `gerbil_version` for version-specific features.
- **`gerbil_vote_feature`**: Vote for an existing feature suggestion by ID. Use this when you encounter a situation where a suggested feature would have saved time or tokens. Votes help prioritize which features to implement next.
### Key Principle
**Never guess — always verify.** If you are unsure about any Gerbil API, symbol name, module export, function arity, or macro behavior, use the appropriate MCP tool to check before writing code. This is not optional — it is required practice for all Gerbil work in this repository.
---
## MANDATORY: Save What You Learn to the Gerbil Cookbook
Gerbil is niche with limited training data. When you discover a non-trivial working pattern (correct imports, arity workarounds, API conventions, gotchas), you MUST save it via `gerbil_howto_add`. Check `gerbil_howto` first for duplicates. Do NOT save trivial one-liners or project-specific logic.
Recipe format: kebab-case `id`, 4-6 `tags` (module name + task + alternative phrasings), all required `imports` (or `[]`), complete working `code` (copy-pasteable), and `notes` for gotchas.
---
## Save Discoveries: Skill and Hook
Two mechanisms save cookbook recipes AND feature suggestions in one pass:
- **`/save-discoveries` skill (manual)**: Install from gerbil-mcp's `.claude/skills/save-discoveries` directory (project or `~/.claude/skills/` for global). Invoke anytime to review the session, save patterns via `gerbil_howto_add`, and suggest tooling via `gerbil_suggest_feature`.
- **PreCompact hook (automatic)**: Add a `PreCompact` hook in `.claude/settings.json` with `type: "prompt"` (NOT `type: "agent"` — agent hooks don't work for PreCompact) that instructs Claude to save discoveries before context compaction. See the gerbil-mcp repo for the full hook configuration JSON.
---
## MANDATORY: Suggest Tooling Improvements
Call `gerbil_suggest_feature` when you notice missing tools, inefficient multi-call workflows, or missing parameters. Check `gerbil_list_features` first — vote with `gerbil_vote_feature` if a matching suggestion exists. Use kebab-case IDs, honest impact ratings, and specific `estimated_token_reduction`.
---
## Workflow Conventions
When implementing new features, always complete the documentation update in the same session. Document non-trivial solutions as howto recipes in the cookbook system.
### Common Workflows
- **Pre-build dependency check**: `gerbil_build_conflict_check` → `gerbil_check_c_library` → `gerbil_build_and_report`
## Language-Specific Notes
When editing Gerbil Scheme, be careful with function naming conventions (e.g., `md5` not `md5sum`) and avoid introducing duplicate definitions across modules.