completion

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

completion

Tiered completion detection. See design spec §5.

Three tiers, strongest first: (1) native agent-CLI hooks wired to a side-channel, (2) prompt-engineered self-report via a file/socket marker for tool-use-capable agents without native hooks, (3) idle-time heuristic as a last resort. Agents run in native interactive mode throughout — this was a deliberate design correction from an earlier headless-mode direction that would have blocked live SSH interaction with a running agent.

Layout

  • completion.go — Tier, AgentConfig, Config (the minimal per-agent-type tier/timeout config this package needs — deliberately not the full agent-type registry spec §6 describes), and Detector (the real orchestrator.CompletionDetector implementation), which resolves a task's tier and dispatches to the matching watcher.
  • marker.go — MarkerWatcher: tiers 1 and 2 share one mechanism (watch a deterministic per-task marker file for existence) since the only difference between a native hook and a prompt-engineered self-report is how the agent was told to signal, not the detection code. Goes through TargetExecutor.FileExists/RemoveFile for both local and remote targets — one code path either way (LOOM-11), so it needs an ExecutorFactory the same way IdleWatcher already does. Also exports MarkerPath (the dir/taskID.done naming convention) and ResolveMarkerDir (configured LOOMUX_MARKER_DIR verbatim, else the per-user default $HOME/.cache/loomux/completion-markers, created 0700 on the target and refused if it's a symlink or not owned by the target user). router.Router uses both to build a launch command's env and MarkerWatcher uses them to watch, so they always agree on the path. The default is no longer a fixed /tmp/loomux/...: on a shared target another user could create that first, or plant markers in it (LOOM-75 review).
  • Process exit (LOOM-71): Detector.Wait also polls TargetExecutor.PaneExited alongside the marker/idle tier and returns *orchestrator.ProcessExitedError (exit status + final output) if the pane's process exits first. TierExit — every registry.TaskKindCommand task — completes on the exit alone.
  • idle.go — IdleWatcher: tier 3, polling TargetExecutor.CapturePane and treating "no change for the configured idle timeout" as completion. Timing is abstracted behind a small Clock/Ticker pair so idle-duration-threshold logic is testable deterministically, with no real sleeping.

Marker detection works identically for local and remote targets — Detector.resolve has no target-kind restriction; it only inspects configuration. It also never probes reachability up front, so an unreachable remote target surfaces as a plain error from Wait (same as any other TargetExecutor operation), not a special-cased fallback to idle.

Getting a task ID into the launched process (LOOM-32)

This package only ever watches for a marker file — it has no opinion on how one gets written. Making TierMarker actually functional required a separate piece, entirely in router: router.Router.launchAgent mints a task's ID before building its launch command (rather than letting orchestrator.Launch mint one afterward, which is what made TierMarker declared-but-nonfunctional until now — see router/README.md's own section), and embeds it — plus, for a TierMarker agent-type, this package's own MarkerPath for that ID — as LOOMUX_TASK_ID/ LOOMUX_MARKER_PATH env vars. The hook that reads them and touches the marker is injected by Loomux on the same command line (LOOM-75): each adapter in package agents supplies CompletionHookArgs (claude: --settings with a Stop hook; codex: -c notify=…). Nothing has to be configured on the target, and the target's own agent config is never modified. Router creates the marker directory before launch (above). The hook re-creates it (umask 077) if it's been removed.

Run go test ./... from the repo root to run the full suite, including an integration test that drives the idle heuristic against a real local tmux pane (TestIntegration_IdleWatcherRealLocalTmux), and marker tests that exercise the real remote (SSH) path via targets/sshtest — not just the scripted fake executor most of this package's tests use.

Documentation

Overview

Package completion implements the real tiered CompletionDetector (design spec §5) behind orchestrator.CompletionDetector: tiers 1+2 (native hook / prompt-engineered self-report) share one marker-watching mechanism (marker.go); tier 3 (idle-time heuristic, the true last resort) polls a task's pane for CapturePane output going quiet (idle.go). Detector (this file) resolves which tier applies to a given task and dispatches to the right one.

Index

Constants

View Source
const (
	CompactionLoopLimit  = 3
	CompactionLoopWindow = 30 * time.Minute
)

A compaction loop (LOOM-109): this many compactions in one turn, within this long.

Variables

This section is empty.

Functions

func MarkerPath

func MarkerPath(dir, taskID string) string

