# Package Analysis — Batch 2

Generated by: gemini-batch-runner.sh
Models: gemini-2.5-flash-lite → gemini-3-flash-preview → gemini-3-pro-preview
Date: 2026-02-09
Packages: cli help session workspace
Total tokens: 125308

---

Here is the documentation for the analyzed framework packages.

# Core Framework Documentation

## Package: `pkg/cli`

### 1. Overview
The `cli` package is a comprehensive application runtime and UI framework designed to build uniform, aesthetic, and robust command-line interfaces. It acts as a high-level wrapper around `cobra`, handling application lifecycle (signals, daemonization), output styling (ANSI colors, glyphs, layouts), interactive prompts, and internationalization (i18n). Its design philosophy prioritizes developer ergonomics ("fluent" APIs) and consistent user experience across different execution modes (interactive vs. headless).

### 2. Public API

#### Application Lifecycle
- `func Init(opts Options) error`: Initialises the global CLI runtime, sets up the root command, and registers services.
- `func Main()`: The main entry point. Handles panic recovery, service initialization, and command execution. Exits process on completion.
- `func Execute() error`: Executes the root command structure.
- `func Shutdown()`: Triggers graceful shutdown of the runtime and all services.
- `func Run(ctx context.Context) error`: Blocking helper for daemon/simple modes.
- `func RunWithTimeout(timeout time.Duration) func()`: Returns a shutdown function that enforces a timeout.

#### Command Building
- `func NewCommand(use, short, long string, run func(*Command, []string) error) *Command`: Factory for standard commands.
- `func NewGroup(use, short, long string) *Command`: Factory for parent commands (no run logic).
- `func RegisterCommands(fn CommandRegistration)`: Registers a callback to add commands to the root at runtime.

#### Output & Styling
- `type AnsiStyle`: Fluent builder for text styling (Bold, Dim, Foreground, Background).
- `func Success(msg string)`, `func Error(msg string)`, `func Warn(msg string)`, `func Info(msg string)`: Semantic logging to stdout/stderr with glyphs.
- `func Table`: Struct and methods for rendering ASCII/Unicode tables.
- `func Check(name string) *CheckBuilder`: Fluent builder for test/verification status lines (Pass/Fail/Skip).
- `func Task(label, message string)`: Prints a task header.
- `func Progress(verb string, current, total int, item ...string)`: Prints a transient progress line.
- `func Layout(variant string) *Composite`: Creates an HLCRF (Header, Left, Content, Right, Footer) terminal layout.

#### Input & Interaction
- `func Confirm(prompt string, opts ...ConfirmOption) bool`: Interactive yes/no prompt.
- `func Prompt(label, defaultVal string) (string, error)`: Standard text input.
- `func Select(label string, options []string) (string, error)`: Interactive list selection.
- `func Choose[T](prompt string, items []T, opts ...ChooseOption[T]) T`: Generic selection helper.

#### Utilities
- `func GhAuthenticated() bool`: Checks GitHub CLI authentication status.
- `func GitClone(ctx, org, repo, path string) error`: Smart clone (uses `gh` if auth, else `git`).

### 3. Internal Design
- **Singleton Runtime**: The package relies on a package-level singleton `instance` (`runtime` struct) initialized via `Init`. This holds the `cobra.Command` tree and the Service Container.
- **Service Layering**: It integrates heavily with `pkg/framework`. Services like `log`, `i18n`, and `crypt` are injected into the runtime during initialization.
- **Mode Detection**: The `daemon.go` logic automatically detects if the app is running interactively (TTY), via pipe, or as a background daemon, adjusting output styling accordingly.
- **Global Error Handling**: Custom error types (`ExitError`) and wrappers (`WrapVerb`) utilize semantic grammar for consistent error messaging.
- **Glyph Abstraction**: The `Glyph` system abstracts symbols, allowing runtime switching between Unicode, Emoji, and ASCII themes based on terminal capabilities.

### 4. Dependencies
- `github.com/spf13/cobra`: The underlying command routing engine.
- `forge.lthn.ai/core/cli/pkg/framework`: The dependency injection and service lifecycle container.
- `forge.lthn.ai/core/cli/pkg/i18n`: For translation and semantic grammar generation.
- `forge.lthn.ai/core/cli/pkg/log`: For structured logging.
- `golang.org/x/term`: For TTY detection.

### 5. Test Coverage Notes
- **Interactive Prompts**: Tests must mock `stdin` to verify `Confirm`, `Prompt`, and `Select` behavior without hanging.
- **Command Registration**: Verify `RegisterCommands` works both before and after `Init` is called.
- **Daemon Lifecycle**: Tests needed for `PIDFile` locking and `HealthServer` endpoints (/health, /ready).
- **Layout Rendering**: Snapshot testing is recommended for `Layout` and `Table` rendering to ensure ANSI codes and alignment are correct.

