agentleFS
alexk-devalexk-dev/golemcore-bot/CLAUDE.md

golemcore-bot

CLAUDE.md41 starsChanged 7 months agoApache-2.0View on GitHub

To run the app locally, configure provider API keys in preferences/runtime-config.json (recommended: via the dashboard at /dashboard). Common env vars (Spring) for local/Docker: Rule: new shared contracts must go into golemcore-bot-contracts, not into the app module. Use golemcore-bot-contracts for: - port interfaces - shared boundary/domain models used across modules - contract-style component interfaces - lightweight shared views Do not put controllers, adapters, Spring services, or tool implementations into golemcore-bot-contracts. Spring Boot 4.0.5, Java 25, Hexagonal Architecture (Ports & Adapters). Max…

  • Reads credentials

The file

Show its rules and text

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

15 rules. About 0 are common, 3 are distinctive, and 12 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.

  • 12

    Very specific

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

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

    Do not put controllers, adapters, Spring services, or tool implementations into golemcore-bot-contracts.

    line 33
  2. Distinctive:

    If a legacy key is removed, update tests to match the new contract.

    line 98
  3. Very specific:

    Use @Slf4j. Parametrized messages only, no string concatenation.

    line 152
  4. Very specific:

    No custom exception hierarchy — use standard exceptions (IllegalStateException, IllegalArgumentException)

    line 163
  5. Very specific:

    Use Optional for lookups, never return null from public methods

    line 164
  6. Distinctive:

    Always create a feature branch from main, commit there, and open a Pull Request.

    line 185
  7. Distinctive:

    Keep PR descriptions current as the branch evolves.

    line 193
  8. Very specific:

    Do not add a Verification section in PR description unless explicitly requested.

    line 195
  9. Very specific:

    Use module/area name: llm, telegram, tools, skills, mcp, auto, security, storage, loop, voice, webhook.

    line 228
  10. Very specific:

    Test class: *Test suffix

    line 255
  11. Very specific:

    Test method: shouldDoSomethingWhenCondition() — no test prefix

    line 256
  12. Very specific:

    Use @ParameterizedTest + @ValueSource for input validation

    line 261
  13. Very specific:

    All tools implement ToolComponent.

    line 303
  14. Very specific:

    Create class in tools/ implementing ToolComponent

    line 307
  15. Very specific:

    Add config flag bot.tools.<name>.enabled in application.properties

    line 309

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.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
CLAUDE.md

CLAUDE.md — GolemCore Bot

Build & Test

./mvnw clean package -DskipTests   # build all modules
./mvnw test                         # run tests
./mvnw clean verify -P strict       # full check (tests + PMD + SpotBugs)

To run the app locally, configure provider API keys in preferences/runtime-config.json (recommended: via the dashboard at /dashboard).

Common env vars (Spring) for local/Docker:

  • STORAGE_PATH (workspace base path)
  • TOOLS_WORKSPACE (sandbox for filesystem/shell tools)

Modules

  • golemcore-bot-contracts — shared contracts: ports, shared domain models, contract-style component interfaces, lightweight shared views.
  • golemcore-bot-app — runnable Spring Boot application and runtime implementation.

Rule: new shared contracts must go into golemcore-bot-contracts, not into the app module.

Use golemcore-bot-contracts for:

  • port interfaces
  • shared boundary/domain models used across modules
  • contract-style component interfaces
  • lightweight shared views

Do not put controllers, adapters, Spring services, or tool implementations into golemcore-bot-contracts.


Architecture

Spring Boot 4.0.5, Java 25, Hexagonal Architecture (Ports & Adapters).

Package Structure

