1
Go Architecture
Virgil edited this page 2026-03-11 12:14:36 +00:00
Go Architecture
Module: forge.lthn.ai/core/agent
Dependencies
Direct: core/cli, go-ai, go-config, go-i18n, go-inference, go-io, go-log, go-ratelimit, go-scm, go-store, mcp-go, go-redis, cobra, testify, yaml.v3, modernc/sqlite.
pkg/orchestrator — Clotho Orchestrator
Manages AI agent fleet configuration and dual-run verification.
Key Types
AgentConfig— Single agent machine config: Host, QueueDir, ForgejoUser, Model, Runner, VerifyModel, SecurityLevel, Roles, DualRun, Active, ApiURL, ApiKey.ClothoConfig— Orchestration strategy: Strategy (directorclotho-verified), ValidationThreshold (0.0-1.0), SigningKeyPath.Spinner— Clotho orchestrator. Holds Config + Agents map.DeterminePlan(signal, agentName) RunMode— decides standard vs dual-run based on strategy, agent config, and repo criticality.GetVerifierModel(agentName) string— returns secondary model for verification (default:gemini-1.5-pro).FindByForgejoUser(user) (name, AgentConfig, bool)— resolves Forgejo username to agent config.Weave(ctx, primary, signed) (bool, error)— compares primary/verifier outputs (placeholder for semantic diff).AgentsSeq() iter.Seq2[string, AgentConfig]— iterator over agents.
RunMode—ModeStandardorModeDual.
Functions
LoadAgents(cfg) (map[string]AgentConfig, error)— reads agents from config, validates, applies defaults.LoadActiveAgents(cfg)— returns only active agents.LoadClothoConfig(cfg)— loads Clotho settings (defaults: strategy=direct, threshold=0.85).SaveAgent(cfg, name, ac)/RemoveAgent(cfg, name)/ListAgents(cfg)— CRUD operations.
Security
SanitizePath(input) (string, error)— validates filename, prevents path traversal.EscapeShellArg(arg) string— single-quote escaping for shell insertion.SecureSSHCommandContext(ctx, host, cmd) *exec.Cmd— SSH with StrictHostKeyChecking, BatchMode, ConnectTimeout.MaskToken(token) string— masks tokens for safe logging.
pkg/jobrunner — Poll-Dispatch Engine
Event-driven job runner that polls sources for signals and dispatches to handlers.
Key Types
PipelineSignal— Snapshot of a child issue/PR: EpicNumber, ChildNumber, PRNumber, RepoOwner, RepoName, PRState, IsDraft, Mergeable, CheckStatus, threads, assignee, issue title/body, agent completion fields.ActionResult— Handler execution outcome: Action, repo coordinates, Success, Error, Timestamp, Duration, Cycle.JobSource(interface) —Name(),Poll(ctx) ([]*PipelineSignal, error),Report(ctx, *ActionResult) error.JobHandler(interface) —Name(),Match(*PipelineSignal) bool,Execute(ctx, *PipelineSignal) (*ActionResult, error).Poller— Orchestrates poll-dispatch cycles. Thread-safe via RWMutex.Run(ctx) error— blocking loop with configurable interval (default 60s).RunOnce(ctx) error— single poll-dispatch cycle.Sources() iter.Seq[JobSource]/Handlers() iter.Seq[JobHandler]— iterators.
Journal— JSONL audit log with date-partitioned files per repo. Path traversal protection.Append(signal, result) error— writes entry with sanitised paths.ReadEntries(path) iter.Seq2[JournalEntry, error]— streams entries.
JournalEntry— Timestamp, Epic, Child, PR, Repo, Action, SignalSnapshot, ResultSnapshot, Cycle.
pkg/lifecycle — API Client + Core Service
Client
HTTP client for the PHP agentic REST API.
Client— BaseURL, Token, HTTPClient, AgentID.ListTasks(ctx, ListOptions) ([]Task, error)GetTask(ctx, id) (*Task, error)ClaimTask(ctx, id) (*Task, error)UpdateTask(ctx, id, TaskUpdate) errorCompleteTask(ctx, id, TaskResult) errorCreateTask(ctx, Task) (*Task, error)Ping(ctx) error
Task— ID, Title, Description, Priority, Status, Labels, Files, ClaimedBy, Dependencies, Blockers, MaxRetries, RetryCount.TaskStatus—pending,in_progress,completed,blocked,failed.TaskPriority—critical,high,medium,low.
Service
Core framework service wrapping Claude Code CLI execution.
Service— embedscore.ServiceRuntime[ServiceOptions].TaskCommit— commit task: Path, Name, CanEdit.TaskPrompt— custom prompt task: Prompt, WorkDir, AllowedTools.- Handles
TaskCommitandTaskPromptviaclaude -psubprocess.
pkg/loop — Agent Loop Engine
Drives the prompt-tool-execute cycle for agentic inference.
Key Types
Engine— model (inference.TextModel), tools, system prompt, maxTurns.Run(ctx, userMessage) (*Result, error)— executes the loop: prompt model, parse tool calls, execute handlers, append results, repeat until no tool blocks or maxTurns exceeded.
Tool— Name, Description, Parameters (JSON Schema), Handler function.Message— Role (user/assistant/tool_result/system), Content, ToolUses.ToolUse— Name, Args (map).Result— Response (final text), Messages (full history), Turns count.
Options
WithModel(m), WithTools(tools...), WithSystem(prompt), WithMaxTurns(n).
CLI Commands
| Command | File | Description |
|---|---|---|
cmd/agent/ |
cmd.go | Agent entry point |
cmd/dispatch/ |
cmd.go, ratelimit.go | Dispatch with rate limiting |
cmd/mcp/ |
server.go, ethics.go, marketplace.go, core_cli.go | MCP server with ethics constraints and marketplace |
cmd/tasks/ |
cmd.go, updates.go | Task management |
cmd/workspace/ |
cmd.go, cmd_agent.go, cmd_task.go, cmd_workspace.go, config.go | Workspace management, agent CRUD, task ops |