### 6. Integration Points
- **Entry Point**: This package is the entry point for the entire application (`main.go` should call `cli.Main()`).
- **Service Registry**: Other packages (like `workspace` or custom logic) are registered as services via `cli.Options.Services`.
- **UI Standard**: All other packages should use `cli.Success`, `cli.Error`, etc., instead of `fmt.Println` to maintain visual consistency.

---

## Package: `pkg/help`

### 1. Overview
The `help` package provides an embedded documentation system. It treats documentation as data, parsing Markdown files into structured topics, and provides an in-memory full-text search engine to allow users to query help topics directly from the CLI.

### 2. Public API
- `type Catalog`: The central registry of help topics.
    - `func DefaultCatalog() *Catalog`: Creates a catalog with built-in topics.
    - `func (c *Catalog) Add(t *Topic)`: Registers a topic.
    - `func (c *Catalog) Search(query string) []*SearchResult`: Performs full-text search.
    - `func (c *Catalog) Get(id string) (*Topic, error)`: Retrieves a specific topic.
- `func ParseTopic(path string, content []byte) (*Topic, error)`: Parses raw Markdown content into a Topic struct.
- `type Topic`: Struct representing a documentation page (includes Title, Content, Sections, Tags).

### 3. Internal Design
- **In-Memory Indexing**: The `searchIndex` struct builds a reverse index (word -> topic IDs) on initialization. It does not use an external database.
- **Scoring Algorithm**: Search results are ranked based on a scoring system where matches in Titles > Section Headers > Content.
- **Markdown Parsing**: It uses Regex (`frontmatterRegex`, `headingRegex`) rather than a full AST parser to extract structure, prioritizing speed and simplicity for this specific use case.
- **Snippet Extraction**: The search logic includes a highlighter that extracts relevant text context around search terms.

### 4. Dependencies
- `gopkg.in/yaml.v3`: Used to parse the YAML frontmatter at the top of Markdown files.

### 5. Test Coverage Notes
- **Search Ranking**: Tests should verify that a keyword in a Title ranks higher than the same keyword in the body text.
- **Frontmatter Parsing**: Test with valid, invalid, and missing YAML frontmatter.
- **Tokenization**: Ensure `tokenize` handles punctuation and case insensitivity correctly to ensure search accuracy.

### 6. Integration Points
- **CLI Help Command**: The `pkg/cli` package would likely have a `help` command that instantiates the `Catalog` and calls `Search` or `Get` based on user input.

---

## Package: `pkg/session`

### 1. Overview
The `session` package is a specialized toolkit for parsing, analyzing, and visualizing "Claude Code" session transcripts (`.jsonl` files). It allows developers to replay AI interactions, search through past sessions, and generate visual artifacts (HTML reports or MP4 videos).

### 2. Public API
- `func ListSessions(projectsDir string) ([]Session, error)`: Scans a directory for session files.
- `func ParseTranscript(path string) (*Session, error)`: Reads a JSONL file and structures it into a `Session` object with a timeline of events.
- `func Search(projectsDir, query string) ([]SearchResult, error)`: specific search across all session files.
- `func RenderHTML(sess *Session, outputPath string) error`: Generates a self-contained HTML file visualizing the session.
- `func RenderMP4(sess *Session, outputPath string) error`: Uses `vhs` to render a video replay of the terminal session.

### 3. Internal Design
- **Streaming Parser**: `ParseTranscript` uses `bufio.Scanner` to handle potentially large JSONL files line-by-line, reconstructing the state of tool use (e.g., matching a `tool_use` event with its corresponding `tool_result`).
- **External Dependency Wrapper**: `RenderMP4` generates a `.tape` file dynamically and executes the external `vhs` binary to produce video.
- **HTML embedding**: `RenderHTML` embeds CSS and JS directly into the Go source strings to produce a single-file portable output without static asset dependencies.

### 4. Dependencies
- `github.com/charmbracelet/vhs` (Runtime dependency): The `vhs` binary must be installed for `RenderMP4` to work.
- Standard Library (`encoding/json`, `html/template` equivalents).

### 5. Test Coverage Notes
- **JSON Parsing**: Critical to test against the exact schema of Claude Code logs, including edge cases like partial streams or error states.
- **VHS Generation**: Test that the generated `.tape` content follows the VHS syntax correctly.
- **Tool Mapping**: Verify that specific tools (Bash, Edit, Write) are correctly categorized and parsed from the raw JSON arguments.

### 6. Integration Points
- **CLI Commands**: Likely used by commands like `core session list`, `core session play`, or `core session export`.
- **Filesystem**: Reads directly from the user's Claude Code project directory (usually `~/.claude/`).

---

## Package: `pkg/workspace`

### 1. Overview
The `workspace` package implements the `core.Workspace` interface, providing isolated, secure working environments. It manages the directory structure, file I/O, and cryptographic identity (PGP keys) associated with specific projects or contexts.