me.golemcore.bot
├── adapter/inbound/          Telegram (TelegramAdapter, TelegramVoiceHandler), CommandRouter, Webhook (WebhookController)
├── adapter/outbound/         LLM, storage, browser, MCP, voice (ElevenLabsAdapter)
├── domain/component/         Interfaces: ToolComponent, SkillComponent, etc.
├── domain/loop/              AgentLoop, AgentContextHolder
├── domain/model/             AgentContext, AgentSession, Message, Skill, ToolDefinition, ContextAttributes, etc.
├── domain/service/           SessionService, SkillService, CompactionService, VoiceResponseHandler, etc.
├── domain/system/            Ordered pipeline systems (see below)
├── port/inbound/             ChannelPort, CommandPort
├── port/outbound/            LlmPort, StoragePort, BrowserPort, VoicePort, McpPort, SessionPort, RagPort, ConfirmationPort
├── security/                 InjectionGuard, InputSanitizer, AllowlistValidator
└── tools/                    FileSystemTool, ShellTool, BrowserTool, TierTool, VoiceResponseTool, etc.

Agent Loop Pipeline

OrderSystemPurpose
10InputSanitizationSystemSanitization, injection detection
18AutoCompactionSystemAuto-compact when context nears limit
20ContextBuildingSystemSystem prompt, memory, skills, tools, MCP, tier resolution
25DynamicTierSystemUpgrade model tier mid-conversation if needed
30ToolLoopExecutionSystemLLM calls, tool execution loop, plan intercept
50MemoryPersistSystemPersist memory
55SkillPipelineSystemAuto-transition between skills
55RagIndexingSystemIndex conversations for RAG
57TurnOutcomeFinalizationSystemBuild canonical TurnOutcome from domain state
58PlanFinalizationSystemPlan mode: detect plan completion, publish approval event
58OutgoingResponsePreparationSystemPrepare OutgoingResponse from LLM results
59FeedbackGuaranteeSystemFallback OutgoingResponse if none produced upstream
60ResponseRoutingSystemSend response to channel

Max iterations: bot.agent.max-iterations=20.

Port/Adapter Boundaries

Domain code (domain/) depends only on port interfaces (port/). Never import adapter classes in domain code.

domain/ -> port/         OK
adapter/ -> port/        OK
adapter/ -> domain/      OK (models and services only)
domain/ -> adapter/      PROHIBITED

Coding Rules

Pipeline Flags & Cross-System Contracts

  • Rule: Any value used as a contract between pipeline systems/tools (i.e. read/written by more than one component) must be represented as a canonical key in ContextAttributes.
  • No ad-hoc string keys inside individual *System/*Tool classes.
  • Typed fields / accessors in AgentContext are allowed for ergonomics, but they must remain consistent with the canonical ContextAttributes contract when that contract is used downstream.
  • If a legacy key is removed, update tests to match the new contract. Tests should assert observable behavior / contracts, not internal implementation details.

Java Style

  • No var — always declare types explicitly
  • No wildcard imports — use explicit imports (import java.util.List, not import java.util.*)
  • No @Autowired — constructor injection only via @RequiredArgsConstructor + private final fields
  • No @Lazy — masks circular dependency problems; break cycles architecturally (see below)
  • No @ConditionalOnProperty — all beans always exist, use isEnabled() for runtime checks
  • Static imports allowed in tests only

Class Organization

@Service
@RequiredArgsConstructor
@Slf4j
public class ExampleService {
    // 1. Static constants
    private static final String DIR_NAME = "examples";
    // 2. Injected dependencies (private final)
    private final StoragePort storagePort;
    // 3. Mutable state (caches, registries)
    private final Map<String, Item> cache = new ConcurrentHashMap<>();
    // 4. @PostConstruct
    // 5. Public interface methods (@Override)
    // 6. Public methods
    // 7. Private methods
}

Naming

SuffixLayerExample
*ServiceDomain servicesSessionService
*SystemPipeline systemsToolLoopExecutionSystem
*ToolTool implementationsFileSystemTool
*AdapterOutbound adaptersLangchain4jAdapter
*PortPort interfacesLlmPort, StoragePort
*ComponentComponent interfacesToolComponent

Methods: get* (throw if missing), find* (return Optional), is*/has* (boolean), create*/build* (factory), process (pipeline), execute (action).

