Examples & Tutorials Interactive

Learn Automergent through real-world examples. Each tutorial shows the full interaction — from your input to the agent's reasoning and final output.

⭐ Quick Examples

These examples show common one-shot interactions — type a message, the agent figures out the rest.

Read a file and explain it Quick
U
You
Read main.go and explain what it does
A
Automergent
✓ Read main.go
✓ Analyzing structure and imports
✓ Generating explanation

main.go is the entry point for the application. It:

  1. Initializes a new CLI application using cobra
  2. Registers subcommands (serve, config, migrate)
  3. Loads configuration from ~/.automergent/config.yaml
  4. Starts an HTTP server on the configured port

The init() function sets up logging and telemetry before the main command runs.

"Explain the auth flow" "What does setup() do?" "Summarize cmd/server.go"
Find all TODO comments Quick
U
You
Find all TODO comments
A
Automergent
✓ Grep "TODO|FIXME|HACK" --include "*.{go,ts,js}"
✓ Found 7 results across 4 files
src/auth/middleware.go:24 // TODO: add rate limiting src/auth/middleware.go:51 // TODO: validate JWT expiry src/db/pool.go:12 // FIXME: connection pool leaks under load cmd/serve.go:38 // HACK: temp workaround for TLS cert tests/integration_test.go:89 // TODO: add test for edge case pkg/config/config.go:67 // TODO: support env var overrides web/handler.go:103 // TODO: implement WebSocket fallback

Summary: 7 items found. 4 TODOs, 1 FIXME, 1 HACK. The FIXME in db/pool.go:12 looks most urgent.

"Find all deprecated functions" "Show me all error handling" "List all functions in auth/"
Run tests and fix failures Quick
U
You
Run the tests and fix failures
A
Automergent
✓ Bash: go test ./... 2>&1
⟳ 2 tests failed — analyzing
3 Read auth_test.go:42-68
4 Edit auth_test.go — fix assertion
5 Bash: go test ./... 2>&1
--- FAIL: TestTokenValidation (0.00s) auth_test.go:55: expected error nil, got "token expired" --- FAIL: TestRefreshFlow (0.00s) auth_test.go:82: expected status 200, got 401

Diagnosis: Both failures trace to the same root cause — ValidateToken() now checks exp claims but the test tokens use a stale expiry. Fixing the test fixture timestamps.

✓ Edit auth_test.go:14-16 — update token fixture
✓ Bash: go test ./...
ok github.com/example/app 0.34s ok github.com/example/app/auth 0.12s ok github.com/example/app/db 0.08s

All 14 tests pass now. The issue was that the test fixture's JWT tokens expired in December 2025 — I updated them to use relative time offsets.

Variations: "Run the e2e tests", "Run tests in the auth package only", "Run tests and show coverage"
Refactor a function Quick
U
You
Refactor this function to be more readable
A
Automergent

Which function? I'll look at the current file context first.

✓ Read handler.go — analyzing parseRequest()
✓ Identified 3 refactoring opportunities

Here's my plan for refactoring parseRequest() (lines 45-92):

  1. Extract validation logic into a separate validatePayload() function
  2. Replace nested if-else with early returns
  3. Add named return values for clarity
✓ Edit handler.go — apply refactor
✓ Bash: go vet ./...
✓ Bash: go test -run TestParseRequest

Refactored. The function went from 47 lines with 4 nesting levels to 28 lines with max 2. All tests pass.

Tip: For larger refactors, the agent will propose a plan first. Say "proceed" to approve, or "adjust" to request changes.
Understand project architecture Quick
U
You
What's the architecture of this project?
A
Automergent
✓ Bash: ls -R
✓ Read go.mod, Makefile, docker-compose.yml
✓ Read cmd/ root files
✓ Analyzing patterns

Project: go-app — Go 1.22, module-based architecture

Directory Structure
├── cmd/           Entry points (one per binary)
│   ├── serve/
│   └── migrate/
├── internal/      Private packages
│   ├── auth/      JWT + middleware
│   ├── db/        PostgreSQL + migrations
│   └── handler/   HTTP handlers
├── pkg/           Public API packages
├── web/           Static assets + templates
├── migrations/    SQL migration files
└── deploy/        Docker + Kubernetes configs

