Make Pipelines Docker-only with OpenCode and Pi

Install current verified harness releases inside Docker, preserve persistent accounts and settings, and provide separate interactive and pipeline model defaults with terminal onboarding and fuzzy pickers.

Add Docker-aware authoring transport, Pi stage execution, bounded workflow controls, reliable final-result readback and usage settlement, and finite short-lived CLI pipe draining. Keep dated installation evidence and packaged authoring guidance consistent.

Verified with a real Docker installation, both harness stages and interactive authors, the built-in plan/implement/review starter, independent host race/vet checks, installer tests, and packaged skill tests. Generated release receipts stay ignored in clean checkouts.
This commit is contained in:
2026-10-11 23:00:25 +01:00
parent c42a19f7d3
commit 05ae530442
131 changed files with 9297 additions and 355 deletions
+159 -26
View File
@@ -8,14 +8,17 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/author"
"git.a-wan.net/alan/pipelines/internal/buildinfo"
"git.a-wan.net/alan/pipelines/internal/client"
"git.a-wan.net/alan/pipelines/internal/draft"
"git.a-wan.net/alan/pipelines/internal/harness"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/runinspect"
@@ -30,13 +33,14 @@ type App struct {
In io.Reader
}
type options struct {
harness string
url, name, prompt, template, workspace, paths, key, opencode, model string
output string
conflict string
all bool
json, source, noOpen, yes, allow, createOnly, force, wait bool
version, expected int
timeout time.Duration
timeout, waitTimeout time.Duration
}
func (a App) flags(command string) (*flag.FlagSet, *options) {
@@ -48,13 +52,15 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.DurationVar(&o.timeout, "timeout", 30*time.Second, "Timeout per server request")
switch command {
case "provider-check":
f.StringVar(&o.harness, "harness", "opencode", "Provider-check harness: opencode or configured pi")
f.StringVar(&o.model, "model", envOr("PIPELINES_DEFAULT_MODEL", ""), "Provider/model to validate with one tool-free generation")
f.BoolVar(&o.yes, "yes", false, "Approve the small validation generation without prompting")
case "new", "edit":
f.StringVar(&o.harness, "harness", "", "Authoring harness: configured opencode/pi, or nvim")
f.BoolVar(&o.yes, "yes", false, "Approve draft creation/editor launch without prompting")
f.StringVar(&o.name, "name", "", "Pipeline name (or edit ID)")
f.StringVar(&o.prompt, "prompt", "", "Request to give OpenCode; omitted asks what to change")
f.BoolVar(&o.noOpen, "no-open", false, "Create the draft without opening OpenCode")
f.StringVar(&o.prompt, "prompt", "", "Request to give the configured harness; omitted asks what to change")
f.BoolVar(&o.noOpen, "no-open", false, "Create the draft without opening the configured harness")
f.StringVar(&o.opencode, "opencode", envOr("PIPELINES_OPENCODE", "opencode"), "Host OpenCode executable")
if command == "new" {
f.StringVar(&o.template, "template", "", "Optional template key; omitted starts a one-stage draft")
@@ -90,18 +96,21 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.StringVar(&o.key, "request-key", "", "Idempotency key (default: generated unique key)")
f.IntVar(&o.version, "version", 0, "Version to run (default: latest)")
f.BoolVar(&o.wait, "wait", false, "In JSON mode, wait for a terminal run state")
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait after the run is admitted (0 waits until terminal); separate from per-request --timeout")
case "runs":
f.StringVar(&o.name, "pipeline", "", "Filter by exact pipeline name or ID")
case "retry":
f.BoolVar(&o.yes, "yes", false, "Confirm retry without an interactive prompt")
f.StringVar(&o.key, "request-key", "", "Idempotency key (default: generated unique key)")
f.BoolVar(&o.wait, "wait", false, "Wait for the new run to finish")
f.DurationVar(&o.waitTimeout, "wait-timeout", 0, "Client limit for --wait (0 waits until the run ends); independent of --timeout")
case "cancel", "draft-delete":
f.BoolVar(&o.yes, "yes", false, "Confirm this action without an interactive prompt")
case "debug":
f.StringVar(&o.harness, "harness", "", "Debugging harness: configured opencode/pi, or nvim")
f.BoolVar(&o.yes, "yes", false, "Approve opening a debugging session without prompting")
f.StringVar(&o.opencode, "opencode", envOr("PIPELINES_OPENCODE", "opencode"), "Host OpenCode executable")
f.BoolVar(&o.noOpen, "no-open", false, "Print the investigation prompt without launching OpenCode")
f.BoolVar(&o.noOpen, "no-open", false, "Print the investigation prompt without launching the configured harness")
}
f.Usage = func() {
fmt.Fprintf(a.Out, "Usage: pipelines %s\n", usage[command])
@@ -167,6 +176,15 @@ func parse(f *flag.FlagSet, args []string) error {
}
func (a App) Run(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "choose-model" {
return a.chooseModel(ctx, args[1:])
}
if len(args) > 0 && args[0] == "harness" {
return a.harness(ctx, args[1:])
}
if len(args) > 0 && args[0] == "--version" {
args = append([]string{"version"}, args[1:]...)
}
// Global selectors may appear before the command as well as after it.
leading := 0
for leading < len(args) {
@@ -186,6 +204,11 @@ func (a App) Run(ctx context.Context, args []string) error {
if leading == len(args) {
return fmt.Errorf("a command is required; use pipelines help")
}
// Harness preferences are local, even when an agent's standard CLI
// prefix includes a server URL. No server mutation occurs here.
if args[leading] == "harness" {
return a.harness(ctx, args[leading+1:])
}
args = append(append([]string{}, args[leading:]...), args[:leading]...)
}
if len(args) == 0 || args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
@@ -215,10 +238,21 @@ func (a App) Run(ctx context.Context, args []string) error {
}
return err
}
if o.timeout <= 0 || o.version < 0 || o.expected < 0 {
return fmt.Errorf("timeout must be positive and versions nonnegative")
if o.timeout <= 0 || o.waitTimeout < 0 || o.version < 0 || o.expected < 0 {
return fmt.Errorf("timeout must be positive, wait-timeout nonnegative, and versions nonnegative")
}
pos := f.Args()
if command == "version" {
if len(pos) != 0 {
return fmt.Errorf("version takes no arguments")
}
build := buildinfo.Current()
if o.json {
return a.output(build)
}
fmt.Fprintf(a.Out, "pipelines %s (commit %s)\n", build.Version, build.Commit)
return nil
}
if command == "provider-check" {
if len(pos) != 0 {
return fmt.Errorf("provider-check takes no positional arguments")
@@ -230,12 +264,38 @@ func (a App) Run(ctx context.Context, args []string) error {
if err := a.confirmAction("Validate "+o.model+" with one small tool-free generation (provider charges may apply)?", o.yes); err != nil {
return err
}
config, err := harness.Load()
if err != nil {
return err
}
// A Docker-linked profile validates through its existing Compose service
// with the original cwd/model/timeout and -T for machine mode. Container
// profiles have no DockerDirectory, so the inner check cannot recurse.
if profile, ok := config.Profiles[o.harness]; ok && profile.DockerDirectory != "" {
return a.providerCheckDocker(ctx, o, profile)
}
check, cancel := context.WithTimeout(ctx, o.timeout)
defer cancel()
operations := &stage.OperationLog{}
session := ""
c := stage.OpenCodeClient{Operations: operations, OnGenerationSession: func(id, backend, reference string, active bool) error { session = id; return nil }}
text, err := c.Generate(check, stage.ModelConfig{Provider: provider, Model: model}, "Provider connection validation only. Do not use tools. Reply with exactly PIPELINES_PROVIDER_OK.")
var generator stage.ModelGenerator
switch o.harness {
case "opencode":
generator = &stage.OpenCodeClient{Operations: operations, OnGenerationSession: func(id, backend, reference string, active bool) error { session = id; return nil }}
case "pi":
profile, ok := config.Profiles["pi"]
if !ok {
return fmt.Errorf("Pi is not configured on this computer")
}
cwd, err := os.Getwd()
if err != nil {
return err
}
generator = &stage.PiClient{Executable: profile.Executable, Directory: cwd, Tools: []string{}, OnOwnership: func(id, reference string, active bool) error { session = id; return nil }}
default:
return fmt.Errorf("provider-check harness must be opencode or pi")
}
text, err := generator.Generate(check, stage.ModelConfig{Harness: o.harness, Provider: provider, Model: model}, "Provider connection validation only. Do not use tools. Reply with exactly PIPELINES_PROVIDER_OK.")
if err == nil && strings.TrimSpace(text) != "PIPELINES_PROVIDER_OK" {
err = fmt.Errorf("model returned a response but did not complete the validation instruction")
}
@@ -422,7 +482,18 @@ func (a App) Run(ctx context.Context, args []string) error {
if err != nil {
return err
}
debug := runinspect.New(response.RunDetail, executable, o.url)
// nvim is a client-side editor: keep the native host prefix. A configured
// harness (including a Docker-linked one) gets the shared Docker-aware prefix.
var prefix string
if o.harness == "nvim" {
prefix, err = harness.CLIPrefix(harness.Profile{}, o.url, executable)
} else {
prefix, err = harness.CLIPrefixFor(o.harness, o.url, executable)
}
if err != nil {
return err
}
debug := runinspect.New(response.RunDetail, prefix)
definition, definitionErr := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: response.RunDetail.PipelineID, Version: response.RunDetail.Version})
if definitionErr != nil {
debug.Prompt += "\nPinned pipeline definition unavailable: " + definitionErr.Error() + "\n"
@@ -435,7 +506,7 @@ func (a App) Run(ctx context.Context, args []string) error {
debug.Prompt += "\nServer-side live session evidence unavailable: " + evidenceErr.Error() + "\n"
} else {
data, _ := json.Marshal(live.Evidence)
debug.Prompt += "\nRead-only retained OpenCode evidence retrieved on the execution computer:\n" + string(data) + "\n"
debug.Prompt += "\nRead-only, bounded and credential-redacted OpenCode session evidence for the latest session-bearing steps, retrieved on the execution computer:\n" + string(data) + "\n"
}
if o.json {
return a.output(debug)
@@ -454,7 +525,19 @@ func (a App) Run(ctx context.Context, args []string) error {
if debug.ContextFile != "" {
fmt.Fprintln(a.Out, "Retained debugging context:", debug.ContextFile)
}
cmd := debug.Command(ctx, o.opencode)
var cmd *exec.Cmd
if o.harness == "nvim" {
debug, err = debug.PrepareFile()
if err != nil {
return err
}
cmd = exec.CommandContext(ctx, "nvim", "-R", debug.ContextFile)
} else {
cmd, err = harness.Command(ctx, o.harness, debug.Workspace, debug.Prompt, "")
if err != nil {
return err
}
}
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
@@ -564,6 +647,11 @@ func (a App) Run(ctx context.Context, args []string) error {
}
case "ping":
fmt.Fprintln(a.Out, "Connected ·", r.Time)
if r.Build != nil {
fmt.Fprintf(a.Out, "Server: %s (commit %s)\n", r.Build.Version, r.Build.Commit)
} else {
fmt.Fprintln(a.Out, "Server build: unavailable (older server)")
}
case "connection":
fmt.Fprintln(a.Out, "Server:", o.url)
for _, n := range r.NotificationEndpoints {
@@ -784,7 +872,7 @@ func (a App) author(ctx context.Context, command string, pos []string, o *option
return fmt.Errorf("pipeline already exists; use edit or choose another name")
}
}
source = pipeline.WithDefaultModel(pipeline.Template([]string{"worker"}, true), r.DefaultModel)
source = pipeline.WithDefaults(pipeline.Template([]string{"worker"}, true), r.DefaultModel, r.DefaultHarness)
if o.template != "" {
r, err := call(protocol.Message{Type: protocol.ListTemplates})
if err != nil {
@@ -805,7 +893,7 @@ func (a App) author(ctx context.Context, command string, pos []string, o *option
}
confirmation := "Create a retained draft?"
if !o.noOpen && !o.json {
confirmation = "Create a retained draft and open OpenCode?"
confirmation = "Create a retained draft and open the configured harness?"
}
if err := a.confirmAction(confirmation, o.yes); err != nil {
return err
@@ -822,14 +910,22 @@ func (a App) author(ctx context.Context, command string, pos []string, o *option
return nil
}
// Give the agent a directly executable command even in an uninstalled source tree.
executable, err := os.Executable()
if err != nil {
return err
}
cliCommand := shellQuote(executable) + " --url " + shellQuote(o.url)
cmd, err := author.Command(ctx, o.opencode, d, o.prompt, cliCommand)
if err != nil {
return err
var cmd *exec.Cmd
if o.harness == "nvim" {
cmd = exec.CommandContext(ctx, "nvim", d.Path)
} else {
executable, err := os.Executable()
if err != nil {
return err
}
cliCommand, err := harness.CLIPrefixFor(o.harness, o.url, executable)
if err != nil {
return err
}
cmd, err = author.HarnessCommand(ctx, o.harness, d, o.prompt, cliCommand)
if err != nil {
return err
}
}
cmd.Stdin = a.In
cmd.Stdout = a.Out
@@ -918,14 +1014,20 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
deadline := time.NewTimer(o.timeout)
defer deadline.Stop()
// The client wait limit is separate from the per-request --timeout.
// Reaching it never cancels or replays admitted work; the run stays active.
var deadline <-chan time.Time
if o.waitTimeout > 0 {
timer := time.NewTimer(o.waitTimeout)
defer timer.Stop()
deadline = timer.C
}
for r.RunDetail.Status == "running" || r.RunDetail.Status == "queued" {
select {
case <-ctx.Done():
return ctx.Err()
case <-deadline.C:
return fmt.Errorf("timed out waiting for run %d; it remains active", r.RunDetail.ID)
case <-deadline:
return fmt.Errorf("client wait limit reached for run %d; it remains active and was not canceled; inspect it read-only with pipelines inspect %d --json, and to keep waiting rerun with --wait reusing the original --request-key instead of starting a duplicate run", r.RunDetail.ID, r.RunDetail.ID)
case <-time.After(time.Second):
}
r, err = call(protocol.Message{Type: protocol.GetRun, RunID: r.RunDetail.ID})
@@ -946,4 +1048,35 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call
return nil
}
func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" }
// providerCheckDocker runs the provider check inside the profile's existing
// Compose service so a Docker-linked profile never falls back to a host harness.
// It streams the child's stdout/stderr and returns its exact exit code.
func (a App) providerCheckDocker(ctx context.Context, o *options, profile harness.Profile) error {
cwd, err := os.Getwd()
if err != nil {
return err
}
args := []string{
"compose", "--project-directory", profile.DockerDirectory,
"exec", "-T", "--workdir", cwd,
"pipelines", "pipelines", "provider-check",
"--harness", o.harness, "--model", o.model, "--yes", "--timeout", o.timeout.String(),
}
// Preserve the caller's output mode: a plain-text invocation must stay
// readable, while --json keeps the structured machine report.
if o.json {
args = append(args, "--json")
}
cmd := exec.CommandContext(ctx, "docker", args...)
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
if err := cmd.Run(); err != nil {
var exit *exec.ExitError
if errors.As(err, &exit) {
return &ExitError{Code: exit.ExitCode()}
}
return err
}
return nil
}
+12 -2
View File
@@ -31,6 +31,11 @@ func setup(t *testing.T) (func(...string) (string, error), *pipeline.Store, stri
t.Cleanup(func() { cancel(); http.Close(); server.WaitRuns(handler); store.Close() })
url := "ws" + strings.TrimPrefix(http.URL, "http") + "/connect"
t.Setenv("PIPELINES_DRAFT_DIR", t.TempDir())
// Isolate harness configuration: a developer's real Docker-linked profile must
// not route debug/author commands through a different service or compare its
// loopback port against this test's ephemeral server. A missing native fixture
// keeps the host executable authoritative, matching unconfigured setups.
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(t.TempDir(), "harnesses.json"))
return func(args ...string) (string, error) {
if len(args) > 0 && (args[0] == "submit" || args[0] == "new" || args[0] == "edit") {
args = append(args, "--yes")
@@ -187,6 +192,12 @@ func TestCLIAuthorOpenCodeReferencesGlobalSkillAndLeavesDraft(t *testing.T) {
capture := filepath.Join(root, "invocation")
script := filepath.Join(root, "opencode")
os.WriteFile(script, []byte("#!/bin/sh\nif [ \"$1\" = --help ]; then printf '%s\\n' ' api commands'; exit 0; fi\nif [ \"$1\" = api ]; then\n if [ \"$3\" = /api/session ]; then printf '%s' '{\"data\":{\"id\":\"ses_test\"}}'; fi\n exit 0\nfi\nprintf '%s\\n' \"$@\" > "+"'"+capture+"'"+"\n"), 0700)
configPath := filepath.Join(root, "harnesses.json")
t.Setenv("PIPELINES_HARNESS_CONFIG", configPath)
configData, _ := json.Marshal(map[string]any{"default": "opencode", "profiles": map[string]any{"opencode": map[string]string{"executable": script, "model": "fixture/model", "pipeline_model": "fixture/model"}}})
if err := os.WriteFile(configPath, configData, 0600); err != nil {
t.Fatal(err)
}
if _, err := run("new", "scoped skill", "Make a digest", "--opencode", script); err != nil {
t.Fatal(err)
}
@@ -194,8 +205,7 @@ func TestCLIAuthorOpenCodeReferencesGlobalSkillAndLeavesDraft(t *testing.T) {
if err != nil {
t.Fatal(err)
}
parts := strings.SplitN(string(data), "\n", 3)
if parts[1] != "--prompt" || !strings.HasPrefix(parts[2], "@pipelines") || !strings.Contains(parts[2], "Make a digest") {
if !strings.HasPrefix(string(data), "mini\n--model\nfixture/model\n--prompt\n@pipelines") || !strings.Contains(string(data), "Make a digest") {
t.Fatal(string(data))
}
skillDir, err := author.SkillDirectory()
+12 -8
View File
@@ -16,14 +16,15 @@ var usage = map[string]string{
"import": "import [FILE.zip] [--all] [--on-conflict ask|keep|both|import] [--yes] [--json]",
"templates": "templates [--json]",
"template": "template <key> [--source | --json]",
"run": "run [name|id] [prompt] [--json [--wait]]",
"run": "run [name|id] [prompt] [--json [--wait [--wait-timeout DURATION]]]",
"runs": "runs [--pipeline NAME] [--json]",
"inspect": "inspect <run-id> [--json]",
"cancel": "cancel <run-id> [--json]",
"retry": "retry <run-id> [--json] [--wait]",
"retry": "retry <run-id> [--json [--wait [--wait-timeout DURATION]]]",
"debug": "debug <run-id> [--json | --no-open]",
"connection": "connection [--json]",
"ping": "ping [--json]",
"version": "version [--json]",
"status": "status [--json]",
"stats": "stats [--json]",
"rpc": "rpc <request.json|->",
@@ -31,20 +32,23 @@ var usage = map[string]string{
}
var notes = map[string]string{
"version": "Identify the local CLI binary without connecting to a server. --version is an alias. Use ping --json to identify the running server separately.",
"ping": "Pong includes the running server's compiled build.version, build.commit and build.dirty (null when unknown). This identifies the server, not the client or runtime workspace. Older servers omit build.",
"export": "Without a name, select pipelines with Space and save a ZIP in the current directory. --output writes a portable definition bundle; --all skips selection. One name without --output prints Markdown as before. No runs, credentials or old versions are exported.",
"import": "Select definitions from a ZIP. Identical existing definitions are skipped. For differing names, choose keep existing, keep both under a new name, or use imported as a new version (history retained). --on-conflict supplies an explicit automation policy; --yes only approves final publication. Schedules may activate; no run history is imported.",
"new": "Create an optional template copy or a one-stage starter. Opens OpenCode with @pipelines; the skill asks any missing questions, including the name. No submission is performed.",
"edit": "Omit the name to open fuzzy selection. Original immutable source is copied to a private draft. OpenCode edits that draft, never the live definition.",
"new": "Create an optional template copy or a one-stage starter. Opens the configured default harness; --harness opencode|pi|nvim overrides it. No submission is performed.",
"edit": "Omit the name to open fuzzy selection. Original immutable source is copied to a private draft. The configured harness edits that draft, never the live definition.",
"validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.",
"submit": "Confirm publication at the prompt, or use --yes for explicit automation; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits.",
"retry": "Start a new attempt of a failed run with the same initial input, directory, pipeline version, and edit scope. Original history is retained. Already-completed side effects are not undone.",
"debug": "Open a fresh OpenCode conversation to investigate a run using inspect/show/runs CLI queries. Does not resume the implementing session or retry the run. --json returns the investigation prompt without opening OpenCode.",
"run": "Runs in your current directory after action confirmation (--yes skips it). Select a pipeline and compose a multiline task with Ctrl+S. Stage tools are enabled automatically; no file list or typed RUN confirmation. Cancellation does not undo edits. In JSON mode --wait polls until terminal; --wait-timeout bounds only the client wait after admission and is independent of per-request --timeout. A reached wait limit leaves the run active: inspect read-only with `inspect <run-id> --json`, or reattach with --wait reusing the original --request-key (never an automatic replay or cancel).",
"retry": "Start a new attempt of a failed run with the same initial input, directory, pipeline version, and edit scope. Original history is retained. Already-completed side effects are not undone. --wait/--wait-timeout behave as for run: a reached wait limit leaves the new run active; inspect read-only with `inspect <run-id> --json`, or reattach with --wait and the original --request-key instead of starting a duplicate retry.",
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs.",
}
var serviceHelp = map[string]string{
"skill": "pipelines skill install installs/updates the bundled global OpenCode skill without changing login/config or user-modified skills. install.sh includes this step.",
"harness": "pipelines harness launches the configured default. harness setup opencode|pi offers fuzzy model selection; --login reopens login, --default chooses the default harness, --model and --pipeline-model set separate defaults explicitly. harness list prints non-secret settings. Only configured harnesses are offered.",
"skill": "pipelines skill install installs/updates the bundled global OpenCode skill without changing login/config or user-modified skills. ./install includes this step.",
"service": "Configure per-user OS autostart: pipelines service enable. Runs use the directory you invoke pipelines run from. Use --print to preview, service status to inspect, and service disable before uninstalling. Linux uses systemd; macOS uses launchd. No sudo.",
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
+1 -1
View File
@@ -44,7 +44,7 @@ func TestDebugIncludesPinnedDefinitionAndRecordedFailure(t *testing.T) {
if err = json.Unmarshal([]byte(output), &debug); err != nil {
t.Fatal(err)
}
for _, expected := range []string{"original task for diagnosis", "recorded provider failure", "original-worker", "Exact immutable pipeline definition", "Read-only retained OpenCode evidence retrieved on the execution computer"} {
for _, expected := range []string{"original task for diagnosis", "recorded provider failure", "original-worker", "Exact immutable pipeline definition", "bounded and credential-redacted OpenCode session evidence"} {
if !strings.Contains(debug.Prompt, expected) {
t.Fatal("missing debug context", expected, debug.Prompt)
}
+12
View File
@@ -0,0 +1,12 @@
package cli
import "fmt"
// ExitError carries a dispatched subprocess exit code so the CLI can propagate the
// exact status. The child already streamed its own stdout/stderr, so main exits
// with this code without printing a duplicate diagnostic.
type ExitError struct{ Code int }
func (e *ExitError) Error() string { return fmt.Sprintf("subprocess exited with status %d", e.Code) }
func (e *ExitError) ExitCode() int { return e.Code }
+318
View File
@@ -0,0 +1,318 @@
package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/author"
"git.a-wan.net/alan/pipelines/internal/harness"
)
func (a App) harness(ctx context.Context, args []string) error {
if len(args) > 0 && args[0] == "list" {
c, err := harness.Load()
if err != nil {
return err
}
return a.output(c)
}
if len(args) > 0 && args[0] == "default" {
c, err := harness.Load()
if err != nil {
return err
}
names, _, err := harness.Choices()
if err != nil {
return err
}
name := ""
if len(args) == 2 {
name = args[1]
} else if len(args) == 1 {
name, err = harness.Select(ctx, "Default harness", names, a.In, a.Err)
if err != nil {
return err
}
} else {
return fmt.Errorf("usage: harness default [opencode|pi]")
}
if _, ok := c.Profiles[name]; !ok {
return fmt.Errorf("harness %q is not configured", name)
}
c.Default = name
return harness.Save(c)
}
if len(args) > 0 && args[0] == "link" {
f := flag.NewFlagSet("harness link", flag.ContinueOnError)
f.SetOutput(a.Err)
directory := f.String("docker-directory", "", "Existing Docker installation checkout")
model := f.String("model", "", "Configured interactive model")
pipelineModel := f.String("pipeline-model", "", "Configured new-pipeline model")
makeDefault := f.Bool("default", false, "Set default harness")
if err := parse(f, args[1:]); err != nil {
return err
}
if len(f.Args()) != 1 || (f.Args()[0] != "pi" && f.Args()[0] != "opencode") || !harness.ValidModel(*model) || !harness.ValidModel(*pipelineModel) {
return fmt.Errorf("harness link requires opencode|pi and exact --model/--pipeline-model")
}
absolute, err := filepath.Abs(*directory)
if err != nil || *directory == "" {
return fmt.Errorf("Docker installation directory is required")
}
if _, err := os.Stat(filepath.Join(absolute, "compose.yaml")); err != nil {
return err
}
c, err := harness.Load()
if err != nil {
return err
}
name := f.Args()[0]
c.Profiles[name] = harness.Profile{Executable: name, Model: *model, PipelineModel: *pipelineModel, DockerDirectory: absolute}
if *makeDefault || c.Default == "" {
c.Default = name
}
return harness.Save(c)
}
if len(args) > 0 && args[0] == "setup" {
f := flag.NewFlagSet("harness setup", flag.ContinueOnError)
f.SetOutput(a.Err)
model := f.String("model", "", "Interactive harness default provider/model")
pipelineModel := f.String("pipeline-model", "", "New pipeline stage default provider/model")
executable := f.String("executable", "", "Harness executable (defaults to its name)")
login := f.Bool("login", false, "Open the harness login without deleting credentials")
makeDefault := f.Bool("default", false, "Use this harness by default")
versions := f.String("versions", "", "Verified Docker harness versions to display (from the in-image probe)")
if err := parse(f, args[1:]); err != nil {
return err
}
if len(f.Args()) > 1 {
return fmt.Errorf("usage: pipelines harness setup [opencode|pi] [--login] [--model P/M] [--pipeline-model P/M] [--default]")
}
name := ""
if len(f.Args()) == 1 {
name = f.Args()[0]
} else {
var available []string
for _, name := range []string{"opencode", "pi"} {
if _, err := exec.LookPath(name); err == nil {
available = append(available, name)
}
}
var err error
name, err = harness.Select(ctx, "Harness to configure", available, a.In, a.Err)
if err != nil {
return err
}
}
if name != "opencode" && name != "pi" {
return fmt.Errorf("supported harnesses: opencode, pi")
}
if *executable == "" {
*executable = name
}
if strings.ContainsRune(*executable, os.PathSeparator) {
absolute, pathErr := filepath.Abs(*executable)
if pathErr != nil {
return pathErr
}
*executable = absolute
}
if _, err := exec.LookPath(*executable); err != nil {
return fmt.Errorf("install %s before configuring it: %w", name, err)
}
c, err := harness.Load()
if err != nil {
return err
}
onboarding := harness.NewOnboarding(a.Out)
action := "Configure"
if _, ok := c.Profiles[name]; ok {
action = "Reconfigure"
}
onboarding.Header(name, action)
onboarding.Versions(*versions)
if *login {
switch name {
case "opencode":
warm, cancel := context.WithTimeout(ctx, 30*time.Second)
_, warmErr := exec.CommandContext(warm, *executable, "api", "get", "/api/integration").Output()
cancel()
if warmErr != nil {
return fmt.Errorf("OpenCode provider discovery failed before login: %w", warmErr)
}
case "pi":
onboarding.AuthHandoff()
}
// Pi has no standalone `auth login`: open a fresh, no-context,
// extension-free, no-prompt, no-tools session and let the user run
// /login there. `--tui-mode regular` is a documented Pi 1.1.0 flag
// that keeps Pipelines' header/handoff visible above Pi's interface
// instead of the default fullscreen clear. Never inject a coding/task
// prompt or scripted keystrokes.
loginArgs := []string{"auth", "login"}
if name == "pi" {
loginArgs = []string{"--tui-mode", "regular", "--no-extensions", "--no-skills", "--no-context-files", "--no-prompt-templates", "--no-tools"}
}
cmd := exec.CommandContext(ctx, *executable, loginArgs...)
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
if err := cmd.Run(); err != nil {
return fmt.Errorf("%s login did not complete: %w", name, err)
}
}
readCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
models, err := harnessModels(readCtx, name, *executable)
if err != nil {
return err
}
if *model == "" {
*model, err = harness.Pick(ctx, harness.Selection{
Step: "Step 1 of 2",
Title: "Choose the interactive " + harness.DisplayName(name) + " model",
Purpose: "Used when you open " + harness.DisplayName(name) + " for authoring and debugging sessions. It is stored separately from the new-pipeline-stage model.",
Options: models,
Current: c.Profiles[name].Model,
}, a.In, a.Err)
if err != nil {
return err
}
}
if *pipelineModel == "" {
*pipelineModel, err = harness.Pick(ctx, harness.Selection{
Step: "Step 2 of 2",
Title: "Choose the default model for new " + harness.DisplayName(name) + " pipelines",
Purpose: "Used by model stages in new pipelines and starters. It never rewrites published workflows or existing drafts.",
Options: models,
Current: c.Profiles[name].PipelineModel,
}, a.In, a.Err)
if err != nil {
return err
}
}
available := func(value string) bool {
for _, m := range models {
if m == value {
return true
}
}
return false
}
if !harness.ValidModel(*model) || !harness.ValidModel(*pipelineModel) || !available(*model) || !available(*pipelineModel) {
return fmt.Errorf("choose exact model IDs from %s's available catalog; defaults unchanged", name)
}
profile := c.Profiles[name]
profile.Executable, profile.Model, profile.PipelineModel = *executable, *model, *pipelineModel
c.Profiles[name] = profile
if *makeDefault || c.Default == "" {
c.Default = name
}
if err = harness.Save(c); err != nil {
return err
}
onboarding.Summary(name, *model, *pipelineModel, c.Default)
return nil
}
name := ""
if len(args) > 0 && (args[0] == "opencode" || args[0] == "pi") {
name = args[0]
args = args[1:]
}
cwd, err := os.Getwd()
if err != nil {
return err
}
skill, err := author.SkillDirectory()
if err != nil {
return err
}
cmd, err := harness.Command(ctx, name, cwd, strings.Join(args, " "), skill)
if err != nil {
return err
}
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
return cmd.Run()
}
func harnessModels(ctx context.Context, name, executable string) ([]string, error) {
if name == "opencode" {
if _, err := exec.CommandContext(ctx, executable, "api", "get", "/api/integration").Output(); err != nil {
return nil, fmt.Errorf("OpenCode provider discovery failed: %w", err)
}
}
args := []string{"models"}
if name == "pi" {
args = []string{"--no-extensions", "--list-models"}
}
data, err := exec.CommandContext(ctx, executable, args...).Output()
if err != nil {
return nil, fmt.Errorf("%s model discovery failed: %w", name, err)
}
if name == "opencode" {
for attempt := 0; len(strings.TrimSpace(string(data))) == 0 && attempt < 2; attempt++ {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(500 * time.Millisecond):
}
data, err = exec.CommandContext(ctx, executable, args...).Output()
if err != nil {
return nil, err
}
}
}
var models []string
seen := map[string]bool{}
for _, line := range strings.Split(string(data), "\n") {
fields := strings.Fields(line)
if len(fields) == 0 {
continue
}
value := fields[0]
if name == "pi" && len(fields) > 1 {
value = fields[0] + "/" + fields[1]
}
if harness.ValidModel(value) && !seen[value] && value != "provider/model" {
seen[value] = true
models = append(models, value)
}
}
if name == "opencode" {
data, err := exec.CommandContext(ctx, executable, "auth", "list", "--format", "json").Output()
if err != nil {
return nil, fmt.Errorf("OpenCode connected-provider discovery failed: %w", err)
}
var accounts []struct {
ID string `json:"id"`
Connections []json.RawMessage `json:"connections"`
}
if err = json.Unmarshal(data, &accounts); err != nil {
return nil, err
}
connected := map[string]bool{}
for _, a := range accounts {
if len(a.Connections) > 0 {
connected[a.ID] = true
}
}
filtered := models[:0]
for _, m := range models {
p, _, _ := strings.Cut(m, "/")
if connected[p] {
filtered = append(filtered, m)
}
}
models = filtered
}
return models, nil
}
+105
View File
@@ -0,0 +1,105 @@
package cli
import (
"bytes"
"context"
"git.a-wan.net/alan/pipelines/internal/harness"
"os"
"path/filepath"
"strings"
"testing"
)
func TestHarnessSetupSeparateDefaultsAndNoInference(t *testing.T) {
root := t.TempDir()
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(root, "harnesses.json"))
script := filepath.Join(root, "opencode")
if err := os.WriteFile(script, []byte("#!/bin/sh\ncase \"$*\" in\n'api get /api/integration') echo '{}' ;;\nmodels) printf '%s\\n' fixture/harness fixture/stages disconnected/model;;\n'auth list --format json') echo '[{\"id\":\"fixture\",\"connections\":[{}]}]' ;;\n*) exit 91;;\nesac\n"), 0700); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
app := App{In: bytes.NewBuffer(nil), Out: &out, Err: &out}
if err := app.Run(context.Background(), []string{"harness", "setup", "opencode", "--executable", script, "--model", "fixture/harness", "--pipeline-model", "fixture/stages", "--default"}); err != nil {
t.Fatal(err)
}
c, err := harness.Load()
if err != nil || c.Default != "opencode" || c.Profiles["opencode"].PipelineModel != "fixture/stages" {
t.Fatal(c, err)
}
before, _ := os.ReadFile(filepath.Join(root, "harnesses.json"))
if err := app.Run(context.Background(), []string{"harness", "setup", "opencode", "--executable", script, "--model", "disconnected/model", "--pipeline-model", "fixture/stages"}); err == nil {
t.Fatal("disconnected model accepted")
}
after, _ := os.ReadFile(filepath.Join(root, "harnesses.json"))
if !bytes.Equal(before, after) {
t.Fatal("failed setup changed defaults")
}
}
func TestHarnessSetupNonTerminalMissingModelFailsClearly(t *testing.T) {
root := t.TempDir()
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(root, "harnesses.json"))
script := filepath.Join(root, "opencode")
if err := os.WriteFile(script, []byte("#!/bin/sh\ncase \"$*\" in\n'api get /api/integration') echo '{}' ;;\nmodels) printf '%s\\n' fixture/harness fixture/stages ;;\n'auth list --format json') echo '[{\"id\":\"fixture\",\"connections\":[{}]}]' ;;\n*) exit 91;;\nesac\n"), 0700); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
app := App{In: bytes.NewBuffer(nil), Out: &out, Err: &out}
err := app.Run(context.Background(), []string{"harness", "setup", "opencode", "--executable", script})
if err == nil || !strings.Contains(err.Error(), "requires a terminal") {
t.Fatalf("non-terminal missing-model error = %v", err)
}
if _, statErr := os.Stat(filepath.Join(root, "harnesses.json")); !os.IsNotExist(statErr) {
t.Fatal("failed non-terminal setup wrote defaults")
}
}
func TestPiLoginHandoffOpensFreshSessionWithoutTaskPrompt(t *testing.T) {
root := t.TempDir()
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(root, "harnesses.json"))
t.Setenv("FIXTURE", root)
script := filepath.Join(root, "pi")
if err := os.WriteFile(script, []byte("#!/bin/sh\ncase \"$*\" in\n'--no-extensions --list-models') printf '%s\\n' provider/interactive provider/stages ;;\n'--tui-mode regular --no-extensions --no-skills --no-context-files --no-prompt-templates --no-tools') printf '%s\\n' \"$@\" >> \"$FIXTURE/pi-login\" ;;\n*) exit 91 ;;\nesac\n"), 0700); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
app := App{In: bytes.NewBuffer(nil), Out: &out, Err: &out}
if err := app.Run(context.Background(), []string{"harness", "setup", "pi", "--executable", script, "--login", "--model", "provider/interactive", "--pipeline-model", "provider/stages", "--default"}); err != nil {
t.Fatal(err)
}
logged, err := os.ReadFile(filepath.Join(root, "pi-login"))
if err != nil {
t.Fatal("pi login session was not opened")
}
wantArgs := "--tui-mode regular --no-extensions --no-skills --no-context-files --no-prompt-templates --no-tools"
if got := strings.Join(strings.Fields(string(logged)), " "); got != wantArgs {
t.Fatalf("pi login args = %q; expected a fresh no-context, no-prompt, no-tools session", got)
}
text := out.String()
for _, want := range []string{"Pi sign-in", "/login", "authentication method", "Sign in with an API key", "ctrl+c/ctrl+d", "reuse them", "provider sign-in", "account/API key/Radius", "provider/interactive", "provider/stages", "Configuration complete"} {
if !strings.Contains(text, want) {
t.Fatalf("missing %q in handoff output:\n%s", want, text)
}
}
c, err := harness.Load()
if err != nil || c.Default != "pi" || c.Profiles["pi"].Model != "provider/interactive" || c.Profiles["pi"].PipelineModel != "provider/stages" {
t.Fatal(c, err)
}
}
func TestHarnessSetupShowsVerifiedVersions(t *testing.T) {
root := t.TempDir()
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(root, "harnesses.json"))
script := filepath.Join(root, "opencode")
if err := os.WriteFile(script, []byte("#!/bin/sh\ncase \"$*\" in\n'api get /api/integration') echo '{}' ;;\nmodels) printf '%s\\n' fixture/harness fixture/stages ;;\n'auth list --format json') echo '[{\"id\":\"fixture\",\"connections\":[{}]}]' ;;\n*) exit 91;;\nesac\n"), 0700); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
app := App{In: bytes.NewBuffer(nil), Out: &out, Err: &out}
if err := app.Run(context.Background(), []string{"harness", "setup", "opencode", "--executable", script, "--versions", "OpenCode 2.0.26 · Pi 1.1.0 · Node 22.19.0", "--model", "fixture/harness", "--pipeline-model", "fixture/stages"}); err != nil {
t.Fatal(err)
}
if text := out.String(); !strings.Contains(text, "OpenCode 2.0.26") || !strings.Contains(text, "Docker image harnesses:") {
t.Fatalf("verified versions not shown:\n%s", text)
}
}
+13 -7
View File
@@ -5,8 +5,8 @@ const help = `PIPELINES — reusable workflows for your repositories
Usage: pipelines <command> [arguments] [options]
AUTHOR
new [name] [prompt] Create a draft and open OpenCode with @pipelines
edit [name|id] [prompt] Pick a pipeline, draft changes, open OpenCode
new [name] [prompt] Create a draft and open the configured harness
edit [name|id] [prompt] Pick a pipeline, draft changes, open a configured harness
drafts List retained draft files (including TUI drafts)
validate <draft.md> Check a draft using the server's validator
submit <draft.md> Explicitly publish a new immutable version
@@ -15,7 +15,8 @@ BROWSE
list List registered pipelines
show <name|id> Inspect graph, settings, source and history
versions <name|id> List immutable versions
export <name|id> Print original Markdown source
export [name|id ...] Select/export definitions as ZIP; one name prints Markdown
import [FILE.zip] Select/import definitions; explicitly resolve conflicts
templates List optional templates (never seeds the DB)
template <key> Inspect a template; --source prints Markdown
@@ -26,20 +27,23 @@ EXECUTE
inspect <run-id> Inspect stages, outputs, errors and status
cancel <run-id> Cancel a run; changes are NOT rolled back
retry <run-id> Restart a failed run with its original input and directory
debug <run-id> Ask OpenCode questions about a recorded or active run
debug <run-id> Investigate a run with a configured harness or nvim
draft-delete <draft.md> Delete a selected retained draft and its metadata
connection Server and public phone connection (no secrets)
status Server/ntfy health, ports and server computer IPs
stats All-history usage, pipeline counts and daily activity
ping Check the server connection
ping Check connection and identify the running server build
version Identify this CLI build without connecting (--version)
rpc <request.json|-> Send any protocol command (automation escape hatch)
SERVER / INTERFACE
harness [opencode|pi] Launch the configured default harness in this directory
harness setup opencode|pi Login/select separate harness and new-pipeline defaults
tui Open the dashboard (default with no command)
serve Start native server in the foreground (Ctrl+C stops it)
service enable Configure user autostart
service disable | status Stop/remove autostart, or inspect OS service status
skill install Install/update the shared OpenCode authoring skill
skill install Install/update the shared Pi/OpenCode authoring skill
uninstall [--yes] Remove verified Go binaries; retain data and drafts
Legacy managed installs: select PIPELINES_PREFIX explicitly for start/stop,
@@ -56,7 +60,9 @@ Examples:
pipelines submit /path/to/draft.md
pipelines run "bug fix" "Fix the layout" --json
Draft-first: OpenCode edits a private draft; nothing is published automatically.
Draft-first: the configured harness (Pi/OpenCode, Docker-linked by default) edits a
private draft; non-Docker installs use a native harness and nvim remains a client
editor. Nothing is published automatically.
Every submission is validated server-side. Submission activates any schedules.
JSON mode never launches an editor or picker; supply explicit arguments.
`
+60
View File
@@ -0,0 +1,60 @@
package cli
import (
"context"
"encoding/json"
"flag"
"fmt"
"git.a-wan.net/alan/pipelines/internal/harness"
"os"
)
// choose-model is used by the installer without piping over its interactive input.
func (a App) chooseModel(ctx context.Context, args []string) error {
f := flag.NewFlagSet("choose-model", flag.ContinueOnError)
f.SetOutput(a.Err)
options := f.String("options-file", "", "JSON array of available exact model IDs")
output := f.String("output", "", "Private new file for the chosen model")
title := f.String("title", "Choose model", "Picker title")
purpose := f.String("purpose", "", "Explanation of this model's purpose")
step := f.String("step", "", "Step label such as 'Step 1 of 2'")
current := f.String("current", "", "Saved model to preselect")
if err := f.Parse(args); err != nil {
return err
}
if *options == "" || *output == "" || len(f.Args()) > 0 {
return fmt.Errorf("choose-model requires --options-file and --output")
}
data, err := os.ReadFile(*options)
if err != nil {
return err
}
var models []string
if len(data) > 1<<20 || json.Unmarshal(data, &models) != nil {
return fmt.Errorf("invalid model catalog")
}
for _, m := range models {
if !harness.ValidModel(m) {
return fmt.Errorf("invalid model ID %q", m)
}
}
selected, err := harness.Pick(ctx, harness.Selection{
Title: *title,
Purpose: *purpose,
Step: *step,
Options: models,
Current: *current,
}, a.In, a.Out)
if err != nil {
return err
}
file, err := os.OpenFile(*output, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return err
}
if _, err = file.WriteString(selected + "\n"); err != nil {
file.Close()
return err
}
return file.Close()
}
+3
View File
@@ -11,6 +11,9 @@ import (
)
func TestProviderCheckExecutesGenerationAndReportsFailures(t *testing.T) {
// Isolate harness settings so an unrelated developer profile cannot route the
// native check through Docker.
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(t.TempDir(), "harnesses.json"))
for _, fail := range []bool{false, true} {
bin := filepath.Join(t.TempDir(), "opencode")
script := `#!/bin/sh
+143
View File
@@ -0,0 +1,143 @@
package cli_test
import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/cli"
)
// fixtureDocker installs a fake docker and a fake host opencode. It returns the
// captured-arguments path and the host-openCode marker path.
func fixtureDocker(t *testing.T, exitCode int) (capture, opencodeMarker string) {
t.Helper()
root := t.TempDir()
capture = filepath.Join(root, "docker-args")
docker := filepath.Join(root, "docker")
script := "#!/bin/sh\nprintf '%s\\n' \"$@\" > " + capture + "\nprintf '{\"healthy\":true,\"session_id\":\"ses_docker\"}'\nexit " + strconv.Itoa(exitCode) + "\n"
if err := os.WriteFile(docker, []byte(script), 0700); err != nil {
t.Fatal(err)
}
opencodeMarker = filepath.Join(root, "opencode-called")
opencode := filepath.Join(root, "opencode")
if err := os.WriteFile(opencode, []byte("#!/bin/sh\ntouch "+opencodeMarker+"\nexit 9\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", root+string(os.PathListSeparator)+os.Getenv("PATH"))
return capture, opencodeMarker
}
func dockerLinkedConfig(t *testing.T, harness string) {
t.Helper()
path := filepath.Join(t.TempDir(), "harnesses.json")
config := `{"default":"` + harness + `","profiles":{"` + harness + `":{"executable":"` + harness + `","model":"fixture/model","pipeline_model":"fixture/model","docker_directory":"/checkout"}}}`
if err := os.WriteFile(path, []byte(config), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_HARNESS_CONFIG", path)
}
func TestProviderCheckDispatchesDockerProfileWithoutHostGeneration(t *testing.T) {
capture, opencodeMarker := fixtureDocker(t, 0)
dockerLinkedConfig(t, "opencode")
var out, stderr bytes.Buffer
app := cli.App{Out: &out, Err: &stderr, In: strings.NewReader("")}
err := app.Run(context.Background(), []string{"provider-check", "--model", "fixture/test", "--json", "--yes", "--timeout", "45s"})
if err != nil {
t.Fatal(err, stderr.String())
}
if !strings.Contains(out.String(), "ses_docker") {
t.Fatalf("docker stdout not forwarded: %q", out.String())
}
if _, statErr := os.Stat(opencodeMarker); !os.IsNotExist(statErr) {
t.Fatal("host OpenCode generator was invoked for a Docker-linked profile")
}
data, err := os.ReadFile(capture)
if err != nil {
t.Fatal(err)
}
args := string(data)
for _, want := range []string{"compose", "--project-directory", "/checkout", "exec", "-T", "--workdir", "pipelines", "provider-check", "--harness", "opencode", "--model", "fixture/test", "--yes", "--json", "--timeout", "45s"} {
if !strings.Contains(args, want) {
t.Fatalf("docker dispatch missing %q in %q", want, args)
}
}
}
func TestProviderCheckDockerPropagatesExitCode(t *testing.T) {
fixtureDocker(t, 3)
dockerLinkedConfig(t, "pi")
var out, stderr bytes.Buffer
app := cli.App{Out: &out, Err: &stderr, In: strings.NewReader("")}
err := app.Run(context.Background(), []string{"provider-check", "--harness", "pi", "--model", "fixture/test", "--json", "--yes"})
var exit *cli.ExitError
if !errors.As(err, &exit) || exit.ExitCode() != 3 {
t.Fatalf("exit code not propagated: %v", err)
}
}
// TestProviderCheckDockerTextModeOmitsJSON pins that a plain-text invocation
// keeps readable output: the Docker child is not forced into --json.
func TestProviderCheckDockerTextModeOmitsJSON(t *testing.T) {
capture, opencodeMarker := fixtureDocker(t, 0)
dockerLinkedConfig(t, "opencode")
var out, stderr bytes.Buffer
app := cli.App{Out: &out, Err: &stderr, In: strings.NewReader("")}
if err := app.Run(context.Background(), []string{"provider-check", "--model", "fixture/test", "--yes"}); err != nil {
t.Fatal(err, stderr.String())
}
if !strings.Contains(out.String(), "ses_docker") {
t.Fatalf("docker stdout not forwarded: %q", out.String())
}
if _, statErr := os.Stat(opencodeMarker); !os.IsNotExist(statErr) {
t.Fatal("host OpenCode generator was invoked for a Docker-linked profile")
}
data, err := os.ReadFile(capture)
if err != nil {
t.Fatal(err)
}
args := string(data)
for _, want := range []string{"exec", "-T", "provider-check", "--harness", "opencode", "--model", "fixture/test", "--yes", "--timeout"} {
if !strings.Contains(args, want) {
t.Fatalf("docker dispatch missing %q in %q", want, args)
}
}
if strings.Contains(args, "--json") {
t.Fatalf("text-mode dispatch forced --json: %q", args)
}
}
func TestProviderCheckNativeProfileKeepsHostGenerator(t *testing.T) {
root := t.TempDir()
marker := filepath.Join(root, "opencode-called")
opencode := filepath.Join(root, "opencode")
// The native generator runs the host opencode; this fixture echoes a healthy
// report so the test needs no provider.
script := "#!/bin/sh\ntouch " + marker + "\ncase \"$*\" in\n *--help*) echo api;;\n *'/api/session/ses_check/generate'*) echo '{\"data\":{\"text\":\"PIPELINES_PROVIDER_OK\"}}';;\n *'/api/session/ses_check/interrupt'*) echo '{}';;\n *'/api/session'*) echo '{\"data\":{\"id\":\"ses_check\"}}';;\n *) exit 9;;\nesac\n"
if err := os.WriteFile(opencode, []byte(script), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_OPENCODE", opencode)
path := filepath.Join(t.TempDir(), "harnesses.json")
if err := os.WriteFile(path, []byte(`{"default":"opencode","profiles":{"opencode":{"executable":"`+opencode+`","model":"fixture/model","pipeline_model":"fixture/model"}}}`), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("PIPELINES_HARNESS_CONFIG", path)
var out, stderr bytes.Buffer
app := cli.App{Out: &out, Err: &stderr, In: strings.NewReader("")}
if err := app.Run(context.Background(), []string{"provider-check", "--model", "fixture/test", "--json", "--yes"}); err != nil {
t.Fatal(err, stderr.String())
}
if _, err := os.Stat(marker); err != nil {
t.Fatal("native profile did not use the host generator:", err)
}
if !strings.Contains(out.String(), "ses_check") {
t.Fatalf("native generator output missing: %q", out.String())
}
}
+35
View File
@@ -0,0 +1,35 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"strings"
"testing"
"git.a-wan.net/alan/pipelines/internal/buildinfo"
)
func TestVersionIsOffline(t *testing.T) {
t.Setenv("PIPELINES_URL", "not-a-websocket-url")
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
for _, args := range [][]string{{"version", "--json"}, {"--version", "--json"}, {"version"}} {
var out bytes.Buffer
app := App{Out: &out, Err: &out, In: strings.NewReader("")}
if err := app.Run(context.Background(), args); err != nil {
t.Fatal(err)
}
want := buildinfo.Current()
if args[len(args)-1] == "--json" {
var got buildinfo.Info
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.Version != want.Version || got.Commit != want.Commit {
t.Fatal("wrong CLI identity", got)
}
} else if !strings.Contains(out.String(), "pipelines "+want.Version) {
t.Fatal(out.String())
}
}
}
+111
View File
@@ -0,0 +1,111 @@
package cli
import (
"bytes"
"context"
"strings"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// The client --wait limit must not reuse the per-request --timeout, and reaching
// it must leave admitted work active rather than canceling or replaying it.
func TestWaitLimitIsIndependentOfRequestTimeout(t *testing.T) {
app := App{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}
active := protocol.Message{RunDetail: &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 7, Status: "running"}}}
o := &options{json: true, wait: true, timeout: time.Millisecond, waitTimeout: 50 * time.Millisecond}
calls := 0
call := func(protocol.Message) (protocol.Message, error) {
calls++
return active, nil
}
start := time.Now()
err := app.finishRun(context.Background(), active, o, call)
if err == nil || !strings.Contains(err.Error(), "remains active") {
t.Fatalf("expected wait-limit message, got %v", err)
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("wait limit not honored: %s", elapsed)
}
if calls > 1 {
t.Fatalf("wait limit replayed admitted work %d times", calls)
}
}
// With no explicit wait limit, a per-request --timeout must not bound the wait.
func TestRequestTimeoutDoesNotBoundWait(t *testing.T) {
app := App{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}
active := protocol.Message{RunDetail: &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 9, Status: "running"}}}
done := protocol.Message{RunDetail: &protocol.RunDetail{RunSummary: protocol.RunSummary{ID: 9, Status: "succeeded"}}}
o := &options{json: true, wait: true, timeout: time.Millisecond}
calls := 0
call := func(protocol.Message) (protocol.Message, error) {
calls++
return done, nil
}
if err := app.finishRun(context.Background(), active, o, call); err != nil {
t.Fatalf("wait lost terminal state: %v", err)
}
if calls != 1 {
t.Fatalf("expected a single reattachment poll, got %d", calls)
}
}
// The public help inventory must advertise the independent client wait limit and
// the safe read-only reattachment advice for run and retry.
func TestHelpDocumentsWaitTimeoutAndReattachment(t *testing.T) {
for _, command := range []string{"run", "retry"} {
if !strings.Contains(usage[command], "--wait-timeout") {
t.Fatalf("%s usage does not document --wait-timeout: %q", command, usage[command])
}
note := notes[command]
if !strings.Contains(note, "--wait-timeout") {
t.Fatalf("%s note does not document --wait-timeout", command)
}
if !strings.Contains(note, "--request-key") {
t.Fatalf("%s note does not warn against a duplicate run keyed by --request-key", command)
}
}
}
// A negative client wait limit is a rejected input, not an unbounded wait, and is
// caught before any server connection is attempted.
func TestNegativeWaitTimeoutIsRejected(t *testing.T) {
for _, args := range [][]string{
{"run", "--json", "--wait", "--wait-timeout", "-1s"},
{"retry", "5", "--json", "--wait", "--wait-timeout", "-1s"},
} {
app := App{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}, In: strings.NewReader("")}
err := app.Run(context.Background(), args)
if err == nil || !strings.Contains(err.Error(), "wait-timeout nonnegative") {
t.Fatalf("negative wait-timeout not rejected for %v: %v", args, err)
}
}
}
// Every documented command must build its flag set without a duplicate-flag panic,
// and the filters the usage map advertises must actually be registered.
func TestDocumentedCommandFlagsAreRegistered(t *testing.T) {
app := App{Out: &bytes.Buffer{}, Err: &bytes.Buffer{}}
for command := range usage {
command := command
func() {
defer func() {
if recovered := recover(); recovered != nil {
t.Fatalf("flags(%q) panicked: %v", command, recovered)
}
}()
app.flags(command)
}()
}
for _, check := range []struct{ command, flag string }{
{"run", "pipeline"}, {"run", "wait-timeout"},
{"runs", "pipeline"}, {"retry", "wait-timeout"},
} {
if fs, _ := app.flags(check.command); fs.Lookup(check.flag) == nil {
t.Fatalf("%s does not register --%s", check.command, check.flag)
}
}
}