Lombok

  • @RequiredArgsConstructor on services/adapters/systems/tools for injection
  • @Slf4j on any class that logs
  • @Data on model POJOs, @Builder on request/response objects
  • @NoArgsConstructor + @AllArgsConstructor on Jackson-deserialized models
  • Gotcha: computed getters in @Data classes get serialized by Jackson — mark them @JsonIgnore

Logging

Use @Slf4j. Parametrized messages only, no string concatenation.

log.info("[MCP] Starting server for skill: {}", skillName);    // OK
log.info("Starting server for " + skillName);                   // PROHIBITED

Levels: error (failures + exception), warn (recoverable), info (milestones), debug (internal flow), trace (raw content).

Error Handling

  • No custom exception hierarchy — use standard exceptions (IllegalStateException, IllegalArgumentException)
  • Use Optional for lookups, never return null from public methods
  • Catch broadly in I/O layers with // NOSONAR comment for intentional broad catches

Spring Stereotypes

  • @Service — domain services
  • @Component — adapters, tools, infrastructure
  • @Configuration — config classes; @Bean methods with injected fields must be static

Circular Dependencies

No @Lazy — it masks architectural problems. Break cycles by:

  1. Extracting a shared interface/service that both sides depend on
  2. Using Spring's ApplicationEventPublisher for one-way notifications
  3. Moving the dependency into a method parameter instead of a constructor field

Git Workflow

  • Direct commits/pushes to main are prohibited.
  • Always create a feature branch from main, commit there, and open a Pull Request.
  • Merge to main only through PR after required checks pass.
  • PR description must use the established structured format:
    1. ## Summary — concise bullet list of the user-facing and architectural changes.
    2. ## Architecture — code block showing the main call chain or component flow.
    3. ### Key design decisions — bullets explaining why the chosen design fits the codebase.
    4. ### Files changed — Markdown table with columns Area, Files, and What.
    5. ### Configuration (...) — JSON examples for new or changed runtime config sections when applicable.
  • Keep PR descriptions current as the branch evolves. When updating an existing PR body, preserve this structure and tone instead of replacing it with a different template.
  • PR descriptions should call out compatibility behavior, feature flags/runtime toggles, observability/tracing impact, dashboard/API surface changes, and test coverage when those areas are touched.
  • Do not add a Verification section in PR description unless explicitly requested.

Commit Messages

Follow Conventional Commits 1.0.0.

Format

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

Types

TypeWhen to use
featNew feature or capability
fixBug fix
refactorCode change that neither fixes a bug nor adds a feature
testAdding or updating tests
docsDocumentation only
choreBuild config, CI, dependencies, tooling
perfPerformance improvement
styleFormatting, whitespace (no logic change)

Scope

Use module/area name: llm, telegram, tools, skills, mcp, auto, security, storage, loop, voice, webhook.

Rules

  • Imperative mood: "add feature", not "added feature"
  • Subject line under 72 characters, no period at end
  • Breaking changes: append ! after type/scope AND add BREAKING CHANGE: footer

Examples

feat(tools): add BrowserTool screenshot mode
fix(llm): handle empty response from Anthropic API
refactor(llm): extract tier resolution from ContextBuildingSystem
test(mcp): add McpClient lifecycle tests
chore: upgrade langchain4j to 1.11.0
feat(skills)!: rename nextSkill field to next_skill in YAML frontmatter

BREAKING CHANGE: skill YAML files must use next_skill instead of nextSkill.

Testing