This is a standard Go project layout following the golang-standards/project-layout conventions. Key patterns:

  • Clean Architecture: internal/ packages have no circular deps
  • Dependency injection: Constructor funcs in cmd/serve/main.go wire everything
  • Interface-driven: db.Repository interface lets handlers be tested with mocks
  • Graceful shutdown: Signal handling + context propagation
Tip: Ask follow-up questions like "How is auth handled?" or "Show me the request lifecycle" for deeper dives.

📩 Workflow: Code Review

A structured workflow for reviewing changes before merge.

Code review workflow Workflow
U
You
/review
A
Automergent
✓ Bash: git diff main...HEAD --stat
✓ Bash: git diff main...HEAD
✓ Reviewing 12 changed files

Reviewing branch: feature/user-settings (14 commits, +842 / -127)

✓ Correctness

All logic paths look sound. The settings update properly validates input before writing to the database.

⚠ Suggestions

settings.go:34 — The UpdateUserSettings function doesn't check if the user exists before updating. Add a GetUser call first to avoid silent no-ops.

handler.go:67 — Missing error context. fmt.Errorf("update failed") should wrap the underlying error with %w.

␒ Notes

  • Migration adds an index on user_settings.user_id — good, matches the query pattern
  • New tests are thorough — 94% coverage on changed files

Verdict: Minor issues only. Approved with the two fixes above.

🐛 Workflow: Bug Investigation

Methodically tracing a bug from symptom to root cause.

Bug investigation: "users can't log in" Workflow
U
You
Users report they can't log in after the latest deploy. Help me investigate.
A
Automergent
✓ Bash: git log --oneline -20
✓ Bash: git diff HEAD~5..HEAD --stat
✓ Grep "auth\|login\|token" --include "*.go"
✓ Read auth/handler.go
✓ Read auth/middleware.go

Investigation log:

1. Last 5 deploys touched auth/, db/, and config/

2. git diff HEAD~5..HEAD auth/ shows the middleware was changed to require exp claim validation

3. But the token signing code in auth/token.go:45 still uses time.Now().Add(24 * time.Hour) — this looks correct

4. Checking the config…

✓ Read config.yaml

Found it. The config change in deploy/config.yaml switched token_issuer from "app" to "App" (capitalized). The middleware validates iss claim case-sensitively, so all existing tokens are rejected.

Fix: Revert the issuer value to lowercase, or make the comparison case-insensitive.

Pattern: Explore → read relevant files → identify root cause → propose fix. The agent often finds issues in config, environment, or dependency changes before touching code.

✨ Workflow: Feature Implementation

Plan-driven feature development with approval gates.

Building a new feature with /plan Workflow
U
You
/plan Add a rate limiter middleware that supports per-user and per-IP limits
A
Automergent

Generating plan artifact…

Plan: rate-limiter (artifact)
## Rate Limiter Middleware

### Goal
Add configurable rate limiting to protect API endpoints.

### Steps
1. Create internal/ratelimit/limiter.go
   - Token bucket algorithm (using golang.org/x/time/rate)
   - Interfaces: PerUserLimiter, PerIPLimiter
   - In-memory store with cleanup goroutine

2. Create internal/ratelimit/middleware.go
   - Extract user ID from JWT or IP from RemoteAddr
   - Check rate, return 429 with Retry-After header

3. Add config fields to config.yaml
   - ratelimit.enabled: true
   - ratelimit.per_user: "100/m"
   - ratelimit.per_ip: "30/m"

4. Wire into cmd/serve/main.go

5. Add tests

### Risks
- In-memory store won't survive restarts (acceptable for MVP)
- No distributed rate limiting (add Redis later if needed)

### Files to create/modify
- Create: internal/ratelimit/limiter.go
- Create: internal/ratelimit/middleware.go
- Create: internal/ratelimit/limiter_test.go
- Modify: cmd/serve/main.go
- Modify: config/config.go
U
You
/artifact approve
A
Automergent
✓ Plan approved — starting implementation
✓ Write internal/ratelimit/limiter.go
✓ Write internal/ratelimit/middleware.go
✓ Edit cmd/serve/main.go — wire middleware
✓ Write internal/ratelimit/limiter_test.go
✓ Bash: go test ./internal/ratelimit/...

