This document provides a detailed technical analysis of the core packages within the framework.
---
## === Package: pkg/ansible ===
### 1. Overview
A native Go implementation of an Ansible playbook runner. Unlike wrappers that call the `ansible` CLI, this package parses YAML playbooks and inventories, handles variable interpolation (Jinja2-style), and executes modules directly over SSH or local connections. It is designed for embedding configuration management directly into the application without external dependencies.
### 2. Public API
#### Executor
The primary entry point for running playbooks.
```go
type Executor struct { ... }
func NewExecutor(basePath string) *Executor
func (e *Executor) SetInventory(path string) error
func (e *Executor) SetInventoryDirect(inv *Inventory)
func (e *Executor) SetVar(key string, value any)
func (e *Executor) Run(ctx context.Context, playbookPath string) error
func (e *Executor) Close()
```
#### Callback Hooks
Callbacks to monitor execution progress.
```go
e.OnPlayStart = func(play *Play)
e.OnTaskStart = func(host string, task *Task)
e.OnTaskEnd = func(host string, task *Task, result *TaskResult)
***Parser**: `parser.go` handles recursive YAML parsing, resolving role paths, and `include_tasks`.
***Module Dispatch**: `modules.go` contains a switch statement dispatching tasks to native Go functions (e.g., `moduleShell`, `moduleCopy`, `moduleApt`) based on the task name.
***Templating**: Implements a custom Jinja2-subset parser in `executor.go` (`templateString`, `resolveExpr`) to handle variables like `{{ var }}` and filters.
***SSH Abstraction**: `ssh.go` wraps `golang.org/x/crypto/ssh` to handle connection pooling, key management, and `sudo` escalation (become).
***Templating Logic**: Critical to test variable resolution, filters (`default`, `bool`), and nested lookups.
***Module Idempotency**: Verify that file/apt modules return `Changed: false` when state matches.
***SSH/Sudo**: Test `become` functionality with password handling.
### 6. Integration Points
Used by higher-level orchestration tools or the `pkg/devops` package to provision environments.
---
## === Package: pkg/devops ===
### 1. Overview
Manages a portable, sandboxed development environment using LinuxKit images. It handles the lifecycle (download, install, boot, stop) of a QEMU-based VM and provides utilities to bridge the host and VM (SSH forwarding, file mounting).
***Image Management**: `images.go` handles versioning and downloading QCOW2 images from GitHub/CDN.
***Container Abstraction**: Delegates low-level VM execution to `pkg/container` (likely a wrapper around QEMU/LinuxKit).
***SSH Bridging**: Heavily relies on `exec.Command("ssh", ...)` to tunnel ports, mount filesystems via SSHFS, and forward agents.
***Auto-Detection**: `DetectServeCommand` and `DetectTestCommand` inspect project files (`package.json`, `go.mod`) to determine how to run projects.
### 4. Dependencies
*`pkg/container`: VM runtime management.
*`pkg/io`: Filesystem abstraction.
*`pkg/config`: Configuration loading.
### 5. Test Coverage Notes
***Command Detection**: Unit tests for `Detect*Command` with various mock file structures.
***SSH Config**: Verify `ensureHostKey` correctly parses and updates `known_hosts`.
### 6. Integration Points
The primary interface for CLI commands (`core dev ...`). Bridges `pkg/mcp` agents into a sandboxed environment.
---
## === Package: pkg/framework ===
### 1. Overview
A facade package that re-exports types and functions from `pkg/framework/core`. It serves as the primary entry point for the Dependency Injection (DI) framework, providing a cleaner import path for consumers.
### 2. Public API
Re-exports `Core`, `Option`, `Message`, `Startable`, `Stoppable`, and constructors like `New`, `WithService`, `ServiceFor`.
### 3. Internal Design
Purely structural; contains type aliases and variable assignments to expose the internal `core` package.
No logic to test directly; coverage belongs in `pkg/framework/core`.
### 6. Integration Points
Imported by `main.go` and all service packages to register themselves with the DI container.
---
## === Package: pkg/mcp ===
### 1. Overview
Implements a Model Context Protocol (MCP) server. It acts as a bridge between AI models (like Claude) and the system tools, exposing file operations, process management, web browsing, and RAG capabilities as callable tools.
### 2. Public API
```go
type Service struct { ... }
func New(opts ...Option) (*Service, error)
func (s *Service) Run(ctx context.Context) error
func (s *Service) ServeTCP(ctx, addr string) error
***Tool I/O**: Ensure JSON inputs/outputs for tools map correctly to internal service calls.
### 6. Integration Points
Runs as a standalone server or subprocess for AI agents. Consumes `pkg/process` and `pkg/webview`.
---
## === Package: pkg/plugin ===
### 1. Overview
Provides a plugin system for the CLI, allowing extensions to be installed from GitHub. It manages a local registry of installed plugins and handles their lifecycle (install, update, remove).
### 2. Public API
```go
type Plugin interface { Name(); Version(); Init(); Start(); Stop() }
func (i *Installer) Install(ctx, source string) error // source: "org/repo"
func (i *Installer) Update(ctx, name string) error
```
### 3. Internal Design
***Manifest**: Relies on `plugin.json` in the root of the plugin repo.
***Git Integration**: Uses the `gh` CLI via `exec` to clone/pull repositories.
***Persistence**: Stores plugin metadata in a `registry.json` file.
### 4. Dependencies
*`pkg/io`: Filesystem access.
*`pkg/framework/core`: Error handling.
* External `gh` and `git` binaries.
### 5. Test Coverage Notes
***Manifest Validation**: Test valid/invalid `plugin.json` parsing.
***Source Parsing**: Test parsing of `org/repo`, `org/repo@v1`, etc.
### 6. Integration Points
Used by the main CLI application to load dynamic commands at startup.
---
## === Package: pkg/unifi ===
### 1. Overview
A strongly-typed client for Ubiquiti UniFi controllers. It wraps the `unpoller` SDK but adds configuration resolution (config file -> env var -> flags) and specific helper methods for data extraction not easily accessible in the raw SDK.
***Raw API Fallback**: Methods like `GetRoutes` and `GetNetworks` bypass the SDK's high-level structs to hit specific API endpoints (`/api/s/%s/stat/routing`) and decode into custom structs.
### 4. Dependencies
*`github.com/unpoller/unifi/v5`: Base SDK.
*`pkg/config`: Config file management.
### 5. Test Coverage Notes
***Config Resolution**: Verify priority order (Flag > Env > Config).
***JSON Unmarshalling**: Test `GetRoutes`/`GetNetworks` against sample JSON responses from a controller.
### 6. Integration Points
Used by network management plugins or diagnostic tools.
---
## === Package: pkg/webview ===
### 1. Overview
A browser automation package using the Chrome DevTools Protocol (CDP). It is designed for headless testing, scraping, and AI-driven interaction. It supports advanced features like Angular-specific waiting strategies.
### 2. Public API
```go
type Webview struct { ... }
func New(opts ...Option) (*Webview, error)
func (wv *Webview) Navigate(url string) error
func (wv *Webview) Click(selector string) error
func (wv *Webview) Type(selector, text string) error
***CDP Client**: `cdp.go` implements a raw WebSocket client for the DevTools protocol, managing message IDs and event dispatching.
***Action Sequence**: `actions.go` implements the Command pattern (`Action` interface) to chain browser interactions.
***Angular Awareness**: `angular.go` injects JS to probe `window.ng` or `getAllAngularRootElements` to interact with Angular's Zone.js and component state.
***CDP Protocol**: Mock the WebSocket server to ensure correct message serialization/response handling.
***Angular Helpers**: Requires an actual Angular app (or mock environment) to verify Zone.js stabilization logic.
### 6. Integration Points
Used by `pkg/mcp` to expose browser tools to AI agents.
---
## === Package: pkg/ws ===
### 1. Overview
A concurrent WebSocket hub implementation. It handles client registration, broadcasting, and channel-based subscriptions (e.g., subscribing only to logs for a specific process).
func (h *Hub) SendEvent(type string, data any) error
```
### 3. Internal Design
***Hub Pattern**: Central `Hub` struct manages a map of clients and channels. Uses unbuffered channels for registration to avoid race conditions.
***Channel Routing**: Maintains a `map[string]map[*Client]bool` to route messages efficiently to subscribers.
***Goroutines**: Each client spawns a `readPump` and `writePump` to handle I/O concurrently.
### 4. Dependencies
*`github.com/gorilla/websocket`
### 5. Test Coverage Notes
***Concurrency**: Test registering/unregistering clients while broadcasting heavily.
***Subscription**: Verify messages only go to subscribed clients.
### 6. Integration Points
Used by `pkg/mcp` to stream process output to a web UI.
---
## === Package: pkg/collect ===
### 1. Overview
A data collection pipeline for gathering data from various sources (GitHub, Forums, Market Data, Papers). It standardizes the collection process into a `Collector` interface and handles common concerns like rate limiting, state tracking (resume support), and formatting.
### 2. Public API
```go
type Collector interface {
Name() string
Collect(ctx, cfg *Config) (*Result, error)
}
type Excavator struct { Collectors []Collector ... }
func (e *Excavator) Run(ctx, cfg) (*Result, error)
```
### 3. Internal Design
***Excavator**: The orchestrator that runs collectors sequentially.
***RateLimiter**: Implements token bucket-like delays per source type (e.g., GitHub, CoinGecko).
***State Persistence**: Saves a JSON cursor file to resume interrupted collections.
***Formatters**: `process.go` converts raw HTML/JSON into Markdown for easier consumption by LLMs.
### 4. Dependencies
*`pkg/io`: File storage.
*`golang.org/x/net/html`: HTML parsing for forums/papers.
*`gh` CLI: Used for GitHub data fetching.
### 5. Test Coverage Notes
***HTML Parsing**: Test `ParsePostsFromHTML` with sample forum HTML.
***Rate Limit**: Verify `Wait` respects context cancellation and time delays.
### 6. Integration Points
Used as a standalone CLI command or by AI agents to gather context.
---
## === Package: pkg/i18n ===
### 1. Overview
A sophisticated internationalization library that goes beyond simple key-value lookups. It includes a grammar engine to handle pluralization, verb conjugation, and semantic sentence generation ("Subject verbed object").
### 2. Public API
```go
func T(key string, args ...any) string // Main translation function
func S(noun string, value any) *Subject // Create a semantic subject
func N(format string, value any) string // Number formatting
func SetLanguage(lang string) error
```
### 3. Internal Design
***Grammar Engine**: `grammar.go` applies rules for past tense, gerunds, and pluralization based on language-specific JSON rules or algorithmic fallbacks.
***Namespace Handlers**: `handler.go` intercepts keys like `i18n.count.*` or `i18n.done.*` to auto-generate phrases based on the grammar engine.