Architecture
terraform-ui is a Go application built with Bubbletea (TUI framework) and terraform-exec (Go library that runs the terraform binary). Features are modular plugins that depend only on a public SDK package.
This page maps each part to its directory and the decision behind it. How to test each part is in Testing; TUI and CLI rules are in TUI UX and CLI UX; decisions are in the ADRs.
Dependency Direction
plugins/* ───→ pkg/sdk ←─── internal/*
│ │
│ (public contract only) │ (implements sdk interfaces)
│ │
└── never imports internal/ ──────┘
Plugins depend exclusively on pkg/sdk/ (ADR-0001). Internal packages implement the interfaces defined there.
Project Structure
cmd/tfui/ — CLI entry point (thin glue)
main.go — Cobra command tree (rootCmd.AddCommand)
root.go — Root command and persistent flags
registry.go — buildRegistry(): every plugin factory with its PluginMeta
session.go — Session: Run (app mode) and RunPlugin (one plugin)
<name>_command.go — One file per subcommand; most parse flags into a plugin's Input
normalize.go — Terraform flag compatibility (normalizeArgs, splitPassthrough)
pkg/sdk/ — Public SDK (the only dependency for plugins; key files below)
plugin.go — Plugin interface + optional interfaces
plugin_deps.go — PluginDeps, handed to Init()
context.go, pins.go — Immutable Context snapshot and its Pins
service.go — Service interface (terraform operations)
command.go — Command: one terraform invocation
bus.go, events.go — EventBus typed dispatch, events and handler interfaces
action_runner.go — ActionRunner: the action-mode lifecycle
frame.go, stack.go — Frame stack navigation primitives
overlay.go, input.go — Modal overlays and input system
styles.go — Style constants for consistent rendering
frames/ — Reusable frames (filter, inspect, confirm, action, form, stream)
ui/ — Widgets (cursor, filter, timer, tree, actions bar, content panel)
sdktest/ — Test harness, MockService, golden helpers
internal/
config/ — HCL config loading, project discovery, Resolve
plugin/registry.go — Plugin registry (host-side only)
terraform/
exec/
service.go — ExecService (implements sdk.Service via terraform-exec)
state_ops.go — State operations (rm, mv, import, taint, untaint)
workspace_ops.go — Workspace operations
dir_lock.go — Non-reentrant per-directory lock (ADR-0016)
macro_service.go — MacroService (records commands, reads from cache)
service_cache.go — ServiceCache (typed, source-aware data cache)
loader.go — LoadPlan / LoadState from raw bytes
plan_parser.go — Plan JSON parsing
risk.go, phantom.go, grouping.go — Analysis over plan and state
source/ — Source layer (URI → bytes)
macro/ — Macro engine (driver, runner, tape parser, recorder)
ui/
app.go — Root Bubbletea model: routing, navigation, Context ownership
components/ — Header, statusbar, command bar, content border
editor/ — Editor integration ($EDITOR at file:line)
logging/ — Structured logger setup
scaffold/ — Project scaffolding (tfui.hcl generation)
compliance/ — Plugin lifecycle compliance tests
plugins/
context/ — Context dashboard: Project + Chdir + Workspace
chdir/ — Chdir picker: select member from explicit list
state/ — State browser (list, inspect, pin, delete, move)
plan/ — Plan review (diff view, expand attributes, risk)
apply/ — Apply executor (the plan file from plan, or a one-shot apply)
taint/ — Taint (Action Mode): mark for recreation
untaint/ — Untaint (Action Mode): remove taint mark
import/ — Import (Action Mode): bring existing infra
workspace/ — Workspace management
console/ — Terraform console (REPL)
output/ — Terraform outputs viewer
validate/ — Terraform validate with diagnostics
init/ — Terraform init with form-based options
risk/ — Groups supplied plan classifications for review
phantom/ — Phantom change detection (decorates plan)
blastradius/ — Blast radius visualization
forceunlock/ — Force unlock stale state locks
version/ — Version information display
tests/
integration/ — CLI integration tests (require terraform)
fixtures/ — Real terraform projects and config fixtures
Plugin System
Every feature is a plugin implementing sdk.Plugin (pkg/sdk/plugin.go):
type Plugin interface {
ID() string
Name() string
Description() string
Init(deps *PluginDeps) tea.Cmd
Update(msg tea.Msg) (Plugin, tea.Cmd)
View(width, height int) string
Configure(cfg map[string]interface{}) error
Ready() bool
}
Optional interfaces add capabilities the app detects by type assertion: Activatable, Busy, Cancellable,
Countable, Hintable, KeyCapturer, Pinnable, Positionable, Stackable (frame.go), StdoutEmitter,
StderrEmitter, ExitCoder, Statusable, Shutdowner (called on every registered plugin when the program ends).
A plugin invoked from the CLI is a use case with two ports (ADR-0021):
- Input port: a typed
InputDTO and the plugin’s ownActivate(input Input) tea.Cmdmethod, distinct fromsdk.Activatable, whoseActivate()takes no input. The subcommand incmd/tfui/<name>_command.goparses flags into the Input. - Output port:
StdoutEmitter.Stdout() ([]byte, error),StderrEmitter.Stderr() []byteandExitCoder.ExitCode() int; the framework pumps each to its sink.
Plugins are:
- Self-contained — own view logic, types, messages
- Configurable — per-plugin options in
tfui.hcl - Independent — import only
pkg/sdk, neverinternal/, and never reference each other - Testable — built with the test harness and
sdktest.MockService(Testing)
PluginDeps and Context
Init receives *sdk.PluginDeps (pkg/sdk/plugin_deps.go), fixed for the process lifetime:
| Field | Purpose |
|---|---|
Logger |
Structured logger |
Service |
Unscoped terraform service, a fallback until the first ContextChangedEvent |
Context |
func() *Context returning the current snapshot |
Pin |
Toggles a group of pin addresses; triggers a Context replacement |
ClearPins |
Removes every pin |
RequestAssessment |
Asks the host to assess a plan summary against the risk policy; returns the request’s AssessmentID, and the result arrives as a RiskAssessedEvent carrying it |
RequestPlan |
Asks the host to plan the active Context with Plan’s default targets, loading no risk policy; returns the request’s PlanRequestID, and the result arrives as a PlanFetchedEvent carrying it |
sdk.Context (pkg/sdk/context.go) is an immutable snapshot of everything that shapes a terraform command: Chdir,
WorkingDir, Workspace, a Service scoped to the working directory, Pins, VarFiles, Vars, ExtraArgs,
Parallelism, Lock and LockTimeout. The app replaces it whole on every chdir, workspace or pin change
(ADR-0018); plugins never mutate it and react through
ContextChangedHandler. WithPins and TogglePins return a fresh snapshot.
Pins are the UI selection; targets are terraform’s -target= flags. The boundary is Context.PlanOptions(), which
sets Targets from Pins. PlanOptions.WithDefaultTargets falls back to Plan’s configured targets when nothing
is pinned; the Plan plugin and the risk coordinator both use it. Context.ApplyOptions() carries no targets, because
apply runs a saved plan file
(ADR-0019). Pins are always resource addresses: a tree row resolves to them
through Tree.PinAddresses(node) in pkg/sdk/ui/tree/ (a leaf gives its own address, a branch every descendant leaf), and the tree keeps no
pin state of its own, so a row cannot disagree with the Context.
Event Bus
pkg/sdk/bus.go dispatches typed events (pkg/sdk/events.go) to every plugin that implements the matching handler
interface (ADR-0003):
| Event | Handler |
|---|---|
ContextChangedEvent |
ContextChangedHandler |
PlanCompletedEvent |
PlanCompletedHandler |
PlanInvalidatedEvent |
PlanInvalidatedHandler |
PlanFetchedEvent |
PlanFetchedHandler |
RiskAssessedEvent |
RiskAssessedHandler |
LockDetectedEvent |
LockDetectedHandler |
LockClearedEvent |
LockClearedHandler |
StateRefreshedEvent |
StateRefreshedHandler |
ContextChangedEvent carries Prev, Next and a Reason; OnlyPinsChanged() lets plan tell a pin toggle (keep UI
state, mark stale) from a chdir or workspace switch (full reset).
PlanCompletedEvent carries the Context its plan ran against and Request, which identifies the plan run: the
AssessmentID of the assessment Plan requested when the plan finished, whose result may never be dispatched. The
App drops one whose Context was replaced since, so a late completion cannot restore results for a Context the user
left. Request IDs grow with every host request, so the ID also orders the plan
against invalidations and other plans: the App drops a completion issued before the last PlanInvalidatedEvent or
Context change, or older than the last completion it dispatched. Before dispatching a current one, the App unpins the
addresses the plan no longer changes; that pin change lands first, so plugins that reset on it keep the plan, and it
is the plan’s own, so the App still treats the plan as current. Plan’s ApplyRequestMsg carries the same ID, and the
App starts Apply only while that plan is current.
Risk assessment
Risk policy architecture explains why the feature is shaped this way.
PluginDeps.RequestAssessment is the only way a plugin gets risk; no plugin runs a plan for it or reads the policy. The
host owns each request in internal/riskassess: it loads and compiles the policy the active Context selects, runs the
plan when the summary is nil, evaluates the summary, re-checks that the policy source did not change, and publishes a
RiskAssessedEvent to every RiskAssessedHandler. A plugin calls RequestAssessment only on the Update loop, because
the request captures the active Context.
RequestAssessment returns the request’s AssessmentID at once, and the event carries it as Request. IDs are
nonzero and never reused, so a plugin records the ID of its pending request and keeps only the event carrying it.
The App routes: it starts requests and drops a result whose request preceded a Context change or a plan invalidation,
which also cancel every pending request. Each plugin holds at most one pending request: a new request cancels its
previous one, and cancelling a plugin cancels its own request, both the plan the host runs for a nil summary and the
policy evaluation, and no other plugin’s. The App still dispatches a cancelled request’s result; the requester ignores
it by AssessmentID.
A plugin that needs a plan and no risk, as Phantom does on a cold open, calls PluginDeps.RequestPlan instead. The
same coordinator runs it with the same rules: one pending request per plugin, cancelled and made stale the same way,
and the plan uses Plan’s default targets when nothing is pinned. It loads no policy, so a broken risk policy cannot
stop it, and its result is a PlanFetchedEvent that carries a PlanRequestID.
Plugin Loading
Plugins are compiled into the binary. buildRegistry() in cmd/tfui/registry.go is the one place every plugin is
registered and handed its tfui.hcl settings. It registers each factory with a plugin.PluginMeta that holds its
routing, so plugins stay invocation-agnostic (ADR-0006):
| Field | Meaning |
|---|---|
Keybinding |
Key that opens it from home |
MenuVisible |
Listed on the home menu |
Nav |
NavReplace (lateral switch, history cleared) or NavPush (pushed onto the return stack) |
Navigation (internal/ui/app.go)
The app keeps the active plugin and a navStack of plugins to return to
(ADR-0004):
navigateTo(p)passes the busy-guard, cancels the active plugin if it isCancellable, then pushes ontonavStackforNavPushor clears it forNavReplace.navigateBack()popsnavStack, or returns home when it is empty.popIfPushed(cmd)pops aNavPushplugin after an event it raised, such as a context switch.- Workflow transitions push at runtime regardless of metadata:
ApplyRequestMsgfrom plan pushes plan and activates apply. - Plugins request navigation with
NavigateMsg{PluginID}and leave withDeactivateMsg; they never hold references to each other.
Busy-guard. Every action that may start a terraform call or change its inputs goes through requireIdle(reason):
while any plugin is Busy() (Terraform runs for it, holding the directory lock,
ADR-0016), the action is refused with a message pointing to :q!. A risk
assessment the host evaluates against a plan it already has runs no Terraform: it keeps the plugin’s Ready() false so
headless output waits, but it is not Busy(), so the action proceeds and cancels it. The chokepoints are
ContextSwitchRequestMsg, navigateTo and :q. UI-only actions such as scrolling, filtering and esc bypass it. :q!
skips the guard and cancels every cancellable plugin.
View delegation. The app calls plugin.View(width, height) directly. The frame stack routes input
(Stack.Update()) but not rendering, so a Stackable plugin’s View() delegates to its top frame itself.
Action Mode
A plugin is in action mode while it executes and reports: run, result, render, ctrl+r retry, success events, with a
cancellable context and an elapsed timer. The embeddable sdk.ActionRunner, configured per operation with an
sdk.ActionSpec, provides it (CONTEXT.md). Taint,
untaint, import and forceunlock use it; they are NavPush, hidden from the menu, and reached through contextual keys
in state and plan (TaintRequestMsg, UntaintRequestMsg, ImportRequestMsg) or :command.
| Operation | Events on success |
|---|---|
| Taint, Untaint | PlanInvalidatedEvent |
| Import | StateRefreshedEvent, PlanInvalidatedEvent |
| ForceUnlock | LockClearedEvent, PlanInvalidatedEvent |
Overlays, Input and Frames
sdk.Overlay (pkg/sdk/overlay.go) is a modal with its own Update, View and Hints. A plugin asks for input with
RequestInputMsg wrapping an InputRequest (Text, Bool, Select or Filter mode) and receives InputResponseMsg; the
helpers are InputConfirm, InputText and InputSelect (pkg/sdk/input.go). pkg/sdk/frames/ holds the reusable
frames: FilterFrame, InspectFrame, ConfirmFrame, ActionFrame (a running operation with cancel), FormFrame
(fields with validation) and StreamFrame (streaming output of plan, apply and init).
Terraform Integration
Two sibling implementations of sdk.Service exist as a strategy pattern, selected once at startup; plugins never know
which one runs (ADR-0002).
A new Service method is implemented on ExecService, MacroService and sdktest.MockService.
ExecService (live execution)
internal/terraform/exec/service.go shells out to the terraform (or tofu) binary via hashicorp/terraform-exec.
Every call is serialized per working directory by a non-reentrant DirLock
(ADR-0016). WithDir() returns a service scoped to another directory with a
fresh cache. Reads go through the ServiceCache; when it is pre-seeded, reads are served without shelling out.
MacroService (recording)
internal/terraform/macro_service.go records every mutation as an sdk.Command without executing anything and serves
reads from the same ServiceCache. After macro playback the recorded commands are printed to stdout. Macros are
deterministic and safe: the UI renders real data from the cache, and mutations never touch infrastructure.
ServiceCache (shared state)
internal/terraform/service_cache.go is shared by both strategies:
- Pre-seeded at startup from
-plan/-state(ADR-0005):PreseedSources.Seed(cmd/tfui/sources.go) fills the cache before the service that wraps it is built - Three source kinds:
file(re-reads on invalidate),stdin(immutable),exec(cleared on invalidate) - State-mutating operations (
StateRm,StateMove,Import,Taint,Untaint) invalidate the state cache Refresh(),Init()andWorkspaceSelect()invalidate everything- Plugins bypass it with
StateList(ctx, sdk.SkipCache())for an explicit refresh (ctrl+r); the variadic option keeps cache semantics out of the interface (ADR-0007)
Source layer (internal/source/)
Resolves a URI to raw bytes; internal/terraform/loader.go parses them with LoadPlan and LoadState.
| URI | Resolves to |
|---|---|
- |
stdin |
/path, ./path, ../path |
local file |
file://... |
local file |
scheme://... |
the Provider registered for that scheme |
| anything else | an error with a suggestion |
Binary resolution
OpenTofu is supported via explicit terraform.bin = "tofu" in HCL config, or by letting terraform-exec resolve the binary from PATH. There is no auto-detection logic.
Entry Point (cmd/tfui/)
Most subcommands are build<Plugin>Command(s *Session) in their own file. Their RunE fills the plugin’s Input from
flags and calls Session.RunPlugin(ctx, "<id>", activate). workspace and force-unlock take the config instead and
run terraform directly through imperativeService(cfg). The bare tfui command calls Session.Run().
Session pipeline (session.go)
Session.Run() executes validate → LoadTape → buildService → buildRegistry → buildApp → present → emitRecorded.
RunPlugin runs the same pipeline with the app in standalone mode for one plugin.
Two orthogonal axes are resolved from flags, and every combination is valid (ADR-0006):
| Axis | Values | Determines |
|---|---|---|
| Presentation | Interactive / Headless |
A tea.Program on the alt screen, or the macro driver: for bare tfui under --macro; for a command when the mode resolution picks headless |
| Backend | Exec / Recording |
Terraform runs live (ExecService) or commands are recorded (MacroService, under --macro) |
Version
main.version comes from the release build’s -ldflags -X main.version=… (goreleaser), else from
debug.ReadBuildInfo() for go install, else 0.0.0-SNAPSHOT.
Config Resolution & Propagation
Config is resolved from tfui.hcl at three levels: root defaults → member (config.LoadChild) → workspace-specific overrides,
by config.Resolve(root, child, workspace).
ContextSwitchRequestMsg{Chdir, Workspace} (emitted by the chdir and workspace plugins)
→ requireIdle("context-switch")
→ config.LoadChild(member dir) → childCfg
→ rebuildContext(chdir, absChdir, workspace)
Service.WithDir(absChdir)
config.Resolve(rootCfg, childCfg, workspace)
→ VarFiles, Vars, Parallelism, Lock, LockTimeout
ExtraArgs from the CLI -- passthrough
Pins empty: a switch ends the targeting selection
→ replaceContext(next, reason) → ContextChangedEvent{Prev, Next, Reason}
ExtraArgs (from CLI -- passthrough) is set once at boot and carried into every snapshot.
Bubbletea Model/Update/View
┌────────────────────────────────────────┐
│ App (root model) │
│ - routes key presses to active plugin │
│ - handles global keys (q, Esc) │
│ - manages window resize │
├────────────────────────────────────────┤
│ Plugin (active) │
│ - receives Update() delegation │
│ - returns View() for content area │
│ - Init() for async data loading │
├────────────────────────────────────────┤
│ Components (header, statusbar) │
│ - shared UI chrome │
│ - rendered by App around plugin view │
└────────────────────────────────────────┘
Macro Engine (internal/macro/)
A synchronous driver for the app model plus the tape language (Macro language), used for headless runs, tests and demo recording.
| File | Role |
|---|---|
driver.go |
Drives the model without a terminal: NewDriver(app, w, h), SendKey, WaitUntil, View |
runner.go |
Executes parsed tape commands against the driver |
tape.go |
Tape parser |
recorder.go |
Wraps a tea.Model to capture ANSI frames and generate a tape (--record); headless, the runner feeds it with CaptureView() |
key_string.go |
Maps tea.KeyMsg back to tape syntax |
Testing
How each layer is tested, and the coverage gate, are in Testing.
Command Type (pkg/sdk/command.go)
Every service operation maps to a sdk.Command:
type Command struct {
Binary string // "terraform" or "tofu"
Verb string // "plan", "apply", "state rm", etc.
Args []string // positional (addresses, IDs)
Flags []string // flags like "-target=X"
Dir string // working directory
}
Every operation is one terraform command: tfui is a command builder with a visual interface. The TUI helps you construct the right terraform command. The CLI gives you a concise alternative. Both produce the same command, same outcome.
In macro mode, mutating operations are recorded as commands — the user sees what they’d need to run:
terraform state rm aws_instance.old
terraform plan -out=<planfile> -target=aws_instance.web
Data Flow: Plan → Pin → Apply
Targets go on plan, never on apply: terraform ignores -target on a saved plan file and applies the whole plan
(ADR-0019).
User presses 'p' → Plan plugin activates
→ Context().Service.Plan(ctx, Context().PlanOptions())
→ Shows changes with risk badges, plan saved to a plan file
User presses 'space' on resources → deps.Pin(...) → Context replaced with the new Pins
→ ContextChangedEvent (OnlyPinsChanged) → plan keeps its view and marks itself stale
→ the next plan runs with -target for each pin
User presses 'a' (or 'A' to auto-approve) → Plan emits ApplyRequestMsg{PlanFile, Request, AutoApprove}
→ App drops it if the plan went stale since (a pin change other than the plan's own unpin, an invalidation, or a newer plan completion)
→ App pushes plan onto navStack and activates Apply with the plan file
→ Apply shows the confirmation (skipped on AutoApprove)
User confirms → terraform apply <planfile>
→ Shows elapsed time → success/error
→ PlanInvalidatedEvent on success
→ esc returns to plan through DeactivateMsg