All 11 tests pass. The rate limiter is implemented with:

  • Per-user: 100 req/min (configurable)
  • Per-IP: 30 req/min (configurable)
  • Returns 429 Too Many Requests with Retry-After header

🔧 Workflow: Refactoring

Incremental refactoring Workflow
U
You
Refactor the database layer to use an interface so we can swap implementations
A
Automergent
✓ Grep "db\." --include "*.go" -l
✓ Read db/postgres.go, db/queries.go
✓ Analyzing all call sites

Current state: db.Store is a concrete struct used directly in 6 files. I'll extract an interface incrementally.

✓ Step 1: Define Repository interface in db/interface.go
✓ Step 2: Make Store implement the interface (it already does)
✓ Step 3: Update function signatures to accept Repository
✓ Step 4: Update call sites in handler/, auth/
✓ Step 5: Run tests — all 23 pass

Refactoring complete. Every function that used *db.Store now accepts db.Repository. You can now create a MockStore for testing or swap to a different backend.

🤖 Sub-agent Examples

Automergent can spawn sub-agents to work in parallel on different tasks.

Parallel exploration with 3 sub-agents Sub-agent
U
You
Launch 3 agents to analyze src/, tests/, and docs/
A
Automergent
✓ Spawning 3 sub-agents…
AgentScopeStatusResult
agent-1 src/ ✓ done 42 functions across 8 files. Core modules: api, auth, cache, db
agent-2 tests/ ✓ done 89 test functions. Coverage: 78%. Missing tests for cache layer
agent-3 docs/ ✓ done 3 markdown docs. API docs outdated (last updated 3 months ago)

Summary: The codebase is well-structured. Two action items: write cache layer tests and update API docs.

Security review sub-agent Sub-agent
U
You
Spawn a review agent to do a security analysis of the auth package
A
Automergent
✓ Spawning review agent targeting internal/auth/
✓ Sub-agent analyzing 6 files…

Security Review — internal/auth/

SeverityFindingFile
HIGH JWT secret read from env without length validation — weak secrets accepted token.go:18
MEDIUM Password comparison not constant-time (using == instead of subtle.ConstantTimeCompare) password.go:34
MEDIUM Session token not invalidated on password change handler.go:89
LOW Missing rate limit on /login endpoint handler.go:22

The sub-agent recommends fixing the HIGH and MEDIUM issues before the next release.

Background shell tasks Sub-agent
U
You
Start the dev server in the background, then help me with the UI
A
Automergent
✓ Bash: npm run dev & (background, PID 48291)
✓ Dev server running on http://localhost:3000

Dev server is running in the background. What do you need help with on the UI?

U
You
Fix the broken navbar on mobile — it doesn't collapse
A
Automergent
✓ Grep "navbar\|hamburger\|mobile" --include "*.css"
✓ Read src/components/Navbar.tsx
✓ Edit src/components/Navbar.tsx — fix toggle
✓ Hot-reload applied — check your browser

Fixed. The hamburger button was missing an onClick handler. Added the toggle state and a click listener. Your browser should have hot-reloaded.

Tip: Background processes stay alive across messages. The agent can interact with them, check logs, or kill them later.

⚙ Configuration Examples

Switching providers mid-session Config
U
You
Switch to claude-sonnet-4-20250514
A
Automergent
✓ Provider changed to anthropic/claude-sonnet-4-20250514

Switched. Next message will use Claude Sonnet.

U
You
Actually, switch back to gpt-4o
A
Automergent
✓ Provider changed to openai/gpt-4o

Back on GPT-4o.

Tip: You can also use /model to list available models and /provider to switch between OpenAI, Anthropic, and local providers.
Setting up MCP servers Config
U
You
Add a Postgres MCP server so I can query the database directly
A
Automergent
✓ Read config.yaml
✓ Edit config.yaml — add MCP server
config.yaml (updated)
# config.yaml
mcp:
  servers:
    postgres:
      transport: stdio
      command: "npx"
      args: ["-y", "@modelcontextprotocol/server-postgres"]
      env:
        DATABASE_URL: "${DATABASE_URL}"

Postgres MCP server added. You can now use tools like mcp__postgres__query to run SQL directly from the conversation.

Custom themes Config
U
You
Change the theme to something more colorful
A
Automergent