MarkerPath returns the deterministic marker file path for a task ID under dir — the same convention MarkerWatcher.MarkerPath applies via its own configured dir. A package-level function (LOOM-32) so a caller without a *MarkerWatcher instance (router.Router, building a launch command before any watcher is involved) can compute the exact same path a hook/notify script should be told to touch.

func ReplyPath

func ReplyPath(markerPath string) string

ReplyPath is where a TierMarker agent's completion hook saves the turn's payload — the JSON its CLI hands the hook — beside markerPath (LOOM-91), so the agent's own final message can be relayed.

func ResolveMarkerDir

func ResolveMarkerDir(ctx context.Context, exec interface {
	RunOnce(ctx context.Context, command string) (string, error)
}, configured string) (string, error)

ResolveMarkerDir returns the marker directory to use on the target behind exec. A configured directory (LOOMUX_MARKER_DIR) is returned verbatim, without touching the target. On a shared target, configure only a directory that belongs to the target user. With nothing configured, the per-user default is created and checked on the target (defaultMarkerDirScript). Both router (to tell the launched agent its LOOMUX_MARKER_PATH) and MarkerWatcher (to watch for it) resolve it this way, so they agree on the path.

Types

type AgentConfig

type AgentConfig struct {
	Tier Tier
	// IdleTimeout is only meaningful when Tier == TierIdle. Zero means
	// "use the package default."
	IdleTimeout time.Duration
	// MaxTurnDuration bounds one turn (LOOM-76): past it, Wait gives up
	// with an *orchestrator.TurnTimeoutError, the pane left running. Zero
	// means the package default (an hour); negative means unbounded.
	// Doesn't apply to TierExit, whose callers bound their own waits.
	MaxTurnDuration time.Duration
	// NoProgressTimeout, for TierMarker only, ends a turn whose pane
	// hasn't changed at all for this long while no marker came — an
	// agent blocked on an approval prompt, say (LOOM-76). Zero means the
	// package default (ten minutes); negative disables it.
	NoProgressTimeout time.Duration
	// DetectPrompt, for TierMarker only, reads the prompt an agent is
	// stopped at off its pane, nil for none (LOOM-97). A prompt showing
	// on two consecutive progress checks ends the wait with an
	// *orchestrator.NeedsAttentionError. nil disables it.
	DetectPrompt func(screen string) *registry.Attention
	// DetectCompaction, for TierMarker only, reports whether the pane
	// shows the agent compacting its context right now (LOOM-109).
	// CompactionLoopLimit compactions starting within CompactionLoopWindow
	// of one turn end the wait with an *orchestrator.CompactionLoopError:
	// an agent whose context refills as fast as it compacts never
	// finishes. nil disables it.
	DetectCompaction func(screen string) bool
}

AgentConfig is the minimal per-agent-type configuration completion detection needs. This is deliberately NOT the full agent-type registry design spec §6 describes (launch command templates, etc.) — that remains a separate, later concern. This shape will need reconciling with whatever that eventual registry looks like.

type Clock

type Clock interface {
	Now() time.Time
	NewTicker(d time.Duration) Ticker
}

Clock abstracts time so IdleWatcher's idle-duration logic is testable deterministically, with zero real sleeping. realClock (the default) is backed by the standard library; tests inject a fake via WithClock.

type Config

type Config map[string]AgentConfig

Config maps agent-type name to its AgentConfig. An agent-type with no entry — including every shell-kind task, whose AgentType is always "" — falls back to TierIdle.

type Detector

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

Detector is the real tiered orchestrator.CompletionDetector implementation.

func NewDetector

func NewDetector(store registry.Store, newExecutor orchestrator.ExecutorFactory, config Config, markerDir string, opts ...DetectorOption) *Detector

NewDetector constructs a Detector. markerDir is the configured marker directory (LOOMUX_MARKER_DIR); empty means the per-user default that ResolveMarkerDir creates on each task's target.

func (*Detector) Wait

func (d *Detector) Wait(ctx context.Context, task *registry.Task) error

Wait resolves task's detection tier and dispatches to the matching watcher. For the marker and idle tiers it also watches the pane's process (LOOM-71): if that exits first, nothing will ever signal the turn complete — an agent CLI that isn't installed writes no marker — so Wait returns an *orchestrator.ProcessExitedError at once instead of hanging (marker) or reporting a dead pane's frozen output as a finished turn (idle).

type DetectorOption

type DetectorOption func(*Detector)

DetectorOption configures a Detector.

func WithPollInterval added in v0.1.16

func WithPollInterval(d time.Duration) DetectorOption

