web

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

ABOUTME: Selects the codergen backend (Claude Code, agent, mux) from environment variables. ABOUTME: Used by the web server to configure which LLM backend drives pipeline execution.

ABOUTME: Build run types and SSE event formatting for the attractor pipeline runner. ABOUTME: Provides BuildRun for tracking active builds and RunState for pipeline lifecycle.

ABOUTME: Template-friendly diagnostics view that splits DOT validation results by severity. ABOUTME: Provides error/warning counts and messages for the build UI.

ABOUTME: HTTP handler that auto-fixes DOT graph validation errors using an LLM. ABOUTME: Parses, validates, and rewrites the project DOT via the configured backend.

ABOUTME: Adapter layer connecting the editor package to the unified project-scoped web flow. ABOUTME: Mounts editor handlers under /projects/{projectID}/editor and keeps project DOT in sync.

ABOUTME: HTTP logging middleware for the unified web server with consistent log.Printf style. ABOUTME: Replaces chi's default logger format to align request logs with agent/runtime logs.

ABOUTME: Configures a default interviewer for wait.human nodes in web builds. ABOUTME: Auto-approves review gates so pipelines run unattended in the web UI.

ABOUTME: Project data model representing a mammoth project through its lifecycle. ABOUTME: Includes ProjectStore for in-memory and filesystem-based persistence.

ABOUTME: Unified mammoth HTTP server providing the wizard flow for Spec Builder, ABOUTME: DOT Editor, and Attractor Pipeline Runner behind a single chi router.

ABOUTME: Adapter layer connecting spec/web handlers to the unified mammoth HTTP server. ABOUTME: Provides middleware for URL translation, lazy spec initialization, and API handlers.

ABOUTME: Spec builder options parsed from form input for pipeline configuration. ABOUTME: Controls toggles like human review, scenario testing, TDD, and complexity level.

ABOUTME: Embeds web/static/ CSS and JS files for serving via the unified HTTP server. ABOUTME: Uses explicit subdirectory globs because //go:embed static/* does not recurse.

ABOUTME: TemplateEngine loads embedded HTML templates and renders them with Go's html/template. ABOUTME: Templates are embedded at compile time via go:embed for zero runtime path issues.

ABOUTME: Transition logic connecting the spec builder phase to the DOT editor and build phases. ABOUTME: Exports DOT from spec state, validates it, and routes to the correct project phase.

Index

Constants

This section is empty.

Variables

View Source
var StaticFS embed.FS

Functions

func TransitionEditorToBuild

func TransitionEditorToBuild(project *Project) error

TransitionEditorToBuild validates the current DOT and transitions to build. If the DOT has parse or lint errors, it stays in the edit phase and returns an error. If the DOT is clean, it transitions to the build phase.

func TransitionSpecToBuild

func TransitionSpecToBuild(project *Project, specState *core.SpecState) error

TransitionSpecToBuild is the "Build Now" shortcut that skips the editor. If the DOT has no lint errors, it transitions straight to build phase. If there are lint errors, it transitions to edit phase with diagnostics.

func TransitionSpecToEditor

func TransitionSpecToEditor(project *Project, specState *core.SpecState) error

TransitionSpecToEditor generates DOT from a spec state and updates the project for the editor phase. The DOT is exported, parsed for validation, and linted for diagnostics. The project is always set to the edit phase on success.

Types

type BuildRun

type BuildRun struct {
	State  *RunState
	Events chan SSEEvent
	Cancel context.CancelFunc
	Ctx    context.Context
	// contains filtered or unexported fields
}

BuildRun holds all state for an active build, including the cancellation context, SSE event channel, and current RunState.

func (*BuildRun) EnsureFanoutStarted

func (r *BuildRun) EnsureFanoutStarted()

EnsureFanoutStarted starts a background broadcaster that fans Events out to all subscribers. Safe to call multiple times.

func (*BuildRun) HistorySnapshot

func (r *BuildRun) HistorySnapshot() []SSEEvent

HistorySnapshot returns a copy of buffered recent events for replay.

func (*BuildRun) Subscribe

func (r *BuildRun) Subscribe() (<-chan SSEEvent, func())

Subscribe registers a subscriber channel that receives all future events. The returned function unsubscribes and closes the channel.