Available themes: modern, catppuccin, dracula, nord, gruvbox, onedark, tokyonight, solarized-dark, solarized-light, high-contrast, monokai

✓ Theme changed to dracula

Applied the Dracula theme. You should see the new colors immediately.

Memory management Config
U
You
Remember that this project uses pnpm, not npm
A
Automergent
✓ Saved to project memory: "Use pnpm, not npm"

Got it. I'll remember this and use pnpm for all package operations in this project.

U
You
What's in my project memory?
A
Automergent

Project Memory:

  • Use pnpm, not npm
  • Tests use vitest (not jest)
  • Branch naming: feat/*, fix/*, chore/*

📦 Context Management

Using /compact for long sessions Quick
U
You
/compact
A
Automergent
✓ Compacting context…
✓ Compressed 42 messages → summary (82% reduction)

Context state:

Before42 messages, ~12k tokens
AfterSummary + current, ~2.1k tokens
Freed~9.9k tokens

Session context compressed. I retain key decisions and file changes from our conversation.

Tip: Run /compact when context usage exceeds 80% or when the agent starts losing track of earlier decisions.
Monitoring context with /context Quick
U
You
/context
A
Automergent

Context Usage

Tokens used 18,420 / 200,000
9.2% used 181,580 remaining
Messages14
Tool calls8
Files read5
Files edited2
Adding external directories Quick
U
You
/add-dir ../shared-lib
A
Automergent
✓ Added ../shared-lib to context (12 files, 2.4k tokens)

Now I can read and reference files from ../shared-lib alongside the main project.

U
You
/context-files
A
Automergent

Files in context:

FileStatusTokens
src/handler.goedited~1.2k
src/auth/middleware.goread~0.8k
../shared-lib/types.goread~0.6k
../shared-lib/utils.goread~0.4k

📦 Git Integration

Committing with message hints Git
U
You
/commit add rate limiter middleware
A
Automergent
✓ Bash: git status
✓ Bash: git diff --stat
✓ Bash: git add internal/ratelimit/ cmd/serve/main.go
✓ Bash: git commit
Commit message
feat: add rate limiter middleware

Add per-user (100/min) and per-IP (30/min) rate limiting
using token bucket algorithm. Returns 429 with Retry-After
header when limits exceeded.

Co-authored-by: Automergent 

Committed: a3f7b2c

Working on GitHub issues Git
U
You
/issue 42
A
Automergent
✓ gh issue view 42

Issue #42: Database connection pool leaks under high concurrency

"Connections are not being returned to the pool after timeout. Memory grows over time."

Label: bug   Assignee: unassigned

✓ Read db/pool.go
✓ Found issue: missing conn.Close() in error path at line 67

I see the bug. In pool.go:67, when a query times out, the connection is never returned to the pool. The fix is to add a defer conn.Close() after acquiring the connection.

Addressing PR review feedback Git
U
You
/pr-comments 15
A
Automergent
✓ gh pr view 15 --comments
✓ 4 review comments, 3 resolved, 1 pending

Pending comment from @reviewer on handler.go:45:

"This should use the existing parseDuration() helper instead of reimplementing it."
✓ Grep "func parseDuration"
✓ Edit handler.go:45 — use parseDuration()

Fixed. Replaced the inline duration parsing with the shared helper. Ready to push.

📋 Advanced Usage

Plan mode for complex changes Advanced
U
You
/plan Migrate from REST to GraphQL
A
Automergent

This is a large change. Generating a comprehensive plan…

Plan: graphql-migration (artifact)
## GraphQL Migration Plan

### Phase 1: Setup (Day 1)
- Add graphql-go dependency
- Create schema file: schema.graphql
- Set up GraphQL handler at /graphql

### Phase 2: User Queries (Day 2)
- Implement User type and queries
- Map existing REST resolvers
- Add DataLoader for N+1 prevention

### Phase 3: Mutations (Day 3-4)
- Port POST/PUT/DELETE endpoints
- Add input validation
- Implement error formatting

### Phase 4: Migration (Day 5-6)
- Run REST and GraphQL in parallel
- Update client code incrementally
- Add feature flag for rollout

### Phase 5: Cleanup (Day 7)
- Remove REST endpoints
- Update documentation
- Remove unused middleware

### Estimated effort: 7 days
### Files affected: ~35 files

This is a significant migration. The plan has 5 phases over 7 days. Each phase can be approved independently.

Tip: Use /artifact approve phase-1 to approve one phase at a time. The agent will implement, test, and wait for your approval before moving to the next phase.
Goal-driven autonomy Advanced
U
You
Goal: Get the test coverage above 90% and fix all flaky tests
A
Automergent
✓ Bash: go test -coverprofile=cover.out ./... && go tool cover -func=cover.out | tail -1
✓ Current coverage: 78.3% (need +11.7%)
✓ Grep "FAIL\|flaky" --include "*_test.go"
✓ Found 3 flaky tests (race conditions in concurrent tests)

Plan to reach 90%:

  1. Fix 3 flaky tests (adds ~2% from skipped runs)
  2. Add tests for cache/ package (+5%)
  3. Add tests for handler/error.go (+3%)
  4. Add edge case tests for auth/ (+4%)

Starting implementation…

✓ Fixed race condition in TestConcurrentAccess
✓ Fixed flaky TestTimeout (was timing-dependent)
✓ Added 23 new tests across cache/, handler/, auth/
✓ Bash: go test -coverprofile=cover.out ./... && go tool cover -func=cover.out | tail -1
91.4% of statements with test coverage

Goal achieved. Coverage: 91.4%. All 47 tests pass, 0 flaky.

Custom workflows Advanced
U
You
/workflow create "pre-release" with steps: run tests, check coverage > 90%, build binary, verify no vulnerabilities
A
Automergent
✓ Workflow "pre-release" created with 4 steps

Run it anytime with /workflow run pre-release.

U
You
/workflow run pre-release
A
Automergent
✓ Step 1/4: Running tests… Passed (47/47)
✓ Step 2/4: Checking coverage… 91.4% ≥ 90%
✓ Step 3/4: Building binary… bin/release/v2.1.0
✓ Step 4/4: Checking vulnerabilities… 0 found
✓ pre-release workflow completed successfully
Skills and MCP integration Advanced
U
You
Create a custom skill for "deploy to staging" that runs tests, builds, and pushes to the staging branch
A
Automergent
✓ Write .automergent/skills/deploy-staging.md
.automergent/skills/deploy-staging.md
# Deploy to Staging

## Trigger
Use when the user says "deploy to staging" or "push staging".

## Steps
1. Run `pnpm test` — abort if any failures
2. Run `pnpm build` — abort if build fails
3. Create release branch: `git checkout -b staging/release-$(date +%Y%m%d)`
4. Commit changes with message from user or auto-generated
5. Push to origin: `git push -u origin staging/release-*`
6. Create PR targeting `staging` branch using `gh pr create`
7. Report PR URL to user

Skill created. Use it with /skill deploy-staging or just say "deploy to staging".

📋 Common Patterns

These are battle-tested patterns for getting the most out of Automergent.

PatternWhyExample
Read before edit Agent understands context before making changes "Read auth.go, then add rate limiting"
Grep before read Find the right file without guessing "Find where JWT validation happens"
Test after change Catch regressions immediately "Run tests after editing"
Use sub-agents for parallel work Explore multiple areas simultaneously "Launch 3 agents to analyze src/, tests/, docs/"
Monitor context with /context Prevent context overflow in long sessions "/context" after 15+ messages
Use /compact proactively Free up space before it's needed "/compact" at 60-70% usage
Plan first, then implement Get alignment before large changes "/plan Refactor the auth module"
Ask for options Agent will propose alternatives "How should I fix this? What are the options?"

Session Lifecycle

A typical well-structured session:

1 Explore — "Explore the project structure"
2 Understand — "How does auth work?"
3 Plan — /plan Add feature X
4 Implement — /artifact approve → agent builds
5 Verify — "Run tests"
6 Review — /review
7 Ship — /commit fix: description

Anti-patterns to Avoid

Don'tDo Instead
"Edit all 50 files" Edit one file at a time, or use a plan
Skipping /compact in long sessions Run /compact at 60% context usage
"Fix everything" (vague goal) Specific: "Fix the failing test in auth_test.go"
Editing without reading first Always let the agent read the file first
Not checking /context Monitor usage, compact when needed