feat: Phase 2 — chat templates, reasoning parser, collapsible TUI, mouse support

- internal/llama/template.go: ChatML/Llama3 template engine with stop tokens
- internal/agent/reasoning.go: parse <think>/<reasoning> tags from LLM output
- companion/promptbuilder.go: output structured BuildResult, add date/time context
- agent/agent.go: wire templates + reasoning split into message loop
- storage: add reasoning TEXT column to messages table + migration
- channel/tui.go: collapsible reasoning (tab toggle), mouse scroll, polished dimmed style
- config: CHAT_TEMPLATE env var (chatml|llama3|none)
- plan.md: mark Phase 2 complete, add themes TODO
This commit is contained in:
2026-06-10 09:42:45 +03:30
parent f57b42fd6e
commit 3895ca68c0
14 changed files with 327 additions and 144 deletions

117
AGENTS.md
View File

@@ -1,91 +1,60 @@
# AGENTS.md — DivaCode
## Quick start
## Commands
```bash
# build
make build # go build -o build/divad ./cmd/divad
make all # lint → vet → build
make build # go build -o build/divad ./cmd/divad
make run # build + run (needs llama.cpp on :8080)
make test # go test -race -count=1 ./...
make lint # golangci-lint run ./...
make vet # go vet ./...
make tidy # go mod tidy
make clean # rm -rf build/
```
# run (llama.cpp server must be on :8080)
make run # build + run
Private proxy for deps:
# verify
make vet # go vet ./...
GONOSUMDB=git.db123.ir GONOSUMCHECK=git.db123.ir GOPRIV=git.db123.ir GOPROXY=https://proxy.golang.org,direct go vet ./...
```bash
GONOSUMDB=git.db123.ir GONOSUMCHECK=git.db123.ir GOPRIV=git.db123.ir \
GOPROXY=https://proxy.golang.org,direct go vet ./...
```
## Architecture
```
cmd/divad/main.go # entrypoint: wires agent, llama, companion, TUI, API, scheduler
internal/agent/ # core loop: message → memory search → prompt → llama.cpp → save → respond
internal/agent/scheduler.go # autonomous tick: mood check, diary write, proactive message
internal/companion/ # orchestrates personality, relationship, reflection, mood, prompt builder
engine.go # BuildPrompt: assembles dynamic prompt from all sub-engines
personality.go # 5 bounded traits in SQLite (humor, curiosity, playfulness, formality, affection)
relationship.go # familiarity, trust, shared topics, inside jokes
reflection.go # diary entries, observations
promptbuilder.go # generates dynamic system prompt section
mood.go # mood derivation from recent interaction + energy level
internal/memory/ # RAG store + self-memory (promises, strategies, mistakes)
internal/llama/client.go # llama.cpp HTTP client (POST /completion, POST /embedding, GET /health)
internal/storage/ # SQLite wrapper, auto-creates data/ directory, auto-migrates on startup
internal/log/handler.go # custom slog: [LEVEL] [TIME] [FILE:LINE] message key=val
internal/tools/ # MCP tool registry + builtins (web_fetch, web_search stub)
internal/channel/ # Bubble Tea TUI + Matrix adapter (stub)
tui.go # chat UI: viewport + input bar, Ctrl+C/Ctrl+Q to quit
internal/config/config.go # std lib os.Getenv only (no third-party config libs)
pkg/types/types.go # Message, Role, Mood, ToolCall types
pkg/personality/traits.go # TraitValue, RelationshipMetrics, DiaryEntry, Observation types
```
| Layer | Dir | Role |
| ---------- | -------------------------------- | ---------------------------------------------------------------------------- |
| Entrypoint | `cmd/divad/main.go` | Wires agent, llama, companion, TUI, API, scheduler |
| Agent | `internal/agent/` | Message loop: receive → memory search → prompt → llama → save → respond |
| Companion | `internal/companion/` | Personality (5 traits), relationship, reflection, mood, prompt builder |
| Memory | `internal/memory/` | RAG store + self-memory (promises, strategies) |
| Inference | `internal/llama/` | llama.cpp HTTP client (`POST /completion`, `POST /embedding`, `GET /health`) |
| Storage | `internal/storage/` | SQLite wrapper, auto-creates `data/`, auto-migrates on startup |
| Channel | `internal/channel/` | Bubble Tea TUI + Matrix stub |
| Tools | `internal/tools/` | MCP tool registry + builtins (`web_fetch`, `web_search` stub) |
| Config | `internal/config/` | All env vars via std lib `os.Getenv` only |
| Types | `pkg/types/`, `pkg/personality/` | Shared data types |
## Key constraints
- **Module path**: `git.db123.ir/db123/divacode` — private Gitea. Set `GOPRIV=git.db123.ir GONOSUMDB=git.db123.ir GONOSUMCHECK=git.db123.ir GODIRECT=git.db123.ir GOPROXY=https://proxy.golang.org,direct` for `go mod tidy` and `go build`.
- **Database**: modernc.org/sqlite (pure Go, no CGO). Schema in `internal/storage/migrations.go` — 15 tables across two schema groups. `data/` dir auto-created on startup.
- **llama.cpp**: required at runtime, connected via HTTP. Default `http://localhost:8080`. Agent exits if health check fails.
- **Module**: `git.db123.ir/db123/divacode` — private Gitea. Set `GOPRIV`, `GONOSUMDB`, `GONOSUMCHECK` for `go mod tidy`/`go build`.
- **Database**: `modernc.org/sqlite` (pure Go, no CGO). **12 tables** across two schema groups in `internal/storage/migrations.go`. Two DB files: `divacode.db` (conversations, messages, context_state, memories) and `companion.db` (personality, relationship, reflection, self-memory). `data/` dir auto-created on startup.
- **Migrations** are code-internal constants; the `migrations/` directory is empty.
- **llama.cpp** required at runtime. Default `http://localhost:8080`. Agent exits if health check fails.
- **Logging**: `[LEVEL] [TIME] [FILE:LINE] message key=val`. Set `LOG_LEVEL=DEBUG` for verbose output.
- **HTTP API**: std lib `net/http`, enabled via `API_ENABLED=true`. Endpoints: `POST /v1/chat`, `POST /v1/conversations`, `GET /health`.
- **TUI quirks**: Bubble Tea with `tea.WithAltScreen()`. Keys: enter to send, backspace to edit, Ctrl+C/Ctrl+Q to quit.
- **OpenCode permissions**: `bash` commands need approval (ask mode), `git push*` and `rm -rf*` are denied.
- **HTTP API** (enabled via `API_ENABLED=true`): std lib `net/http` only. Endpoints: `GET /health`, `POST /v1/chat`, `POST /v1/conversations`.
- **TUI**: Bubble Tea with `tea.WithAltScreen()`. Enter to send, backspace to edit, Ctrl+C/Ctrl+Q to quit.
- **Formatters** in `opencode.json`: `gofmt` for `.go`, `prettier` for everything else. LSP enabled.
- **Config**: all via env vars, never third-party config libs. See `.env.example` for all knobs.
## Conventions (from "The Holy Code Bible")
| Context | Rule |
| ------------------------- | -------------------------------------------------------------- |
| exported Go identifiers | PascalCase |
| unexported Go identifiers | camelCase |
| Go file names | snake_case (`user_handler.go`) |
| Error wrapping | `fmt.Errorf("context: %w", err)` |
| Error checking | always check, no silent discards |
| Config | env vars only via `os.Getenv`, never `caarlos0/env` or similar |
| HTTP API | std lib `net/http` only, no third-party routers |
## Project files layout
```
cmd/divad/main.go # single entrypoint
internal/ # all app logic (unexported)
agent/ # two files: agent.go, scheduler.go
channel/ # two files: tui.go, matrix.go
companion/ # six files: engine.go + five sub-engines
config/ # one file
llama/ # one file
log/ # one file
memory/ # two files
storage/ # two files: sqlite.go, migrations.go
tools/ # two files: registry.go, builtin.go
pkg/ # shared types (exported if needed elsewhere)
```
## Docker
```bash
docker compose up -d # starts divacode agent only (llama.cpp runs externally)
```
Override variables via `.env` or environment:
```bash
LLAMACPP_URL=http://host.docker.internal:8080 docker compose up
```
| Context | Rule |
| ------------------------- | ----------------------------------------------- |
| Exported Go identifiers | PascalCase |
| Unexported Go identifiers | camelCase |
| Go file names | `snake_case.go` |
| Error wrapping | `fmt.Errorf("context: %w", err)` |
| Error checking | always check, no silent discards |
| Config | env vars only via `os.Getenv` |
| HTTP API | std lib `net/http` only, no third-party routers |