### 2. Public API
- `func New(c *core.Core) (any, error)`: Service factory function compatible with the framework registry.
- `func (s *Service) CreateWorkspace(identifier, password string) (string, error)`: Initialises a new workspace directory with keys.
- `func (s *Service) SwitchWorkspace(name string) error`: Sets the active context.
- `func (s *Service) WorkspaceFileGet(filename string) (string, error)`: Reads a file from the active workspace.
- `func (s *Service) WorkspaceFileSet(filename, content string) error`: Writes a file to the active workspace.

### 3. Internal Design
- **Service Implementation**: Implements `core.Workspace`.
- **IPC Handling**: Contains `HandleIPCEvents` to respond to generic framework messages (`workspace.create`, `workspace.switch`), allowing loose coupling with other components.
- **Path Hashing**: Uses SHA-256 to hash workspace identifiers into directory names (referred to as "LTHN proxy" in comments), likely to sanitize paths and obscure names.
- **Key Management**: Delegates actual key generation to the core's `Crypt()` service but manages the storage of the resulting keys within the workspace layout.

### 4. Dependencies
- `forge.lthn.ai/core/cli/pkg/framework/core`: Interfaces.
- `forge.lthn.ai/core/cli/pkg/io`: File system abstraction (`io.Medium`).
- `crypt` service (Runtime dependency): Required for `CreateWorkspace`.

### 5. Test Coverage Notes
- **Mocking IO**: Use an in-memory `io.Medium` implementation to test directory creation and file writing without touching the real disk.
- **State Management**: Test that `WorkspaceFileGet` fails correctly if `SwitchWorkspace` hasn't been called yet.
- **Concurrency**: `sync.RWMutex` is used; tests should verify race conditions aren't possible during rapid switching/reading.

### 6. Integration Points
- **Core Framework**: Registered in `pkg/cli/app.go` via `framework.WithName("workspace", workspace.New)`.
- **IPC**: Can be controlled by other plugins or UI components via the framework's message bus.

---

## Quick Reference (Flash Summary)

### Package: `pkg/cli`
**Description:** A comprehensive CLI framework providing terminal styling, command management, interactive prompts, and daemon lifecycles.

**Key Exported Types and Functions:**
- `AnsiStyle`: Struct for chaining terminal text styles (bold, colors, etc.).
- `Main()`: The primary entry point that initializes services and executes the root command.
- `Command`: Re-exported `cobra.Command` for simplified dependency management.
- `NewDaemon(opts)`: Manages background process lifecycles, PID files, and health checks.
- `Check(name)`: Fluent API for rendering status check lines (e.g., "✓ audit passed").
- `Confirm/Question/Choose`: Interactive prompt utilities for user input and selection.
- `Composite`: Implements a region-based layout system (Header, Left, Content, Right, Footer).
- `Table`: Helper for rendering aligned tabular data in the terminal.

**Dependencies:**
- `pkg/crypt/openpgp`
- `pkg/framework`
- `pkg/log`
- `pkg/workspace`
- `pkg/i18n`
- `pkg/io`

**Complexity:** Complex

---

### Package: `pkg/help`
**Description:** Manages display-agnostic help content with markdown parsing and full-text search capabilities.

**Key Exported Types and Functions:**
- `Catalog`: Registry for managing and searching help topics.
- `Topic`: Represents a help page including content, sections, and metadata.
- `ParseTopic(path, content)`: Parses markdown files with YAML frontmatter into structured topics.
- `searchIndex`: Internal engine providing scored full-text search and snippet extraction.
- `GenerateID(title)`: Utility to create URL-safe identifiers from strings.

**Dependencies:**
- *None* (Internal `pkg/*` imports)

**Complexity:** Moderate

---

### Package: `pkg/session`
**Description:** Parses, searches, and renders Claude Code session transcripts (JSONL) into HTML or video formats.

**Key Exported Types and Functions:**
- `Session`: Holds metadata and a timeline of `Event` objects from a transcript.
- `ParseTranscript(path)`: Reads JSONL files and reconstructs tool usage, user, and assistant interactions.
- `RenderHTML(sess, path)`: Generates a self-contained, interactive HTML timeline of a session.
- `RenderMP4(sess, path)`: Uses VHS to generate a terminal-style video recording of a session.
- `Search(dir, query)`: Scans a directory of session files for specific text or tool usage.

**Dependencies:**
- *None*

**Complexity:** Moderate

---

### Package: `pkg/workspace`
**Description:** Manages isolated, encrypted filesystem environments for different CLI projects.

**Key Exported Types and Functions:**
- `Service`: Core service managing active workspaces and their storage roots.
- `CreateWorkspace(id, pass)`: Initializes a hashed directory structure and generates PGP keypairs.
- `SwitchWorkspace(name)`: Sets the active workspace for subsequent file operations.
- `WorkspaceFileSet/Get`: Encrypted file I/O within the active workspace context.
- `HandleIPCEvents`: Processes workspace-related commands via the internal message bus.

**Dependencies:**
- `pkg/framework/core`
- `pkg/io`

**Complexity:** Moderate