func (*BuildRun) SubscribeWithHistory

func (r *BuildRun) SubscribeWithHistory() ([]SSEEvent, <-chan SSEEvent, func())

SubscribeWithHistory atomically snapshots buffered events and subscribes for future events to avoid replay/stream duplication races.

type DiagnosticsView

type DiagnosticsView struct {
	BuildBlocked bool
	ErrorCount   int
	WarningCount int
	Errors       []string
	Warnings     []string
	Other        []string
}

DiagnosticsView provides a template-friendly summary split by severity.

type PageData

type PageData struct {
	Title       string
	Project     *Project
	Projects    []*Project
	Mode        string // "idea" or "dot" for project_new
	ActivePhase string // current wizard phase for highlighting
	Diagnostics DiagnosticsView
	Workspace   *Workspace // workspace info for display on project list
}

PageData holds all data passed to templates for rendering.

type Project

type Project struct {
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	CreatedAt   time.Time    `json:"created_at"`
	Phase       ProjectPhase `json:"phase"`
	SpecID      string       `json:"spec_id,omitempty"`
	DOT         string       `json:"dot,omitempty"`
	Diagnostics []string     `json:"diagnostics,omitempty"`
	RunID       string       `json:"run_id,omitempty"`
	DataDir     string       `json:"-"`
}

Project represents a mammoth project spanning the full wizard flow (Spec -> Edit -> Build).

type ProjectPhase

type ProjectPhase string

ProjectPhase represents the current stage of a project in the wizard flow.

const (
	PhaseSpec  ProjectPhase = "spec"
	PhaseEdit  ProjectPhase = "edit"
	PhaseBuild ProjectPhase = "build"
	PhaseDone  ProjectPhase = "done"
)

type ProjectStore

type ProjectStore struct {
	// contains filtered or unexported fields
}

ProjectStore provides in-memory storage with filesystem persistence for projects.

func NewProjectStore

func NewProjectStore(baseDir string) *ProjectStore

NewProjectStore creates a new ProjectStore rooted at the given base directory.

func (*ProjectStore) Create

func (s *ProjectStore) Create(name string) (*Project, error)

Create makes a new project with the given name. It starts in the spec phase.

func (*ProjectStore) Get

func (s *ProjectStore) Get(id string) (*Project, bool)

Get retrieves a project by ID. Returns a copy of the project and true if found, or nil and false if not found. The copy prevents data races when callers modify the returned project concurrently.

func (*ProjectStore) List

func (s *ProjectStore) List() []*Project

List returns all projects sorted by creation time, newest first. Each returned project is a copy to prevent data races from concurrent mutation.

func (*ProjectStore) LoadAll

func (s *ProjectStore) LoadAll() error

LoadAll reads all project.json files from subdirectories of baseDir and populates the in-memory store.

func (*ProjectStore) Save

func (s *ProjectStore) Save(p *Project) error

Save persists a project to disk as JSON in its data directory. It validates the project ID to prevent path traversal attacks before writing.

func (*ProjectStore) Update

func (s *ProjectStore) Update(p *Project) error

Update replaces the stored project with the provided one. The project must already exist in the store (matched by ID).

type RunState

type RunState struct {
	ID             string     `json:"id"`
	Status         string     `json:"status"` // "running", "completed", "failed", "cancelled"
	StartedAt      time.Time  `json:"started_at"`
	CompletedAt    *time.Time `json:"completed_at,omitempty"`
	CurrentNode    string     `json:"current_node"`
	CompletedNodes []string   `json:"completed_nodes"`
	Error          string     `json:"error,omitempty"`
}

RunState tracks the lifecycle state of a pipeline run within the web layer. It mirrors attractor.RunState fields relevant to the UI.

type SSEEvent

type SSEEvent struct {
	Event string // event type (e.g. "pipeline.started", "stage.completed")
	Data  string // JSON-encoded event data
}

SSEEvent represents a server-sent event ready for formatting and transmission.

func (SSEEvent) Format

func (e SSEEvent) Format() string

Format renders the SSEEvent as a properly formatted SSE message string. The format follows the SSE spec: "event: <type>\ndata: <data>\n\n".

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the unified mammoth HTTP server that provides the wizard flow: Spec Builder -> DOT Editor -> Attractor Pipeline Runner.

