Initial pipelines server, CLI, TUI, and Go installation

This commit is contained in:
2026-10-08 22:22:17 +01:00
commit 0f30a001c2
143 changed files with 17557 additions and 0 deletions
+700
View File
@@ -0,0 +1,700 @@
package cli
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
tea "github.com/charmbracelet/bubbletea"
"pipelines/internal/author"
"pipelines/internal/client"
"pipelines/internal/draft"
"pipelines/internal/pipeline"
"pipelines/internal/protocol"
"pipelines/internal/tui"
)
type App struct {
Out, Err io.Writer
In io.Reader
}
type options struct {
url, name, prompt, template, workspace, paths, key, opencode string
json, source, noOpen, yes, allow, createOnly, force, wait bool
version, expected int
timeout time.Duration
}
func (a App) flags(command string) (*flag.FlagSet, *options) {
o := &options{}
f := flag.NewFlagSet(command, flag.ContinueOnError)
f.SetOutput(a.Err)
f.StringVar(&o.url, "url", envOr("PIPELINES_URL", "ws://127.0.0.1:8080/connect"), "Pipeline server WebSocket URL")
f.BoolVar(&o.json, "json", false, "Machine-readable JSON; no interactive picker/editor")
f.DurationVar(&o.timeout, "timeout", 30*time.Second, "Timeout per server request")
switch command {
case "new", "edit":
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.opencode, "opencode", envOr("PIPELINES_OPENCODE", "opencode"), "Host OpenCode V2 executable")
if command == "new" {
f.StringVar(&o.template, "template", "", "Optional template key; omitted starts a one-stage draft")
}
if command == "edit" {
f.IntVar(&o.version, "version", 0, "Source version (0 = latest)")
}
case "show", "export", "versions":
f.IntVar(&o.version, "version", 0, "Immutable version (0 = latest)")
case "template":
f.BoolVar(&o.source, "source", false, "Print original Markdown instead of metadata")
case "submit":
f.StringVar(&o.name, "name", "", "Name for an external Markdown file (managed drafts already know their name)")
f.BoolVar(&o.createOnly, "create-only", false, "Reject existing names rather than creating another version")
f.IntVar(&o.expected, "expected-version", 0, "Reject if the latest version changed")
f.BoolVar(&o.force, "force", false, "Explicitly bypass a draft's base-version conflict guard (validation still applies)")
case "run":
f.StringVar(&o.name, "pipeline", "", "Exact registered pipeline name or ID")
f.StringVar(&o.prompt, "prompt", "", "Task prompt; omitted opens a multiline composer")
f.StringVar(&o.workspace, "workspace", "", "Run directory (default: current directory)")
f.BoolVar(&o.yes, "yes", false, "Start supplied name/prompt without interactive confirmation")
f.BoolVar(&o.allow, "allow-tools", false, "Explicitly approve declared shell/edit tools with --yes")
f.StringVar(&o.paths, "write-paths", "", "Comma-separated exact existing project-local Go files")
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")
case "runs":
f.StringVar(&o.name, "pipeline", "", "Filter by exact pipeline name or ID")
}
f.Usage = func() {
fmt.Fprintf(a.Out, "Usage: pipelines %s\n", usage[command])
if note := notes[command]; note != "" {
fmt.Fprintln(a.Out, "\n"+note)
}
fmt.Fprintln(a.Out, "\nOptions:")
f.VisitAll(func(entry *flag.Flag) {
label := "--" + entry.Name
if b, ok := entry.Value.(interface{ IsBoolFlag() bool }); !ok || !b.IsBoolFlag() {
label += " <value>"
}
defaultLabel := ""
if entry.DefValue != "" && entry.DefValue != "false" && entry.DefValue != "0" {
defaultLabel = " (default: " + entry.DefValue + ")"
}
fmt.Fprintf(a.Out, " %-28s %s%s\n", label, entry.Usage, defaultLabel)
})
fmt.Fprintln(a.Out, " --help Show this help")
}
return f, o
}
func envOr(key, value string) string {
if v := os.Getenv(key); v != "" {
return v
}
return value
}
// parse allows flags before or after positional arguments without reinterpreting values.
func parse(f *flag.FlagSet, args []string) error {
var flags, positionals []string
for i := 0; i < len(args); i++ {
arg := args[i]
if arg == "--" {
positionals = append(positionals, args[i+1:]...)
break
}
if !strings.HasPrefix(arg, "-") || arg == "-" {
positionals = append(positionals, arg)
continue
}
flags = append(flags, arg)
name := strings.SplitN(strings.TrimLeft(arg, "-"), "=", 2)
if len(name) == 2 || name[0] == "help" || name[0] == "h" {
continue
}
entry := f.Lookup(name[0])
if entry == nil {
return fmt.Errorf("unknown option %s; use pipelines help %s", arg, f.Name())
}
if b, ok := entry.Value.(interface{ IsBoolFlag() bool }); ok && b.IsBoolFlag() {
continue
}
if i+1 >= len(args) {
return fmt.Errorf("%s needs a value", arg)
}
i++
flags = append(flags, args[i])
}
return f.Parse(append(flags, positionals...))
}
func (a App) Run(ctx context.Context, args []string) error {
// Global selectors may appear before the command as well as after it.
leading := 0
for leading < len(args) {
parts := strings.SplitN(strings.TrimLeft(args[leading], "-"), "=", 2)
if !strings.HasPrefix(args[leading], "-") || (parts[0] != "url" && parts[0] != "timeout" && parts[0] != "json") {
break
}
leading++
if len(parts) == 1 && parts[0] != "json" {
if leading >= len(args) {
return fmt.Errorf("--%s requires a value", parts[0])
}
leading++
}
}
if leading > 0 {
if leading == len(args) {
return fmt.Errorf("a command is required; use pipelines help")
}
args = append(append([]string{}, args[leading:]...), args[:leading]...)
}
if len(args) == 0 || args[0] == "help" || args[0] == "--help" || args[0] == "-h" {
if len(args) > 1 && args[0] == "help" {
if note, ok := serviceHelp[args[1]]; ok {
fmt.Fprintf(a.Out, "Usage: pipelines %s [options]\n\n%s\n\nService commands require the installed launcher.\n", args[1], note)
return nil
}
if _, ok := usage[args[1]]; !ok {
return fmt.Errorf("unknown application command %q; service help: pipelines <service-command> --help", args[1])
}
f, _ := a.flags(args[1])
f.Usage()
return nil
}
fmt.Fprint(a.Out, help)
return nil
}
command := args[0]
if _, ok := usage[command]; !ok {
return fmt.Errorf("unknown command %q; use pipelines help", command)
}
f, o := a.flags(command)
if err := parse(f, args[1:]); err != nil {
if errors.Is(err, flag.ErrHelp) {
return nil
}
return err
}
if o.timeout <= 0 || o.version < 0 || o.expected < 0 {
return fmt.Errorf("timeout must be positive and versions nonnegative")
}
pos := f.Args()
if command == "tui" {
if len(pos) > 0 {
return fmt.Errorf("tui takes no arguments")
}
_, err := tea.NewProgram(tui.New(ctx, o.url), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
if command == "drafts" {
if len(pos) > 0 {
return fmt.Errorf("drafts takes no arguments")
}
items, err := draft.List()
if err != nil {
return err
}
if o.json {
return a.output(items)
}
for _, d := range items {
fmt.Fprintf(a.Out, "%s\t%s\tbase v%d\n", d.Name, d.Path, d.BaseVersion)
}
return nil
}
// Connect only for server operations. Keep each RPC bounded, not the interactive session.
dialCtx, cancel := context.WithTimeout(ctx, o.timeout)
c, err := client.Open(dialCtx, o.url)
cancel()
if err != nil {
return err
}
defer c.Close()
call := func(request protocol.Message) (protocol.Message, error) {
requestCtx, cancel := context.WithTimeout(ctx, o.timeout)
defer cancel()
return c.Call(requestCtx, request)
}
resolve := func(value string) (protocol.PipelineSummary, error) {
r, err := call(protocol.Message{Type: protocol.List})
if err != nil {
return protocol.PipelineSummary{}, err
}
// Names win over IDs so numeric pipeline names remain addressable.
for _, p := range r.Pipelines {
if p.Name == value {
return p, nil
}
}
id, _ := strconv.ParseInt(value, 10, 64)
for _, p := range r.Pipelines {
if p.ID == id && id > 0 {
return p, nil
}
}
return protocol.PipelineSummary{}, fmt.Errorf("pipeline %q not found", value)
}
one := func() (string, error) {
if len(pos) != 1 {
return "", fmt.Errorf("%s requires one argument; use pipelines help %s", command, command)
}
return pos[0], nil
}
switch command {
case "new", "edit":
return a.author(ctx, command, pos, o, call, resolve)
case "validate", "submit":
path, err := one()
if err != nil {
return err
}
source, err := draft.Read(path)
if err != nil {
return err
}
request := protocol.Message{Type: protocol.Validate, Source: source}
if command == "submit" {
d, metaErr := draft.Load(path)
if metaErr != nil && !os.IsNotExist(metaErr) {
return metaErr
}
if d.Server != "" && d.Server != o.url {
return fmt.Errorf("draft belongs to server %s; select it with --url", d.Server)
}
name := o.name
if name == "" {
name = d.Name
}
if name == "" {
return fmt.Errorf("external draft requires --name")
}
expected := d.BaseVersion
if o.expected > 0 {
expected = o.expected
}
if o.force {
expected = 0
}
request = protocol.Message{Type: protocol.Submit, Name: name, Source: source, CreateOnly: d.CreateOnly || o.createOnly, ExpectedVersion: expected}
}
r, err := call(request)
if err != nil {
return err
}
if o.json {
return a.output(r)
}
if command == "validate" {
fmt.Fprintln(a.Out, "Valid draft (server validation). No changes submitted.")
} else {
fmt.Fprintf(a.Out, "Submitted %s v%d\n", r.Name, r.Version)
if r.Detail != nil && r.Detail.Graph.Settings != nil {
fmt.Fprintln(a.Err, "Schedules are now active for this version.")
}
}
return nil
case "list", "templates", "runs", "ping", "connection":
if len(pos) > 0 {
return fmt.Errorf("%s takes no positional arguments", command)
}
typeName := map[string]string{"list": protocol.List, "templates": protocol.ListTemplates, "runs": protocol.ListRuns, "ping": protocol.Ping, "connection": protocol.List}[command]
r, err := call(protocol.Message{Type: typeName})
if err != nil {
return err
}
if command == "runs" && o.name != "" {
p, err := resolve(o.name)
if err != nil {
return err
}
filtered := []protocol.RunSummary{}
for _, run := range r.Runs {
if run.PipelineID == p.ID {
filtered = append(filtered, run)
}
}
r.Runs = filtered
}
if o.json {
return a.output(r)
}
switch command {
case "list":
for _, p := range r.Pipelines {
fmt.Fprintf(a.Out, "%d\t%s\tv%d\t%d stages\n", p.ID, p.Name, p.Version, p.Stages)
}
case "templates":
for _, t := range r.Templates {
note := ""
if t.Scheduled {
note = " [scheduled]"
}
fmt.Fprintf(a.Out, "%-24s %s%s\n", t.Key, t.Description, note)
}
case "runs":
for _, run := range r.Runs {
fmt.Fprintf(a.Out, "%d\t%s\tv%d\t%s\n", run.ID, run.Name, run.Version, run.Status)
}
case "ping":
fmt.Fprintln(a.Out, "Connected ·", r.Time)
case "connection":
fmt.Fprintln(a.Out, "Server:", o.url)
for _, n := range r.NotificationEndpoints {
fmt.Fprintf(a.Out, "ntfy: %s · topic %s\n", n.ServerURL, n.Topic)
}
}
return nil
case "show", "versions", "export":
value, err := one()
if err != nil {
return err
}
p, err := resolve(value)
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: p.ID, Version: o.version})
if err != nil {
return err
}
if r.Detail == nil {
return fmt.Errorf("missing pipeline detail")
}
if command == "export" {
_, err = fmt.Fprint(a.Out, r.Detail.Source)
return err
}
if command == "versions" {
if o.json {
return a.output(r.Detail.Versions)
}
for _, v := range r.Detail.Versions {
fmt.Fprintf(a.Out, "v%d\t%d stages\t%s\n", v.Version, v.Stages, v.CreatedAt)
}
return nil
}
return a.output(r.Detail)
case "template":
key, err := one()
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.ListTemplates})
if err != nil {
return err
}
for _, t := range r.Templates {
if t.Key == key {
if o.source {
_, err = fmt.Fprint(a.Out, t.Source)
return err
}
return a.output(t)
}
}
return fmt.Errorf("template %q not found", key)
case "inspect", "cancel":
value, err := one()
if err != nil {
return err
}
id, err := strconv.ParseInt(value, 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive")
}
typeName := protocol.GetRun
if command == "cancel" {
typeName = protocol.CancelRun
}
r, err := call(protocol.Message{Type: typeName, RunID: id})
if err != nil {
return err
}
return a.output(r.RunDetail)
case "rpc":
path, err := one()
if err != nil {
return err
}
reader := a.In
if path != "-" {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
reader = f
}
data, err := io.ReadAll(io.LimitReader(reader, (2<<20)+1))
if err != nil {
return err
}
if len(data) > 2<<20 {
return fmt.Errorf("request exceeds 2 MiB")
}
var request protocol.Message
if err = json.Unmarshal(data, &request); err != nil {
return err
}
r, err := call(request)
if err != nil {
return err
}
return a.output(r)
case "run":
return a.run(ctx, pos, o, call, resolve)
}
return nil
}
func (a App) output(value any) error {
encoder := json.NewEncoder(a.Out)
encoder.SetIndent("", " ")
return encoder.Encode(value)
}
type callFunc func(protocol.Message) (protocol.Message, error)
type resolveFunc func(string) (protocol.PipelineSummary, error)
func (a App) author(ctx context.Context, command string, pos []string, o *options, call callFunc, resolve resolveFunc) error {
if len(pos) > 2 {
return fmt.Errorf("%s accepts [name] [prompt]", command)
}
if len(pos) > 0 {
if o.name != "" {
return fmt.Errorf("supply name once")
}
o.name = pos[0]
}
if len(pos) > 1 {
if o.prompt != "" {
return fmt.Errorf("supply prompt once")
}
o.prompt = pos[1]
}
var source string
var base int
if command == "edit" {
if o.name == "" {
if o.json {
return fmt.Errorf("edit --json requires a name or ID")
}
r, err := call(protocol.Message{Type: protocol.List})
if err != nil {
return err
}
p, err := tui.PickPipeline(ctx, r.Pipelines)
if err != nil {
return err
}
o.name = p.Name
}
p, err := resolve(o.name)
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.GetPipeline, PipelineID: p.ID, Version: o.version})
if err != nil {
return err
}
if r.Detail == nil {
return fmt.Errorf("missing pipeline detail")
}
o.name = p.Name
source = r.Detail.Source
base = r.Detail.LatestVersion
} else {
if o.name == "" {
if o.json || o.noOpen {
return fmt.Errorf("new requires a name in noninteractive mode")
}
fmt.Fprint(a.Err, "New pipeline name: ")
name, err := bufio.NewReader(a.In).ReadString('\n')
if err != nil {
return err
}
o.name = strings.TrimSpace(name)
}
if strings.TrimSpace(o.name) == "" || len(o.name) > 200 || strings.ContainsAny(o.name, "\r\n\x00") {
return fmt.Errorf("name must be 1–200 bytes without line breaks or NUL")
}
r, err := call(protocol.Message{Type: protocol.List})
if err != nil {
return err
}
for _, p := range r.Pipelines {
if p.Name == o.name {
return fmt.Errorf("pipeline already exists; use edit or choose another name")
}
}
source = pipeline.Template([]string{"worker"}, true)
if o.template != "" {
r, err := call(protocol.Message{Type: protocol.ListTemplates})
if err != nil {
return err
}
found := false
for _, t := range r.Templates {
if t.Key == o.template {
source = t.Source
found = true
break
}
}
if !found {
return fmt.Errorf("template %q not found", o.template)
}
}
}
d, err := draft.Create(o.name, source, o.url, command == "new", base)
if err != nil {
return err
}
if o.json {
return a.output(d)
}
fmt.Fprintf(a.Out, "Draft: %s\nValidate: pipelines validate %q\nSubmit when ready: pipelines submit %q\n", d.Path, d.Path, d.Path)
if o.noOpen {
return nil
}
workspace, err := author.Workspace(d)
if err != nil {
return err
}
prepareCtx, cancel := context.WithTimeout(ctx, o.timeout)
session, err := author.PrepareSession(prepareCtx, o.opencode, workspace, d.Name)
cancel()
if err != nil {
return err
}
// 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 := exec.CommandContext(ctx, o.opencode, workspace, "--session", session, "--prompt", author.Prompt(d, o.prompt, cliCommand))
cmd.Stdin = a.In
cmd.Stdout = a.Out
cmd.Stderr = a.Err
return cmd.Run()
}
func (a App) run(ctx context.Context, pos []string, o *options, call callFunc, resolve resolveFunc) error {
if len(pos) > 2 {
return fmt.Errorf("run accepts [name] [prompt]")
}
if len(pos) > 0 {
if o.name != "" {
return fmt.Errorf("supply pipeline once")
}
o.name = pos[0]
}
if len(pos) > 1 {
if o.prompt != "" {
return fmt.Errorf("supply prompt once")
}
o.prompt = pos[1]
}
if o.workspace == "" {
cwd, err := os.Getwd()
if err != nil {
return err
}
o.workspace = cwd
}
workspace, err := filepath.Abs(o.workspace)
if err != nil {
return err
}
var paths []string
for _, p := range strings.Split(o.paths, ",") {
if p = strings.TrimSpace(p); p != "" {
paths = append(paths, p)
}
}
if o.yes && (o.name == "" || strings.TrimSpace(o.prompt) == "") {
return fmt.Errorf("--yes requires a pipeline and nonempty prompt")
}
if o.yes && len(paths) > 0 && !o.allow {
return fmt.Errorf("--write-paths with --yes requires --allow-tools")
}
if !o.json {
if o.name != "" {
p, err := resolve(o.name)
if err != nil {
return err
}
o.name = p.Name
}
if o.wait || o.key != "" || o.version > 0 {
return fmt.Errorf("--wait, --request-key and --version require --json")
}
_, err := tea.NewProgram(tui.NewRun(ctx, o.url, tui.RunOptions{Pipeline: o.name, Prompt: o.prompt, Workspace: workspace, Yes: o.yes, AllowTools: o.allow, WritePaths: paths}), tea.WithContext(ctx), tea.WithAltScreen()).Run()
return err
}
if !o.yes {
return fmt.Errorf("noninteractive run requires --yes (tool approval remains separate)")
}
p, err := resolve(o.name)
if err != nil {
return err
}
version := o.version
if version == 0 {
version = p.Version
}
key := o.key
if key == "" {
key = fmt.Sprintf("cli-%d-%d", os.Getpid(), time.Now().UnixNano())
}
r, err := call(protocol.Message{Type: protocol.RunPipeline, PipelineID: p.ID, Version: version, RequestKey: key, Workspace: workspace, Input: map[string]any{"prompt": o.prompt}, AllowTools: o.allow, WritePaths: paths})
if err != nil {
return err
}
if o.wait {
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail")
}
deadline := time.NewTimer(o.timeout)
defer deadline.Stop()
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 <-time.After(time.Second):
}
r, err = call(protocol.Message{Type: protocol.GetRun, RunID: r.RunDetail.ID})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("missing run detail")
}
}
}
if err = a.output(r); err != nil {
return err
}
if o.wait && r.RunDetail.Status != "succeeded" {
return fmt.Errorf("run ended %s", r.RunDetail.Status)
}
return nil
}
func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" }
+189
View File
@@ -0,0 +1,189 @@
package cli_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"pipelines/internal/cli"
"pipelines/internal/draft"
"pipelines/internal/pipeline"
"pipelines/internal/protocol"
"pipelines/internal/server"
)
func setup(t *testing.T) (func(...string) (string, error), *pipeline.Store, string) {
t.Helper()
ctx, cancel := context.WithCancel(context.Background())
store, err := pipeline.Open(filepath.Join(t.TempDir(), "cli.db"))
if err != nil {
t.Fatal(err)
}
handler := server.Handler(ctx, store)
http := httptest.NewServer(handler)
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())
return func(args ...string) (string, error) {
var out, stderr bytes.Buffer
app := cli.App{Out: &out, Err: &stderr, In: strings.NewReader("")}
err := app.Run(ctx, append([]string{"--url", url}, args...))
return out.String(), err
}, store, url
}
func TestCLIHelpDoesNotNeedServer(t *testing.T) {
for _, args := range [][]string{{"help"}, {"--help"}, {"help", "edit"}, {"help", "start"}, {"run", "--help"}} {
var out, stderr bytes.Buffer
err := (cli.App{Out: &out, Err: &stderr}).Run(context.Background(), args)
if err != nil {
t.Fatal(err)
}
text := out.String() + stderr.String()
if !strings.Contains(text, "pipelines") && !strings.Contains(text, "Usage") {
t.Fatal("missing help", text)
}
}
}
func TestCLIDraftValidateSubmitAndImmutableHistory(t *testing.T) {
run, store, _ := setup(t)
output, err := run("new", "example", "--template", "bug-fix", "--json")
if err != nil {
t.Fatal(err)
}
var d draft.Draft
if err = json.Unmarshal([]byte(output), &d); err != nil {
t.Fatal(err)
}
items, _ := store.List(context.Background())
if len(items) != 0 {
t.Fatal("draft seeded database")
}
if !d.CreateOnly {
t.Fatal("new draft can overwrite")
}
if _, err = run("validate", d.Path, "--json"); err != nil {
t.Fatal(err)
}
if _, err = run("submit", d.Path, "--json"); err != nil {
t.Fatal(err)
}
if _, err = run("submit", d.Path); err == nil || !strings.Contains(err.Error(), "already exists") {
t.Fatal("duplicate submitted", err)
}
if _, err = run("new", "example", "--json"); err == nil {
t.Fatal("new accepted existing name")
}
output, err = run("edit", "example", "Add a review step", "--json")
if err != nil {
t.Fatal(err)
}
json.Unmarshal([]byte(output), &d)
if d.BaseVersion != 1 || d.CreateOnly {
t.Fatal("edit missing base version", d)
}
original, err := run("export", "example")
if err != nil {
t.Fatal(err)
}
changed := strings.Replace(original, "# stage planner", "# stage planner", 1) + "\n"
os.WriteFile(d.Path, []byte(changed), 0600)
if _, err = run("submit", d.Path, "--json"); err != nil {
t.Fatal(err)
}
output, err = run("versions", "example", "--json")
if err != nil {
t.Fatal(err)
}
var versions []protocol.VersionSummary
json.Unmarshal([]byte(output), &versions)
if len(versions) != 2 {
t.Fatal(versions)
}
old, err := run("export", "example", "--version", "1")
if err != nil || old != original {
t.Fatal("history rewritten", err)
}
os.WriteFile(d.Path, []byte(changed+"\n"), 0600)
if _, err = run("submit", d.Path); err == nil || !strings.Contains(err.Error(), "conflict") {
t.Fatal("stale draft accepted", err)
}
if _, err = run("submit", d.Path, "--force"); err != nil {
t.Fatal(err)
}
os.WriteFile(d.Path, []byte("not a definition"), 0600)
if _, err = run("validate", d.Path, "--json"); err == nil {
t.Fatal("invalid draft accepted")
}
if _, err = run("submit", d.Path, "--force"); err == nil {
t.Fatal("force bypassed validation")
}
items, _ = store.List(context.Background())
if items[0].Version != 3 {
t.Fatal("invalid submission changed live version", items)
}
for _, command := range [][]string{{"list", "--json"}, {"show", "example", "--json"}, {"templates", "--json"}, {"template", "bug-fix", "--source"}, {"drafts", "--json"}, {"runs", "--json"}, {"connection", "--json"}, {"ping"}} {
if _, err = run(command...); err != nil {
t.Fatal(command, err)
}
}
if _, err = run("--json", "list"); err != nil {
t.Fatal("global JSON flag before command", err)
}
}
func TestCLIAuthorOpenCodeGetsScopedSkillAndLeavesDraft(t *testing.T) {
run, store, _ := setup(t)
// A fake executable captures launch behavior without spending model tokens.
root := t.TempDir()
capture := filepath.Join(root, "invocation")
script := filepath.Join(root, "opencode")
os.WriteFile(script, []byte("#!/bin/sh\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)
if _, err := run("new", "scoped skill", "Make a digest", "--opencode", script); err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(capture)
if err != nil {
t.Fatal(err)
}
parts := strings.SplitN(string(data), "\n", 3)
if parts[1] != "--session" || !strings.Contains(parts[2], "ses_test\n--prompt\n@pipelines") || !strings.Contains(parts[2], "Make a digest") {
t.Fatal(string(data))
}
for _, name := range []string{"DRAFT.json", ".opencode/skills/pipelines/SKILL.md", ".opencode/skills/pipelines/references/format.md"} {
if _, err := os.Stat(filepath.Join(parts[0], name)); err != nil {
t.Fatal(name, err)
}
}
items, _ := store.List(context.Background())
if len(items) != 0 {
t.Fatal("OpenCode launch submitted draft")
}
}
func TestCLIBoundedFilesServerMismatchAndNoninteractiveGuards(t *testing.T) {
run, _, url := setup(t)
d, err := draft.Create("test", pipeline.Template([]string{"worker"}, true), url+"-other", true, 0)
if err != nil {
t.Fatal(err)
}
if _, err = run("submit", d.Path); err == nil || !strings.Contains(err.Error(), "belongs") {
t.Fatal(err)
}
os.WriteFile(d.Path, bytes.Repeat([]byte("x"), (1<<20)+1), 0600)
if _, err = run("validate", d.Path); err == nil {
t.Fatal("oversized draft accepted")
}
for _, args := range [][]string{{"run", "--json"}, {"run", "x", "prompt", "--json"}, {"run", "x", "prompt", "--yes", "--json", "--write-paths", "a.go"}, {"edit", "--json"}, {"new", "--json"}, {"new", "test", "--template", "missing", "--json"}, {"inspect", "0"}, {"cancel", "no"}, {"show", "missing"}, {"list", "unexpected"}} {
if _, err := run(args...); err == nil {
t.Fatal("expected error", fmt.Sprint(args))
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package cli
// Help is also the public command inventory for agents and parity checks.
var usage = map[string]string{
"new": "new [name] [prompt] [--template KEY] [--no-open | --json]",
"edit": "edit [name|id] [prompt] [--version N] [--no-open | --json]",
"drafts": "drafts [--json]",
"validate": "validate <draft.md> [--json]",
"submit": "submit <draft.md> [--name NAME] [--create-only] [--json]",
"list": "list [--json]",
"show": "show <name|id> [--version N] [--json]",
"versions": "versions <name|id> [--json]",
"export": "export <name|id> [--version N]",
"templates": "templates [--json]",
"template": "template <key> [--source | --json]",
"run": "run [name|id] [prompt] [--yes] [--json [--wait]]",
"runs": "runs [--pipeline NAME] [--json]",
"inspect": "inspect <run-id> [--json]",
"cancel": "cancel <run-id> [--json]",
"connection": "connection [--json]",
"ping": "ping [--json]",
"rpc": "rpc <request.json|->",
"tui": "tui",
}
var notes = map[string]string{
"new": "Create an optional template copy or a one-stage starter. Opens OpenCode with the pipeline skill already loaded. 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.",
"validate": "Uses the same server parser as submission. Does not persist or activate schedules. Structural validity does not prove runtime/tool availability.",
"submit": "This command is explicit approval to publish; schedules activate on acceptance. Managed drafts provide the name and base-version guard. --force never bypasses validation.",
"run": "Interactive: Enter adds a prompt line, Ctrl+S continues, then type RUN to start. JSON: supply a name/prompt and --yes. Tool approval is separate; cancellation does not undo edits.",
"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{
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
"stop": "Stop both services. Active execution is interrupted; file changes are not rolled back.",
"restart": "Stop, then start both services, retaining definitions, run history, and credentials.",
"status": "Show pipeline/ntfy health and the public phone connection (no credentials).",
"doctor": "Check both health endpoints and host OpenCode API discovery; does not execute a model.",
"logs": "Follow the native server log. Press Ctrl+C to stop following.",
"uninstall": "Remove this installation; retain data by default. --purge explicitly deletes this installation and its ntfy volume; --yes skips prompts.",
}
+51
View File
@@ -0,0 +1,51 @@
package cli
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
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
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
templates List optional templates (never seeds the DB)
template <key> Inspect a template; --source prints Markdown
EXECUTE
run [name] [prompt] Fuzzy selection, multiline prompt, live inspector
runs List audited runs; --pipeline filters results
inspect <run-id> Inspect stages, outputs, errors and status
cancel <run-id> Cancel a run; changes are NOT rolled back
connection Server and public phone connection (no secrets)
ping Check the server connection
rpc <request.json|-> Send any protocol command (automation escape hatch)
SERVICE / INTERFACE (managed installation)
tui Open the dashboard (default with no command)
start | stop | restart Manage the native server + Docker ntfy together
status | doctor | logs Health, OpenCode discovery, server logs
uninstall [--purge] Remove app; retain data unless explicitly purged
Options: --url ws://127.0.0.1:8080/connect --json --help
Use pipelines help <command> for its flags. Names with spaces must be quoted.
Examples:
pipelines edit "bug fix" "Add a review step"
pipelines new "release notes" "Summarize changes and notify my phone"
pipelines new "weekly digest" --template scheduled-summary --no-open --json
pipelines validate /path/to/draft.md --json
pipelines submit /path/to/draft.md
pipelines run "bug fix" "Fix the layout" --yes --json
Draft-first: OpenCode edits a private draft; 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.
`