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
In this repository5 other files it gives its agents.
- AGENTS.mdAGENTS.md
- dashboard/CLAUDE.mdCLAUDE.md
- golemcore-bot-app/CLAUDE.mdCLAUDE.md
- golemcore-bot-client/CLAUDE.mdCLAUDE.md
- golemcore-bot-contracts/CLAUDE.mdCLAUDE.md
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
- Very specific: line 33
Do not put controllers, adapters, Spring services, or tool implementations into golemcore-bot-contracts.
- Distinctive: line 98
If a legacy key is removed, update tests to match the new contract.
- Very specific: line 152
Use @Slf4j. Parametrized messages only, no string concatenation.
- Very specific: line 163
No custom exception hierarchy — use standard exceptions (IllegalStateException, IllegalArgumentException)
- Very specific: line 164
Use Optional for lookups, never return null from public methods
- Distinctive: line 185
Always create a feature branch from main, commit there, and open a Pull Request.
- Distinctive: line 193
Keep PR descriptions current as the branch evolves.
- Very specific: line 195
Do not add a Verification section in PR description unless explicitly requested.
- Very specific: line 228
Use module/area name: llm, telegram, tools, skills, mcp, auto, security, storage, loop, voice, webhook.
- Very specific: line 255
Test class: *Test suffix
- Very specific: line 256
Test method: shouldDoSomethingWhenCondition() — no test prefix
- Very specific: line 261
Use @ParameterizedTest + @ValueSource for input validation
- Very specific: line 303
All tools implement ToolComponent.
- Very specific: line 307
Create class in tools/ implementing ToolComponent
- Very specific: line 309
Add config flag bot.tools.<name>.enabled in application.properties
≈ “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.
Files
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
| Order | System | Purpose |
| 10 | InputSanitizationSystem | Sanitization, injection detection |
| 18 | AutoCompactionSystem | Auto-compact when context nears limit |
| 20 | ContextBuildingSystem | System prompt, memory, skills, tools, MCP, tier resolution |
| 25 | DynamicTierSystem | Upgrade model tier mid-conversation if needed |
| 30 | ToolLoopExecutionSystem | LLM calls, tool execution loop, plan intercept |
| 50 | MemoryPersistSystem | Persist memory |
| 55 | SkillPipelineSystem | Auto-transition between skills |
| 55 | RagIndexingSystem | Index conversations for RAG |
| 57 | TurnOutcomeFinalizationSystem | Build canonical TurnOutcome from domain state |
| 58 | PlanFinalizationSystem | Plan mode: detect plan completion, publish approval event |
| 58 | OutgoingResponsePreparationSystem | Prepare OutgoingResponse from LLM results |
| 59 | FeedbackGuaranteeSystem | Fallback OutgoingResponse if none produced upstream |
| 60 | ResponseRoutingSystem | Send 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/ PROHIBITEDCoding 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/*Toolclasses. - Typed fields / accessors in
AgentContextare allowed for ergonomics, but they must remain consistent with the canonicalContextAttributescontract 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, notimport java.util.*) - No
@Autowired— constructor injection only via@RequiredArgsConstructor+private finalfields - No
@Lazy— masks circular dependency problems; break cycles architecturally (see below) - No
@ConditionalOnProperty— all beans always exist, useisEnabled()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
| Suffix | Layer | Example |
*Service | Domain services | SessionService |
*System | Pipeline systems | ToolLoopExecutionSystem |
*Tool | Tool implementations | FileSystemTool |
*Adapter | Outbound adapters | Langchain4jAdapter |
*Port | Port interfaces | LlmPort, StoragePort |
*Component | Component interfaces | ToolComponent |
Methods: get* (throw if missing), find* (return Optional), is*/has* (boolean), create*/build* (factory), process (pipeline), execute (action).
Lombok
@RequiredArgsConstructoron services/adapters/systems/tools for injection@Slf4jon any class that logs@Dataon model POJOs,@Builderon request/response objects@NoArgsConstructor+@AllArgsConstructoron Jackson-deserialized models- Gotcha: computed getters in
@Dataclasses 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); // PROHIBITEDLevels: 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
Optionalfor lookups, never returnnullfrom public methods - Catch broadly in I/O layers with
// NOSONARcomment for intentional broad catches
Spring Stereotypes
@Service— domain services@Component— adapters, tools, infrastructure@Configuration— config classes;@Beanmethods with injected fields must bestatic
Circular Dependencies
No @Lazy — it masks architectural problems. Break cycles by:
- Extracting a shared interface/service that both sides depend on
- Using Spring's
ApplicationEventPublisherfor one-way notifications - Moving the dependency into a method parameter instead of a constructor field
Git Workflow
- Direct commits/pushes to
mainare prohibited. - Always create a feature branch from
main, commit there, and open a Pull Request. - Merge to
mainonly through PR after required checks pass. - PR description must use the established structured format:
## Summary— concise bullet list of the user-facing and architectural changes.## Architecture— code block showing the main call chain or component flow.### Key design decisions— bullets explaining why the chosen design fits the codebase.### Files changed— Markdown table with columnsArea,Files, andWhat.### 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
Verificationsection 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
| Type | When to use |
feat | New feature or capability |
fix | Bug fix |
refactor | Code change that neither fixes a bug nor adds a feature |
test | Adding or updating tests |
docs | Documentation only |
chore | Build config, CI, dependencies, tooling |
perf | Performance improvement |
style | Formatting, 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 addBREAKING 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:
*Testsuffix - Test method:
shouldDoSomethingWhenCondition()— notestprefix - 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
Answeron mock creation (notwhen().thenAnswer()) - Use
@ParameterizedTest+@ValueSourcefor 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
- Create class in
tools/implementingToolComponent - Implement
getDefinition()(JSON Schema),execute(),isEnabled() - Add config flag
bot.tools.<name>.enabledinapplication.properties
Adding a New System
- Implement
AgentSystemindomain/system/ - Set
@Order(N)to control pipeline position - 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: 10Voice
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:
- ElevenLabs API Reference
- Error Messages & Status Codes
- STT endpoint:
POST /v1/speech-to-text(model:scribe_v1) - TTS endpoint:
POST /v1/text-to-speech/{voice_id}
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 comparisonWebhookChannelAdapter—ChannelPortimplementation, captures responses, sends callbacksWebhookCallbackSender— ReactiveWebClientPOST with exponential backoff retryWebhookPayloadTransformer—{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.
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
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.