Tests mirror main source structure.

  • Test class: *Test suffix
  • Test method: shouldDoSomethingWhenCondition() — no test prefix
  • Pattern: Arrange-Act-Assert
  • Mocking: Mockito, create mocks in @BeforeEach
  • Unit tests must not use real network/socket connections; for OkHttp-based adapters use in-memory test doubles (e.g. src/test/java/me/golemcore/bot/testsupport/http/OkHttpMockEngine.java)
  • For varargs mocks, use custom Answer on mock creation (not when().thenAnswer())
  • Use @ParameterizedTest + @ValueSource for input validation
@Test
void shouldRejectPathTraversalAttempt() {
    // Arrange
    Map<String, Object> params = Map.of("path", "../../../etc/passwd");
    // Act
    ToolResult result = tool.execute(params).join();
    // Assert
    assertTrue(result.getError().contains("traversal"));
}

Key Patterns

AgentContext

Uses @Builder only (no no-arg constructor):

AgentContext context = AgentContext.builder()
        .session(session).messages(messages)
        .channel(channelPort).chatId("123")
        .build();

AgentSession

Field is chatId (not channelId).

ToolDefinition

Field is inputSchema (not parameters).

ToolResult

ToolResult.success(output) stores in output field. ToolResult.failure(error) stores in error field.

Tools

All tools implement ToolComponent. Tools using AgentContextHolder (ThreadLocal) must NOT use CompletableFuture.supplyAsync() — ThreadLocal not propagated to ForkJoinPool.

Adding a New Tool

  1. Create class in tools/ implementing ToolComponent
  2. Implement getDefinition() (JSON Schema), execute(), isEnabled()
  3. Add config flag bot.tools.<name>.enabled in application.properties

Adding a New System

  1. Implement AgentSystem in domain/system/
  2. Set @Order(N) to control pipeline position
  3. Implement process(AgentContext), shouldProcess(), isEnabled()

Storage

Local filesystem only. StoragePort uses "directory" and "path" terminology. Base path: ${user.home}/.golemcore/workspace. Directories: sessions/, memory/, skills/, usage/, preferences/.

MCP Client

Lightweight MCP over stdio (Jackson + ProcessBuilder, JSON-RPC 2.0). McpPort outbound port interface. McpClientManager manages pool of McpClient by skill name with idle timeout. McpToolAdapter (NOT a Spring bean) wraps MCP tools as ToolComponent.

Skill frontmatter:

mcp:
  command: npx -y @modelcontextprotocol/server-github
  env:
    GITHUB_PERSONAL_ACCESS_TOKEN: ${GITHUB_TOKEN}
  startup_timeout: 30
  idle_timeout: 10

Voice

ElevenLabs for STT + TTS. Voice prefix mechanism: LLM starts response with 🔊 -> ResponseRoutingSystem detects, strips prefix, synthesizes TTS, sends voice. Falls back to text on failure.

API Documentation:

Error Handling: Handles 401 (auth), 429 (rate limit), 500/503 (server errors), network errors. See ElevenLabsAdapter for implementation.

Webhooks

Inbound HTTP webhooks (OpenClaw-style, WebFlux). Three endpoint types: /api/hooks/wake (fire-and-forget, 200), /api/hooks/agent (full agent turn, 202), /api/hooks/{name} (custom mapped). Configuration stored in UserPreferences.WebhookConfig (not application.properties).

Components:

  • WebhookController — REST endpoints (Mono<ResponseEntity<WebhookResponse>>)
  • WebhookAuthenticator — Bearer token + HMAC-SHA256 with constant-time comparison
  • WebhookChannelAdapter — ChannelPort implementation, captures responses, sends callbacks
  • WebhookCallbackSender — Reactive WebClient POST with exponential backoff retry
  • WebhookPayloadTransformer — {field.path} placeholder resolution from JSON

Message flow: WebhookController → ApplicationEventPublisher → InboundMessageEvent → SessionRunCoordinator → AgentLoop pipeline. External payloads wrapped with [EXTERNAL WEBHOOK DATA] safety markers.

See docs/WEBHOOKS.md for the full guide.

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.