WithPollInterval overrides how often marker, idle and exit checks poll (default a second, sized for SSH round trips). For tests against fake targets.

func WithProgressPollInterval

func WithProgressPollInterval(d time.Duration) DetectorOption

WithProgressPollInterval overrides how often the no-progress check (LOOM-76) captures the pane. Mainly for tests.

func WithUnreachableGrace added in v0.1.16

func WithUnreachableGrace(d time.Duration) DetectorOption

WithUnreachableGrace overrides how long a wait rides out a target it can't reach before failing the turn (default a minute). For tests.

type IdleWatcher

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

IdleWatcher implements design spec §5's tier 3 (idle-time heuristic): poll a task's pane and treat "no change for at least idleTimeout" as completion. The true last resort — explicitly the weakest signal in the system, not a default. Unlike MarkerWatcher, Wait here takes extra parameters beyond what orchestrator.CompletionDetector requires (the resolved target and a per-call idle timeout), so IdleWatcher does not itself implement that interface — only the top-level Detector does, dispatching to this with the resolved per-agent-type configuration.

func NewIdleWatcher

func NewIdleWatcher(newExecutor orchestrator.ExecutorFactory, pollInterval time.Duration, opts ...IdleWatcherOption) *IdleWatcher

NewIdleWatcher constructs an IdleWatcher.

func (*IdleWatcher) Wait

func (w *IdleWatcher) Wait(ctx context.Context, task *registry.Task, target *registry.Target, idleTimeout time.Duration) error

Wait blocks until target's pane output for task hasn't changed for at least idleTimeout, or ctx is done.

type IdleWatcherOption

type IdleWatcherOption func(*IdleWatcher)

IdleWatcherOption configures an IdleWatcher.

func WithClock

func WithClock(c Clock) IdleWatcherOption

WithClock overrides the Clock used for timing. Test-only hook, mirrors LOOM-4's RemoteOption pattern (targets.WithPort etc).

type MarkerWatcher

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

MarkerWatcher implements the shared mechanism behind design spec §5's tiers 1 and 2 (native hook vs. prompt-engineered self-report): watch a deterministic per-task marker file for existence. Content doesn't matter — existence is the signal — so both a native hook (a one-line `touch <path>`) and a prompt-engineered self-report (an agent with shell access told to touch the path when done) can satisfy it identically. Goes through TargetExecutor.FileExists/RemoveFile for both local and remote targets — one code path, same spirit as tiers 1+2 sharing one mechanism in the first place, rather than a raw os.Stat for local and a separate mechanism for remote (LOOM-11).

func NewMarkerWatcher

func NewMarkerWatcher(newExecutor orchestrator.ExecutorFactory, dir string, pollInterval time.Duration) *MarkerWatcher

NewMarkerWatcher constructs a MarkerWatcher. dir is the configured marker directory; empty means the per-user default, resolved on each task's target by ResolveMarkerDir.

func (*MarkerWatcher) MarkerPath

func (w *MarkerWatcher) MarkerPath(taskID string) string

MarkerPath returns the deterministic marker file path for a task ID.

func (*MarkerWatcher) Wait

func (w *MarkerWatcher) Wait(ctx context.Context, task *registry.Task, target *registry.Target) error

Wait blocks until task's marker file exists on target's filesystem, or ctx is done. On success, the marker file is removed (best-effort) so a long-running server doesn't accumulate stale marker files. Unlike the interface it partially resembles, Wait takes target explicitly — it needs it to build the right executor (local vs. remote), the same reason IdleWatcher.Wait already takes one.

type Ticker

type Ticker interface {
	C() <-chan time.Time
	Stop()
}

Ticker abstracts *time.Ticker.

type Tier

type Tier int

Tier identifies which completion-detection strategy applies. Native hooks and prompt-engineered self-report (spec §5 tiers 1 and 2) share one detection mechanism — the only difference between them is how the agent was told to signal, not the detection code — so they collapse to a single Tier value here.

const (
	// TierMarker watches a side-channel marker file (tiers 1+2).
	TierMarker Tier = iota + 1
	// TierIdle polls the pane and treats "no change for a while" as
	// completion (tier 3) — the true last resort per the design spec,
	// not a default agents opt into by omission.
	TierIdle
	// TierExit completes when the pane's process exits (LOOM-71) — design
	// spec §3's "completion for a Loomux-driven shell task is just script
	// exit". It is not configured per agent-type: every
	// registry.TaskKindCommand task uses it, and nothing else does.
	TierExit
)

Jump to

Keyboard shortcuts

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