func NewServer

func NewServer(cfg ServerConfig) (*Server, error)

NewServer creates a new Server with the given configuration. It initializes the project store and sets up routing.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the HTTP server on the configured address with appropriate timeouts to prevent resource exhaustion from slow clients.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP delegates to the chi router, satisfying http.Handler.

type ServerConfig

type ServerConfig struct {
	Addr      string    // listen address (default: "127.0.0.1:2389")
	Workspace Workspace // workspace for path resolution
}

ServerConfig holds the configuration for the unified web server.

type TemplateEngine

type TemplateEngine struct {
	// contains filtered or unexported fields
}

TemplateEngine loads and renders embedded HTML templates.

func NewTemplateEngine

func NewTemplateEngine() (*TemplateEngine, error)

NewTemplateEngine parses all embedded templates and returns a ready-to-use engine. Each page template is parsed together with the layout so that the layout wraps every page.

func (*TemplateEngine) Render

func (e *TemplateEngine) Render(w http.ResponseWriter, name string, data any) error

Render executes the named template with the given data and writes the result to w. It sets the Content-Type header to text/html.

func (*TemplateEngine) RenderStandalone added in v0.5.0

func (e *TemplateEngine) RenderStandalone(w http.ResponseWriter, name string, data any) error

RenderStandalone executes a standalone template (no layout wrapping) and writes the result to w. It sets the Content-Type header to text/html.

func (*TemplateEngine) RenderStandaloneTo added in v0.5.0

func (e *TemplateEngine) RenderStandaloneTo(w io.Writer, name string, data any) error

RenderStandaloneTo executes a standalone template (no layout wrapping) and writes the result to an arbitrary io.Writer.

func (*TemplateEngine) RenderTo

func (e *TemplateEngine) RenderTo(w io.Writer, name string, data any) error

RenderTo executes the named template with the given data and writes the result to an arbitrary io.Writer (useful for testing without HTTP).

type Workspace added in v0.6.0

type Workspace struct {
	Mode     WorkspaceMode
	RootDir  string // Where artifacts/code output goes
	StateDir string // Where .mammoth state lives (projects, checkpoints, runs)
}

Workspace resolves all filesystem paths for mammoth based on the active mode.

func NewGlobalWorkspace added in v0.6.0

func NewGlobalWorkspace(dataDir string) Workspace

NewGlobalWorkspace creates a workspace where root and state are the same centralized directory (the XDG data dir).

func NewLocalWorkspace added in v0.6.0

func NewLocalWorkspace(rootDir string) Workspace

NewLocalWorkspace creates a workspace rooted at the given directory. State and artifacts go in {rootDir}/.mammoth/.

func (Workspace) ArtifactDir added in v0.6.0

func (w Workspace) ArtifactDir(projectID, runID string) string

ArtifactDir returns where build artifacts (generated code) should be written. In local mode, artifacts go directly into the project root so the user sees generated files in their working directory. In global mode, artifacts are namespaced under the state directory by project and run.

func (Workspace) CheckpointDir added in v0.6.0

func (w Workspace) CheckpointDir(projectID, runID string) string

CheckpointDir returns where checkpoints and progress logs are stored. Always under the state directory regardless of mode.

func (Workspace) ProgressLogDir added in v0.6.0

func (w Workspace) ProgressLogDir(projectID, runID string) string

ProgressLogDir returns where progress.ndjson is stored. Always under the state directory regardless of mode.

func (Workspace) ProjectStoreDir added in v0.6.0

func (w Workspace) ProjectStoreDir() string

ProjectStoreDir returns the directory where project.json files are stored.

func (Workspace) RunStateDir added in v0.6.0

func (w Workspace) RunStateDir() string

RunStateDir returns the directory for persistent run state (manifests, events).

type WorkspaceMode added in v0.6.0

type WorkspaceMode string

WorkspaceMode determines how mammoth resolves paths for state and artifacts.

const (
	// ModeLocal stores state and artifacts in .mammoth/ under CWD.
	ModeLocal WorkspaceMode = "local"
	// ModeGlobal stores everything under a centralized data directory (XDG).
	ModeGlobal WorkspaceMode = "global"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL