diff --git a/README.md b/README.md index daba9a0f..693e69e8 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,9 @@ cd pipelines ``` Native setup reuses your existing host OpenCode login and never installs, -upgrades or downloads OpenCode/Pi. Start it with +upgrades or downloads OpenCode/Pi. It writes host harness profiles (no Docker +link) for the harnesses it detects, so authoring works immediately, and clears a +stale Docker link when migrating a Docker install. Start it with `PIPELINES_PREFIX=~/.local/share/pipelines ~/.local/share/pipelines/bin/pipelines start`. When Docker volumes are present it migrates the existing database and ntfy auth store (never overwriting newer native data; use `--replace-data` to opt in). See @@ -319,8 +321,9 @@ pipelines ping --json # running server identity pipelines help edit ``` -CLI `new`/`edit` open the configured harness (**OpenCode** or **Pi**) directly with -the Pipelines skill. The installed skill asks +CLI `new`/`edit` open the configured harness (**OpenCode** or **Pi**, native host +by default; a profile is Docker-linked only when a checkout is explicitly linked) +directly with the Pipelines skill. The installed skill asks missing questions; `pipelines new` needs no preliminary questionnaire. Changes stay as drafts by default; CLI and TUI share validation and draft storage. Most commands support `--json` for agents and scripts. @@ -330,7 +333,8 @@ CLI-created ones. **e** reopens a draft, **v** validates it, and **s** opens exp submission confirmation, asking for a name first if needed. Drafts remain retained after submission. Drafts are portable: submit to the currently connected server. When that differs from the origin, submission creates a new pipeline rather than -applying the origin's version number to an existing destination pipeline. +applying the origin's version number to an existing destination pipeline, and a +notice names both server URLs instead of silently retargeting the draft. From a run, press **P** / **:pipeline** to open the pipeline version it used. Initial run input also records `pwd`. Press **r** / **:retry** on a failed run diff --git a/docs/cli.md b/docs/cli.md index a8521693..efce5665 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -72,8 +72,9 @@ pipelines new "release notes" "Summarize changes and notify my phone" pipelines new "Text summary" --template summary ``` -`new` opens the configured harness (Pi or OpenCode; Docker-linked by default) -immediately when its name/request is omitted. The skill asks only for missing +`new` opens the configured harness (Pi or OpenCode; host by default, or +Docker-linked when a checkout is linked) immediately when its name/request is +omitted. The skill asks only for missing decisions and records the chosen name in draft metadata. `edit` accepts an exact name or ID, with names taking precedence over numeric IDs. Both retain private drafts and launch the harness once with a short `@pipelines` reference and @@ -144,7 +145,9 @@ the existing draft, `v` for server validation, and `s` for submission confirmati server you are connected to. Same-server submissions preserve create-only/version guards. A different destination imports the draft as a new pipeline, ignoring the origin's version number and refusing an existing destination name; the -confirmation shows the destination. Retained source and origin metadata stay +confirmation shows the destination, and opening, validating or submitting a draft +whose recorded server differs from the configured one prints a notice naming both +URLs so it is never silently retargeted. Retained source and origin metadata stay unchanged. For an edit draft, CLI `submit --expected-version N` can explicitly approve an update against version N on the destination (or `--force` can explicitly skip that version check). For unnamed drafts, submission asks you to diff --git a/docs/harnesses-and-control.md b/docs/harnesses-and-control.md index bd8eb0f7..278ef5d5 100644 --- a/docs/harnesses-and-control.md +++ b/docs/harnesses-and-control.md @@ -41,6 +41,17 @@ host OpenCode/Pi and never installs, upgrades or downloads them, and reconfiguration never falls back to host harness execution. Container credentials and accounts are separate from host credentials and are reused on reinstall/reconfigure. +Profiles live in XDG config home's `pipelines/harnesses.json` and record their +launch mode: a host profile launches the executable directly, while a +Docker-linked profile records the checkout directory and launches through +`docker compose exec`. `harness setup --host` configures (or +converts) a host profile and clears any Docker link; without `--host`, +reconfiguring a Docker-linked profile re-verifies that the recorded directory +still has `compose.yaml` and fails naming it instead of saving a link that cannot +launch. Setup's summary and `harness list` report the resulting mode (and, for +Docker, the directory) so a profile never silently stays Docker-linked. The +native installer writes host profiles for the harnesses it detects and clears a +stale Docker link rather than leaving the config Docker-linked. Defaults affect only new drafts/starters, not existing immutable versions. OpenCode uses `mini --model` to avoid changing unrelated host/project defaults. Pi stage execution requires its profile on the server; interactive host and diff --git a/docs/install.md b/docs/install.md index 77ff0942..4430c82d 100644 --- a/docs/install.md +++ b/docs/install.md @@ -36,6 +36,15 @@ manifest is what `scripts/manage.py` and the Go CLI load. Provider/model default are never invented: your existing host OpenCode configuration is reused (an explicit `--model` is recorded if supplied), and setup never starts a picker. +The native install also writes **host** harness profiles for the harnesses it +detects into XDG config home's `pipelines/harnesses.json` (no +`docker_directory`), defaulting to the detected OpenCode profile rather than a +stale `pi` default and taking models from `--model` or the existing valid profile. +When migrating a Docker install it clears the recorded Docker link instead of +leaving the config Docker-linked. It never installs, upgrades or downloads a +harness. If no valid model can be resolved it writes nothing and points you at +`pipelines harness setup --host`. + ntfy is built from source with no Homebrew or package manager. Setup resolves the exact stable `binwiederhier/ntfy` tag (never the moving `latest` tag and never an older fallback), then compiles the server from the pinned `heckel.io/ntfy/v2` Go diff --git a/internal/author/skill/references/harnesses.md b/internal/author/skill/references/harnesses.md index 9c0b5414..16b01e9d 100644 --- a/internal/author/skill/references/harnesses.md +++ b/internal/author/skill/references/harnesses.md @@ -65,7 +65,10 @@ the last verified Dockerfile fallback pins); they never guess, fall back to a ho runtime or install a stale pin. Without a Docker installation, `./install --opencode`/`--pi` stop and require an existing Docker setup; the native installation reuses the host OpenCode -configuration. Container and host credentials and accounts remain independent and +configuration, writes **host** (non-Docker) profiles for the harnesses it detects +into XDG config home's `pipelines/harnesses.json`, and clears a stale Docker link +so a Docker-era profile is not left Docker-linked. It never installs, upgrades or +downloads a harness. Container and host credentials and accounts remain independent and are reused on reinstall/reconfigure. `./install` installs natively by default (`--native` is equivalent); explicit `./install --docker` selects the Docker server + ntfy installation. @@ -74,7 +77,14 @@ login. Existing setup can configure either harness independently. Pi setup does not run a generation check; `provider-check --harness pi --model PROVIDER/MODEL` is a separate confirmed, potentially chargeable check. Profiles live in XDG config home's `pipelines/harnesses.json`, store preferences -only, and preserve unrelated configuration. Harness CLI setup/default commands +only, and preserve unrelated configuration. A profile launches a native host +harness unless it records a Docker checkout directory, in which case it launches +through that installation's Compose service. `harness setup --host` +configures or converts a host profile and clears any Docker link; without +`--host`, reconfiguring a Docker-linked profile re-verifies that the recorded +directory still has `compose.yaml` and fails naming it rather than saving a link +that cannot launch. Setup's summary and `harness list` report the resulting mode +(and, for Docker, the directory). Harness CLI setup/default commands always configure the local execution user, not a remote `--url` server. OpenCode interactive launch uses `mini --model`: verified V2 full CLI lacks a model flag. Pi uses its CLI with the diff --git a/internal/cli/app.go b/internal/cli/app.go index 0ce1d825..de310df8 100644 --- a/internal/cli/app.go +++ b/internal/cli/app.go @@ -561,7 +561,14 @@ func (a App) Run(ctx context.Context, args []string) error { } origin := d crossServer := d.Server != "" && d.Server != o.url - d = d.ForServer(o.url) + d, notice := d.Resolve(o.url) + if notice != "" { + if o.json { + fmt.Fprintln(a.Err, notice) + } else { + fmt.Fprintln(a.Out, notice) + } + } name := o.name if name == "" { name = d.Name @@ -586,6 +593,14 @@ func (a App) Run(ctx context.Context, args []string) error { if err := a.confirmAction("Publish "+name+" to "+o.url+" as an immutable version? Included schedules activate on acceptance.", o.yes); err != nil { return err } + } else if d, metaErr := draft.Load(path); metaErr == nil { + if _, notice := d.Resolve(o.url); notice != "" { + if o.json { + fmt.Fprintln(a.Err, notice) + } else { + fmt.Fprintln(a.Out, notice) + } + } } r, err := call(request) if err != nil { diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 923a2121..ba79a79a 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -47,7 +47,7 @@ var notes = map[string]string{ } var serviceHelp = map[string]string{ - "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.", + "harness": "pipelines harness launches the configured default. harness setup opencode|pi offers fuzzy model selection; --host configures a native host harness and clears any Docker link, --login reopens login, --default chooses the default harness, --model and --pipeline-model set separate defaults explicitly. harness list prints non-secret settings, including each profile's launch mode. 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.", diff --git a/internal/cli/harness.go b/internal/cli/harness.go index f3d29250..2918b7e3 100644 --- a/internal/cli/harness.go +++ b/internal/cli/harness.go @@ -17,11 +17,11 @@ import ( func (a App) harness(ctx context.Context, args []string) error { if len(args) > 0 && args[0] == "list" { - c, err := harness.Load() + list, err := harness.List() if err != nil { return err } - return a.output(c) + return a.output(list) } if len(args) > 0 && args[0] == "default" { c, err := harness.Load() @@ -66,7 +66,7 @@ func (a App) harness(ctx context.Context, args []string) error { if err != nil || *directory == "" { return fmt.Errorf("Docker installation directory is required") } - if _, err := os.Stat(filepath.Join(absolute, "compose.yaml")); err != nil { + if err := harness.VerifyDockerLink(absolute); err != nil { return err } c, err := harness.Load() @@ -88,12 +88,13 @@ func (a App) harness(ctx context.Context, args []string) error { 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") + host := f.Bool("host", false, "Configure a native host harness and clear any Docker link") 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]") + return fmt.Errorf("usage: pipelines harness setup [opencode|pi] [--login] [--host] [--model P/M] [--pipeline-model P/M] [--default]") } name := "" if len(f.Args()) == 1 { @@ -131,9 +132,19 @@ func (a App) harness(ctx context.Context, args []string) error { if err != nil { return err } + existing, exists := c.Profiles[name] + // A profile can move between Docker and host. Without an explicit + // --host selection a Docker-linked profile is only reconfigured when its + // recorded installation is still verifiable; otherwise setup fails + // naming the directory instead of saving a link that cannot launch. + if !*host && exists && existing.DockerDirectory != "" { + if err := harness.VerifyDockerLink(existing.DockerDirectory); err != nil { + return err + } + } onboarding := harness.NewOnboarding(a.Out) action := "Configure" - if _, ok := c.Profiles[name]; ok { + if exists { action = "Reconfigure" } onboarding.Header(name, action) @@ -211,6 +222,9 @@ func (a App) harness(ctx context.Context, args []string) error { } profile := c.Profiles[name] profile.Executable, profile.Model, profile.PipelineModel = *executable, *model, *pipelineModel + if *host { + profile.DockerDirectory = "" + } c.Profiles[name] = profile if *makeDefault || c.Default == "" { c.Default = name @@ -218,7 +232,7 @@ func (a App) harness(ctx context.Context, args []string) error { if err = harness.Save(c); err != nil { return err } - onboarding.Summary(name, *model, *pipelineModel, c.Default) + onboarding.Summary(name, *model, *pipelineModel, c.Default, c.Profiles[name].Mode()) return nil } name := "" diff --git a/internal/cli/harness_transition_test.go b/internal/cli/harness_transition_test.go new file mode 100644 index 00000000..cab406ef --- /dev/null +++ b/internal/cli/harness_transition_test.go @@ -0,0 +1,175 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +// fixtureOpencode writes a fake opencode executable that answers the bounded +// model-discovery calls harness setup makes, so setup can run without a real +// harness or any network access. +func fixtureOpencode(t *testing.T, root string) string { + t.Helper() + script := filepath.Join(root, "opencode") + body := "#!/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" + if err := os.WriteFile(script, []byte(body), 0700); err != nil { + t.Fatal(err) + } + return script +} + +func writeHarnessConfig(t *testing.T, path, body string) { + t.Helper() + if err := os.WriteFile(path, []byte(body), 0600); err != nil { + t.Fatal(err) + } +} + +// TestHarnessSetupHostModeClearsDockerLinkDrivesTheRealConfigFile covers the +// Docker-linked -> host transition and host -> host idempotence by reading the +// saved JSON, not a private helper. +func TestHarnessSetupHostModeClearsDockerLinkDrivesTheRealConfigFile(t *testing.T) { + root := t.TempDir() + configPath := filepath.Join(root, "harnesses.json") + t.Setenv("PIPELINES_HARNESS_CONFIG", configPath) + script := fixtureOpencode(t, root) + writeHarnessConfig(t, configPath, `{"default":"opencode","profiles":{"opencode":{"docker_directory":"/checkout","executable":"opencode","model":"fixture/harness","pipeline_model":"fixture/stages"}}}`) + + var out bytes.Buffer + app := App{In: bytes.NewBuffer(nil), Out: &out, Err: &out} + if err := app.Run(context.Background(), []string{"harness", "setup", "opencode", "--host", "--executable", script, "--model", "fixture/harness", "--pipeline-model", "fixture/stages"}); err != nil { + t.Fatal(err) + } + saved, err := os.ReadFile(configPath) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(saved), "docker_directory") { + t.Fatalf("host setup kept a Docker link:\n%s", saved) + } + if text := out.String(); !strings.Contains(text, "Launch mode:") || !strings.Contains(text, "host") { + t.Fatalf("summary did not report host mode:\n%s", text) + } + + // host -> host leaves it absent and unchanged in mode. + if err := app.Run(context.Background(), []string{"harness", "setup", "opencode", "--host", "--executable", script, "--model", "fixture/harness", "--pipeline-model", "fixture/stages"}); err != nil { + t.Fatal(err) + } + again, err := os.ReadFile(configPath) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(again), "docker_directory") { + t.Fatalf("host -> host reintroduced a Docker link:\n%s", again) + } +} + +// TestHarnessSetupReverifiesDockerLinkBeforeSaving fails a reconfigure whose +// recorded installation no longer has compose.yaml, names the directory, and +// leaves the file byte-identical. +func TestHarnessSetupReverifiesDockerLinkBeforeSaving(t *testing.T) { + root := t.TempDir() + configPath := filepath.Join(root, "harnesses.json") + t.Setenv("PIPELINES_HARNESS_CONFIG", configPath) + script := fixtureOpencode(t, root) + // The directory exists but has no compose.yaml, so the link is unusable. + checkout := filepath.Join(root, "checkout") + if err := os.Mkdir(checkout, 0700); err != nil { + t.Fatal(err) + } + writeHarnessConfig(t, configPath, `{"default":"opencode","profiles":{"opencode":{"docker_directory":"`+checkout+`","executable":"opencode","model":"fixture/harness","pipeline_model":"fixture/stages"}}}`) + before, err := os.ReadFile(configPath) + if 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, "--model", "fixture/harness", "--pipeline-model", "fixture/stages"}) + if err == nil { + t.Fatal("setup reported success for an unverifiable Docker link") + } + if !strings.Contains(err.Error(), checkout) { + t.Fatalf("error does not name the directory: %v", err) + } + after, readErr := os.ReadFile(configPath) + if readErr != nil { + t.Fatal(readErr) + } + if !bytes.Equal(before, after) { + t.Fatalf("failed setup rewrote the config:\nbefore %s\nafter %s", before, after) + } +} + +// TestHarnessSetupKeepsVerifiedDockerLink confirms a still-verifiable Docker +// installation is preserved and its directory reported. +func TestHarnessSetupKeepsVerifiedDockerLink(t *testing.T) { + root := t.TempDir() + configPath := filepath.Join(root, "harnesses.json") + t.Setenv("PIPELINES_HARNESS_CONFIG", configPath) + script := fixtureOpencode(t, root) + checkout := filepath.Join(root, "checkout") + if err := os.Mkdir(checkout, 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(checkout, "compose.yaml"), []byte("services: {}\n"), 0600); err != nil { + t.Fatal(err) + } + writeHarnessConfig(t, configPath, `{"default":"opencode","profiles":{"opencode":{"docker_directory":"`+checkout+`","executable":"opencode","model":"fixture/harness","pipeline_model":"fixture/stages"}}}`) + + 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"}); err != nil { + t.Fatal(err) + } + saved, err := os.ReadFile(configPath) + if err != nil || !strings.Contains(string(saved), checkout) { + t.Fatalf("verified Docker link was not preserved: %s %v", saved, err) + } + if text := out.String(); !strings.Contains(text, "Docker-linked") || !strings.Contains(text, checkout) { + t.Fatalf("summary did not report Docker mode and directory:\n%s", text) + } +} + +// TestHarnessListReportsModeAndKeepsModelFields keeps the JSON compatible with +// scripts/setup-docker.py's link_host parsing (default, model, pipeline_model) +// while exposing an explicit per-profile mode. +func TestHarnessListReportsModeAndKeepsModelFields(t *testing.T) { + root := t.TempDir() + configPath := filepath.Join(root, "harnesses.json") + t.Setenv("PIPELINES_HARNESS_CONFIG", configPath) + writeHarnessConfig(t, configPath, `{"default":"opencode","profiles":{"opencode":{"docker_directory":"/checkout","executable":"opencode","model":"fixture/harness","pipeline_model":"fixture/stages"},"pi":{"executable":"pi","model":"provider/interactive","pipeline_model":"provider/stages"}}}`) + var out bytes.Buffer + app := App{In: bytes.NewBuffer(nil), Out: &out, Err: &out} + if err := app.Run(context.Background(), []string{"harness", "list", "--json"}); err != nil { + t.Fatal(err) + } + var view struct { + Default string `json:"default"` + Profiles map[string]struct { + Model string `json:"model"` + PipelineModel string `json:"pipeline_model"` + Mode string `json:"mode"` + DockerDirectory string `json:"docker_directory"` + } `json:"profiles"` + } + if err := json.Unmarshal(out.Bytes(), &view); err != nil { + t.Fatalf("harness list --json is not valid JSON: %v\n%s", err, out.String()) + } + if view.Default != "opencode" { + t.Fatalf("default = %q", view.Default) + } + opencode := view.Profiles["opencode"] + if opencode.Model != "fixture/harness" || opencode.PipelineModel != "fixture/stages" || opencode.Mode != "Docker-linked (/checkout)" { + t.Fatalf("opencode profile changed shape: %+v", opencode) + } + pi := view.Profiles["pi"] + if pi.Mode != "host" || pi.DockerDirectory != "" || pi.Model != "provider/interactive" { + t.Fatalf("pi profile did not report host mode: %+v", pi) + } +} diff --git a/internal/cli/help.go b/internal/cli/help.go index bffe35f2..d0090b87 100644 --- a/internal/cli/help.go +++ b/internal/cli/help.go @@ -60,9 +60,9 @@ Examples: pipelines submit /path/to/draft.md pipelines run "bug fix" "Fix the layout" --json -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. +Draft-first: the configured harness (Pi/OpenCode; host by default, or Docker-linked +when a checkout is linked) edits a private draft; 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. ` diff --git a/internal/cli/portable_draft_test.go b/internal/cli/portable_draft_test.go index 302cd2e8..6a03eb5b 100644 --- a/internal/cli/portable_draft_test.go +++ b/internal/cli/portable_draft_test.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "strings" "testing" "git.a-wan.net/alan/pipelines/internal/draft" @@ -80,3 +81,42 @@ func TestCLIEditDraftCanPublishToAnotherServerWithoutOriginVersion(t *testing.T) t.Fatal("publication changed retained source", err) } } + +// TestCLIForeignDraftNoticeNamesBothServersAndTargetsConfigured covers the stale +// 8081-draft case: validate and submit emit a dual-URL notice and only the +// configured server receives the submission, while the retained draft is not +// rewritten. +func TestCLIForeignDraftNoticeNamesBothServersAndTargetsConfigured(t *testing.T) { + run, destination, configured := setup(t) + foreign := "ws://127.0.0.1:8081/connect" + d, err := draft.Create("mismatch", pipeline.Template([]string{"worker"}, true), foreign, true, 0) + if err != nil { + t.Fatal(err) + } + metadata, err := os.ReadFile(d.Path + ".json") + if err != nil { + t.Fatal(err) + } + validated, err := run("validate", d.Path) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(validated, foreign) || !strings.Contains(validated, configured) { + t.Fatalf("validate notice did not name both servers:\n%s", validated) + } + submitted, err := run("submit", d.Path) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(submitted, foreign) || !strings.Contains(submitted, configured) { + t.Fatalf("submit notice did not name both servers:\n%s", submitted) + } + items, err := destination.List(context.Background()) + if err != nil || len(items) != 1 || items[0].Version != 1 { + t.Fatalf("submission did not target the configured server: %v %v", items, err) + } + retained, err := os.ReadFile(d.Path + ".json") + if err != nil || string(retained) != string(metadata) { + t.Fatalf("foreign draft metadata was rewritten: %v", err) + } +} diff --git a/internal/draft/draft.go b/internal/draft/draft.go index c1a381ca..70573f6a 100644 --- a/internal/draft/draft.go +++ b/internal/draft/draft.go @@ -30,6 +30,22 @@ func (d Draft) ForServer(server string) Draft { return d } +// Resolve projects this retained draft onto the configured server and reports a +// user-visible notice when the draft was created against a different server. +// The projection through ForServer keeps cross-server publication create-only, +// so the original version never leaks; the notice names both URLs so neither the +// CLI nor the TUI silently retargets a foreign draft. The returned notice is +// empty when the draft already matches (or records no server). +func (d Draft) Resolve(configured string) (Draft, string) { + resolved := d.ForServer(configured) + if d.Server == "" || d.Server == configured { + return resolved, "" + } + return resolved, fmt.Sprintf( + "draft was created against %s but this client is configured for %s; publishing to %s as a new pipeline (version numbers do not carry over)", + d.Server, configured, configured) +} + func Directory() (string, error) { if dir := os.Getenv("PIPELINES_DRAFT_DIR"); dir != "" { return filepath.Abs(dir) diff --git a/internal/draft/portable_test.go b/internal/draft/portable_test.go index d20125fe..08d64cf0 100644 --- a/internal/draft/portable_test.go +++ b/internal/draft/portable_test.go @@ -1,6 +1,9 @@ package draft -import "testing" +import ( + "strings" + "testing" +) func TestPublicationScopeForServer(t *testing.T) { original := Draft{Path: "/retained/draft.md", Name: "demo", Server: "ws://origin/connect", BaseVersion: 7} @@ -21,3 +24,23 @@ func TestPublicationScopeForServer(t *testing.T) { t.Fatal("unbound legacy draft lost its version guard", bound) } } + +func TestResolveReportsForeignServerAndKeepsMatchSilent(t *testing.T) { + configured := "ws://127.0.0.1:8080/connect" + foreign := Draft{Name: "stale", Server: "ws://127.0.0.1:8081/connect", BaseVersion: 4} + resolved, notice := foreign.Resolve(configured) + if notice == "" || !strings.Contains(notice, foreign.Server) || !strings.Contains(notice, configured) { + t.Fatalf("foreign notice did not name both servers: %q", notice) + } + if resolved.Server != configured || !resolved.CreateOnly || resolved.BaseVersion != 0 { + t.Fatalf("foreign draft not projected create-only: %+v", resolved) + } + match := Draft{Name: "current", Server: configured, BaseVersion: 4} + resolvedMatch, matchNotice := match.Resolve(configured) + if matchNotice != "" || resolvedMatch.CreateOnly || resolvedMatch.BaseVersion != 4 { + t.Fatalf("matching draft produced a notice or lost its guard: %q %+v", matchNotice, resolvedMatch) + } + if _, unboundNotice := (Draft{Name: "legacy"}).Resolve(configured); unboundNotice != "" { + t.Fatalf("unbound draft produced a notice: %q", unboundNotice) + } +} diff --git a/internal/harness/config.go b/internal/harness/config.go index 918992b5..6917bf74 100644 --- a/internal/harness/config.go +++ b/internal/harness/config.go @@ -37,6 +37,31 @@ func Path() (string, error) { return filepath.Join(root, "pipelines", "harnesses.json"), nil } +// Mode returns the profile's launch mode. A profile with a recorded Docker +// directory launches through that Compose installation; every other profile +// launches the host executable. It is the single mode label shared by setup's +// summary and any caller that reports where a harness runs. +func (p Profile) Mode() string { + if p.DockerDirectory == "" { + return "host" + } + return "Docker-linked (" + p.DockerDirectory + ")" +} + +// VerifyDockerLink re-checks that a recorded Docker installation still owns a +// compose.yaml, the same requirement `harness link` enforces when first +// linking. It is the single re-verification used before a Docker-linked profile +// is reconfigured or reported as usable, so a stale link is never silently kept. +func VerifyDockerLink(directory string) error { + if directory == "" { + return fmt.Errorf("no Docker installation directory is recorded; run pipelines harness setup --host for a native harness") + } + if _, err := os.Stat(filepath.Join(directory, "compose.yaml")); err != nil { + return fmt.Errorf("recorded Docker installation %s is no longer usable: %w; relink with pipelines harness link --docker-directory , or switch to a host harness with pipelines harness setup --host", directory, err) + } + return nil +} + func ValidModel(value string) bool { provider, model, ok := strings.Cut(value, "/") if !ok || provider == "" || model == "" || len(value) > 501 { @@ -134,6 +159,34 @@ func Save(c Config) error { return os.Rename(file.Name(), path) } +// ListView is the JSON shape `harness list` emits. It mirrors Config and adds a +// computed per-profile Mode so callers and scripts can read the launch mode +// without inferring it from docker_directory. The embedded Profile keeps every +// stored field (executable/model/pipeline_model/docker_directory) at the same +// level, so existing consumers such as setup-docker.py's link_host are unaffected. +type ListView struct { + Default string `json:"default"` + Profiles map[string]ProfileView `json:"profiles"` +} + +type ProfileView struct { + Profile + Mode string `json:"mode"` +} + +// List returns the configured profiles with an explicit launch mode. +func List() (ListView, error) { + c, err := Load() + if err != nil { + return ListView{}, err + } + view := ListView{Default: c.Default, Profiles: map[string]ProfileView{}} + for name, p := range c.Profiles { + view.Profiles[name] = ProfileView{Profile: p, Mode: p.Mode()} + } + return view, nil +} + func Choices() ([]string, string, error) { c, err := Load() if err != nil { diff --git a/internal/harness/onboarding.go b/internal/harness/onboarding.go index cedffa0b..2232356d 100644 --- a/internal/harness/onboarding.go +++ b/internal/harness/onboarding.go @@ -59,14 +59,17 @@ func (o Onboarding) AuthHandoff() { } } -// Summary reports the saved choices without implying inference. -func (o Onboarding) Summary(name, harnessModel, pipelineModel, defaultHarness string) { +// Summary reports the saved choices without implying inference. Mode is the +// resulting launch mode ("host" or "Docker-linked ()") so a setup run +// always states where the harness will actually run. +func (o Onboarding) Summary(name, harnessModel, pipelineModel, defaultHarness, mode string) { s := o.styles() fmt.Fprintln(o.out) fmt.Fprintln(o.out, s.title("Configuration complete")) fmt.Fprintf(o.out, " %s %s\n", s.muted("Interactive "+DisplayName(name)+" model:"), s.step(harnessModel)) fmt.Fprintf(o.out, " %s %s\n", s.muted("New "+DisplayName(name)+" pipeline model:"), s.step(pipelineModel)) fmt.Fprintf(o.out, " %s %s\n", s.muted("Default harness:"), s.step(defaultHarness)) + fmt.Fprintf(o.out, " %s %s\n", s.muted("Launch mode:"), s.step(mode)) fmt.Fprintln(o.out, s.muted(" No inference was performed; published workflows and drafts were not rewritten.")) } diff --git a/internal/harness/picker_test.go b/internal/harness/picker_test.go index cae7866d..af18fea2 100644 --- a/internal/harness/picker_test.go +++ b/internal/harness/picker_test.go @@ -149,7 +149,7 @@ func TestOnboardingPlainOutputHasHandoffAndSummary(t *testing.T) { o.Header("pi", "Configure") o.Versions("OpenCode 2.0.26 · Pi 1.1.0 · Node 22.19.0") o.AuthHandoff() - o.Summary("pi", "provider/interactive", "provider/stages", "pi") + o.Summary("pi", "provider/interactive", "provider/stages", "pi", "host") text := out.String() if strings.Contains(text, "\x1b[") { t.Fatalf("non-terminal onboarding emitted ANSI: %q", text) diff --git a/internal/tui/drafts.go b/internal/tui/drafts.go index b4288a99..f121281e 100644 --- a/internal/tui/drafts.go +++ b/internal/tui/drafts.go @@ -38,28 +38,38 @@ func (m Model) openDrafts() (tea.Model, tea.Cmd) { func (m *Model) loadDraftPreview() { m.draftTop = 0 m.draftSource = "" + m.draftNotice = "" if len(m.draftItems) == 0 { return } - source, err := draft.Read(m.draftItems[m.draftIndex].Path) + _, source, notice, err := m.readDraft(m.draftIndex) if err != nil { m.draftError = err.Error() return } m.draftSource = source + m.draftNotice = notice } -func (m Model) selectedDraft() (draft.Draft, string, error) { - if len(m.draftItems) == 0 { - return draft.Draft{}, "", fmt.Errorf("no drafts") - } - d, err := draft.Load(m.draftItems[m.draftIndex].Path) +// readDraft loads one retained draft's metadata and source once, projecting it +// onto the configured server. It returns the shared dual-URL notice when the +// draft was created against a different server so no caller silently retargets +// a foreign draft. +func (m *Model) readDraft(index int) (draft.Draft, string, string, error) { + d, err := draft.Load(m.draftItems[index].Path) if err != nil { - return d, "", err + return d, "", "", err } - d = d.ForServer(m.url) + d, notice := d.Resolve(m.url) source, err := draft.Read(d.Path) - return d, source, err + return d, source, notice, err +} + +func (m Model) selectedDraft() (draft.Draft, string, string, error) { + if len(m.draftItems) == 0 { + return draft.Draft{}, "", "", fmt.Errorf("no drafts") + } + return m.readDraft(m.draftIndex) } func (m Model) updateDrafts(msg tea.KeyMsg) (tea.Model, tea.Cmd) { @@ -123,11 +133,12 @@ func (m Model) updateDrafts(msg tea.KeyMsg) (tea.Model, tea.Cmd) { case "k", "up": m.draftTop = max(0, m.draftTop-1) case "enter", "e", "s", "v": - d, source, err := m.selectedDraft() + d, source, notice, err := m.selectedDraft() if err != nil { m.draftError = err.Error() return m, nil } + m.draftNotice = notice switch msg.String() { case "enter", "e": return m.confirmMutation("Edit retained draft?", func() tea.Cmd { return editDraftMode(d.Name, source, true, d.CreateOnly, d) }) @@ -173,7 +184,14 @@ func (m Model) draftsView(height int) string { if name == "" { name = "Unnamed draft" } - lines := []string{fmt.Sprintf("Drafts · %d/%d · %s", m.draftIndex+1, len(m.draftItems), name), d.Path, fmt.Sprintf("Create-only: %t · Base version: %d", d.CreateOnly, d.BaseVersion), m.draftError, ""} + lines := []string{fmt.Sprintf("Drafts · %d/%d · %s", m.draftIndex+1, len(m.draftItems), name), d.Path, fmt.Sprintf("Create-only: %t · Base version: %d", d.CreateOnly, d.BaseVersion)} + if m.draftNotice != "" { + // Pre-wrap the dual-URL notice to the panel width: fitBlock truncates a + // single long line, so an unwrapped notice would cut off the configured + // endpoint and the TUI would not actually name both servers. + lines = append(lines, strings.Split(ansi.Wrap("Warning: "+m.draftNotice, max(1, m.width), ""), "\n")...) + } + lines = append(lines, m.draftError, "") source := strings.Split(m.draftSource, "\n") rows := max(0, height-len(lines)-1) top := min(m.draftTop, max(0, len(source)-rows)) diff --git a/internal/tui/drafts_test.go b/internal/tui/drafts_test.go index c899683a..31929278 100644 --- a/internal/tui/drafts_test.go +++ b/internal/tui/drafts_test.go @@ -191,3 +191,42 @@ func TestDraftBrowserAcceptsOtherServerAndKeepsUnnamedDraft(t *testing.T) { t.Fatal("unnamed draft submitted") } } + +// TestDraftBrowserNoticeNamesBothServersForForeignDraft covers the stale 8081 +// draft case in the TUI: the selected foreign draft is projected onto the +// configured server (create-only) and a notice names both endpoints instead of +// silently retargeting it. +func TestDraftBrowserNoticeNamesBothServersForForeignDraft(t *testing.T) { + t.Setenv("PIPELINES_DRAFT_DIR", t.TempDir()) + foreign := "ws://127.0.0.1:8081/connect" + configured := "ws://127.0.0.1:8080/connect" + d, err := draft.Create("wrong", "source", foreign, true, 0) + if err != nil { + t.Fatal(err) + } + m := New(context.Background(), configured) + updated, _ := m.openDrafts() + m = updated.(Model) + if !strings.Contains(m.draftNotice, foreign) || !strings.Contains(m.draftNotice, configured) { + t.Fatalf("preview notice did not name both servers: %q", m.draftNotice) + } + // The notice must name both endpoints at any realistic panel width: an + // unwrapped line is truncated by fitBlock and loses the configured URL. + for _, width := range []int{60, 100} { + view := m + view.width, view.height = width, 24 + rendered := view.View() + if !strings.Contains(rendered, foreign) || !strings.Contains(rendered, configured) { + t.Fatalf("notice at width %d did not name both servers:\n%s", width, rendered) + } + } + updated, _ = m.updateDrafts(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'s'}}) + m = updated.(Model) + if !m.confirmOpen || m.pendingDraft == nil || !m.pendingDraft.createOnly || m.pendingDraft.baseVersion != 0 { + t.Fatalf("foreign draft was not projected as create-only: %+v", m.pendingDraft) + } + if !strings.Contains(m.draftNotice, foreign) || !strings.Contains(m.draftNotice, configured) { + t.Fatalf("submit lost the dual-URL notice: %q", m.draftNotice) + } + _ = d +} diff --git a/internal/tui/model.go b/internal/tui/model.go index d6f9d638..deea282c 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -95,110 +95,110 @@ func (k keyMap) ShortHelp() []key.Binding { func (k keyMap) FullHelp() [][]key.Binding { return [][]key.Binding{k.ShortHelp()} } type Model struct { - editorCheckGeneration uint64 - editorChecking bool - statusOpen bool - statusTop int - statusRequest, statusError string - systemStatus *protocol.SystemStatus - usage *protocol.UsageStats - draftOpen bool - draftItems []draft.Draft - draftIndex, draftTop int - draftError, draftSource string - ctx context.Context - url string - conn *websocket.Conn - status string - nextID uint64 - lines []string - width int - height int - help help.Model - keys keyMap - pipelines []protocol.PipelineSummary - loaded bool - notificationEndpoints []protocol.NotificationEndpoint - logSeen []bool - unread int - logOpen bool - logTop int - logPan int - paletteOpen bool - commandInput textinput.Model - commandIndex int - homeTop int - searchOpen bool - detail *protocol.PipelineDetail - detailRequest string - detailLoading bool - detailError string - pipelineTop int - graphPan int - versionsOpen bool - versionIndex int - confirmOpen bool - actionConfirm *protocol.Message - actionConfirmTop int - actionApproved bool - defaultModel string - defaultHarness string - editorDebugRunID int64 - mutationTitle string - mutationCommand func() tea.Cmd - mutationTop int - pendingDraft *editedMsg - draftNameInput textinput.Model - submitID string - submitNotice string - stageIndex int - stageTop int - stageFocus bool - stageConfigExpanded bool - reconnecting bool - requestedPipelineID int64 - requestedVersion int - runs []protocol.RunSummary - runDetail *protocol.RunDetail - runOpen bool - runForm int - runInput textinput.Model - runPrompt textarea.Model - runWorkspace string - cliRun, cliStarted, runPicker bool - cliOptions RunOptions - runPickerIndex int - runPickerInput textinput.Model - runTask string - runPaths []string - runIndex, runTop int - requestedRunID int64 - runStartRequest string - runStepIndex int - runDetailFocus bool - runCollapsed map[string]bool - runError string - runPipelineID int64 - runFailedOnly bool - runSearch textinput.Model - runSearchOpen bool - runGraphFocus bool - runGraphTop int - runGraphPan int - editorOpen bool - editorInput textinput.Model - editorIndex int - editorDraft *editedMsg - draftDeletingPath string - draftDeletingTop int - runSpinner spinner.Model - templates []protocol.Template - templateOpen, templateRaw bool - templateGraphFocus, templateConfirm bool - templateGraphTop, templateGraphPan int - templateIndex, templateTop int - templateLines []string - templateRequest, templateError string + editorCheckGeneration uint64 + editorChecking bool + statusOpen bool + statusTop int + statusRequest, statusError string + systemStatus *protocol.SystemStatus + usage *protocol.UsageStats + draftOpen bool + draftItems []draft.Draft + draftIndex, draftTop int + draftError, draftSource, draftNotice string + ctx context.Context + url string + conn *websocket.Conn + status string + nextID uint64 + lines []string + width int + height int + help help.Model + keys keyMap + pipelines []protocol.PipelineSummary + loaded bool + notificationEndpoints []protocol.NotificationEndpoint + logSeen []bool + unread int + logOpen bool + logTop int + logPan int + paletteOpen bool + commandInput textinput.Model + commandIndex int + homeTop int + searchOpen bool + detail *protocol.PipelineDetail + detailRequest string + detailLoading bool + detailError string + pipelineTop int + graphPan int + versionsOpen bool + versionIndex int + confirmOpen bool + actionConfirm *protocol.Message + actionConfirmTop int + actionApproved bool + defaultModel string + defaultHarness string + editorDebugRunID int64 + mutationTitle string + mutationCommand func() tea.Cmd + mutationTop int + pendingDraft *editedMsg + draftNameInput textinput.Model + submitID string + submitNotice string + stageIndex int + stageTop int + stageFocus bool + stageConfigExpanded bool + reconnecting bool + requestedPipelineID int64 + requestedVersion int + runs []protocol.RunSummary + runDetail *protocol.RunDetail + runOpen bool + runForm int + runInput textinput.Model + runPrompt textarea.Model + runWorkspace string + cliRun, cliStarted, runPicker bool + cliOptions RunOptions + runPickerIndex int + runPickerInput textinput.Model + runTask string + runPaths []string + runIndex, runTop int + requestedRunID int64 + runStartRequest string + runStepIndex int + runDetailFocus bool + runCollapsed map[string]bool + runError string + runPipelineID int64 + runFailedOnly bool + runSearch textinput.Model + runSearchOpen bool + runGraphFocus bool + runGraphTop int + runGraphPan int + editorOpen bool + editorInput textinput.Model + editorIndex int + editorDraft *editedMsg + draftDeletingPath string + draftDeletingTop int + runSpinner spinner.Model + templates []protocol.Template + templateOpen, templateRaw bool + templateGraphFocus, templateConfirm bool + templateGraphTop, templateGraphPan int + templateIndex, templateTop int + templateLines []string + templateRequest, templateError string } func New(ctx context.Context, url string) Model { diff --git a/scripts/setup-native.py b/scripts/setup-native.py index 1917cd20..2bba4407 100644 --- a/scripts/setup-native.py +++ b/scripts/setup-native.py @@ -8,8 +8,8 @@ and ntfy from source into a per-user prefix, generates an ntfy configuration tha mirrors compose.yaml, creates the publishing/phone accounts and writes the manifest scripts/manage.py loads. ntfy is compiled from its pinned Go module on every host because upstream publishes no macOS server binary. It reuses existing -host OpenCode configuration; model selection stays at runtime and is never -invented here. +host OpenCode configuration; it writes host (non-Docker) harness profiles for the +harnesses it detects and never invents a model. """ import argparse import importlib.util @@ -100,6 +100,78 @@ class Setup: pi = shutil.which("pi") return {"opencode": str(Path(opencode).resolve()), "pi": str(Path(pi).resolve()) if pi else ""} + # --- host harness profiles ------------------------------------------ + + MODEL_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_./:-" + + @classmethod + def _valid_model(cls, value): + if not isinstance(value, str) or len(value) > 501 or "/" not in value: + return False + provider, model = value.split("/", 1) + if not provider or not model: + return False + return all(char in cls.MODEL_CHARS for char in value) + + def harness_config_path(self): + root = Path(self.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") + return root / "pipelines" / "harnesses.json" + + def _existing_harness_config(self): + path = self.harness_config_path() + if path.is_symlink() or not path.is_file(): + return {} + try: + data = json.loads(path.read_text()) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + def configure_harnesses(self, harness, model=""): + """Write host (non-Docker) profiles for the harnesses detected on PATH. + + The native install launches host harnesses, so a Docker-era + ``docker_directory`` must be cleared rather than kept. Models come from + the explicit ``--model`` (recorded as PIPELINES_DEFAULT_MODEL) or the + existing valid profile; they are never invented. Unrelated keys and + profiles for harnesses that are not detected are preserved, matching + harness.Save. No harness is installed, upgraded or downloaded. + """ + existing = self._existing_harness_config() + profiles = existing.get("profiles") + if not isinstance(profiles, dict): + profiles = {} + merged = {name: dict(value) for name, value in profiles.items() if isinstance(value, dict)} + order = [name for name in ("opencode", "pi") if harness.get(name)] + configured = [] + for name in order: + current = merged.get(name, {}) + harness_model = current.get("model") if self._valid_model(current.get("model")) else "" + pipeline_model = current.get("pipeline_model") if self._valid_model(current.get("pipeline_model")) else "" + if name == "opencode" and self._valid_model(model): + harness_model = harness_model or model + pipeline_model = pipeline_model or model + if not harness_model or not pipeline_model: + continue + # Host mode: no docker_directory, executable is the detected host binary. + merged[name] = {"executable": harness[name], "model": harness_model, "pipeline_model": pipeline_model} + configured.append(name) + if not configured: + print("Host harness profiles were not written: no valid model was found for " + + ", ".join(order) + ". Run 'pipelines harness setup opencode --host' to configure authoring.") + return None + # Prefer the primary detected harness, so a stale Docker-era default ("pi") + # never survives a native install. + default = "opencode" if "opencode" in configured else configured[0] + data = dict(existing) + data["default"] = default + data["profiles"] = merged + path = self.harness_config_path() + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + self._write_atomic(path, (json.dumps(data, indent=2) + "\n").encode(), 0o600) + print(f"Host harness profiles written for {', '.join(configured)}; default {default} ({path}).") + return path + def resolve_prefix(self): default = Path.home() / ".local/share/pipelines" raw = self.prefix_argument or self.environ.get("PIPELINES_PREFIX") or default @@ -382,6 +454,10 @@ class Setup: resolution = self.resolve_ntfy() self.build(prefix) self.install_skill(prefix) + # The native install launches host harnesses, so write host profiles for + # the detected harnesses and clear any Docker-era link. Uses only the + # explicit --model or the existing valid profile/host configuration. + self.configure_harnesses(harness, args.model or "") lan_ip = lan.detect_lan() base_url = args.ntfy_url or f"http://{lan_ip}:{args.ntfy_port}" config_path = self.write_ntfy_config(prefix, base_url, args.ntfy_port) diff --git a/scripts/test_setup_native.py b/scripts/test_setup_native.py index e277612e..06f9fbd4 100644 --- a/scripts/test_setup_native.py +++ b/scripts/test_setup_native.py @@ -1,4 +1,5 @@ import importlib.util +import json import os from pathlib import Path import subprocess @@ -358,6 +359,87 @@ class SetupNativeTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, "no local Pipelines image"): installer.migrate_docker(prefix, replace=False) + def test_configure_harnesses_writes_host_profiles_for_detected_harness(self): + with tempfile.TemporaryDirectory() as directory: + recorder = Recorder() + installer = self.installer(directory, recorder) + prefix = Path(directory) / "prefix" + installer.configure_harnesses({"opencode": "/usr/bin/opencode", "pi": ""}, "fixture/harness") + path = installer.harness_config_path() + self.assertEqual(path, Path(directory) / "config/pipelines/harnesses.json") + config = json.loads(path.read_text()) + self.assertEqual(config["default"], "opencode") + profile = config["profiles"]["opencode"] + self.assertEqual(profile["executable"], "/usr/bin/opencode") + self.assertNotIn("docker_directory", profile) + self.assertTrue(installer._valid_model(profile["model"])) + self.assertTrue(installer._valid_model(profile["pipeline_model"])) + self.assertEqual(profile["model"], "fixture/harness") + # Detection-only: no harness install/upgrade/download was invoked. + self.assertFalse(any("opencode" in part for call in recorder.calls for part in call)) + + def test_configure_harnesses_skips_without_a_valid_model(self): + with tempfile.TemporaryDirectory() as directory: + installer = self.installer(directory, Recorder()) + path = installer.harness_config_path() + result = installer.configure_harnesses({"opencode": "/usr/bin/opencode", "pi": ""}) + self.assertIsNone(result) + self.assertFalse(path.exists(), "an invalid profile was written") + + def test_configure_harnesses_migrates_stale_docker_link_and_default(self): + with tempfile.TemporaryDirectory() as directory: + installer = self.installer(directory, Recorder()) + path = installer.harness_config_path() + path.parent.mkdir(parents=True) + path.write_text(json.dumps({ + "default": "pi", + "future": "preserve", + "profiles": { + "opencode": {"docker_directory": "/checkout", "executable": "opencode", + "model": "fixture/interactive", "pipeline_model": "fixture/stages"}, + "pi": {"docker_directory": "/checkout", "executable": "pi", + "model": "provider/interactive", "pipeline_model": "provider/stages"}, + }, + })) + installer.configure_harnesses({"opencode": "/usr/bin/opencode", "pi": "/usr/bin/pi"}) + saved = json.loads(path.read_text()) + self.assertEqual(saved["default"], "opencode") + self.assertEqual(saved["future"], "preserve") + for name in ("opencode", "pi"): + self.assertNotIn("docker_directory", saved["profiles"][name], name) + self.assertTrue(installer._valid_model(saved["profiles"][name]["model"])) + self.assertEqual(saved["profiles"]["opencode"]["executable"], "/usr/bin/opencode") + + def test_full_run_migrates_docker_harness_config_to_host(self): + with tempfile.TemporaryDirectory() as directory: + recorder = Recorder() + installer = self.installer(directory, recorder) + prefix = Path(directory) / "prefix" + path = installer.harness_config_path() + path.parent.mkdir(parents=True) + path.write_text(json.dumps({ + "default": "pi", + "profiles": { + "opencode": {"docker_directory": "/checkout", "executable": "opencode", + "model": "fixture/interactive", "pipeline_model": "fixture/stages"}, + "pi": {"docker_directory": "/checkout", "executable": "pi", + "model": "provider/interactive", "pipeline_model": "provider/stages"}, + }, + })) + with patch.object(setup_native.shutil, "which", side_effect=self.which_all(opencode="/usr/bin/opencode", pi="/usr/bin/pi")), \ + patch.object(setup_native.lan, "detect_lan", return_value="192.168.1.20"), \ + patch.object(setup_native.configure, "host_timezone", return_value="Europe/London"): + installer.run(setup_native.arguments([])) + saved = json.loads(path.read_text()) + self.assertEqual(saved["default"], "opencode", "stale Docker-era pi default survived") + self.assertNotIn("docker_directory", saved["profiles"]["opencode"]) + self.assertTrue(saved["profiles"]["opencode"]["executable"].endswith("opencode")) + self.assertTrue(installer._valid_model(saved["profiles"]["opencode"]["model"])) + # Detection-only: no harness install/upgrade/download command recorded. + self.assertFalse(any("opencode" in part for call in recorder.calls for part in call)) + self.assertFalse(any(part == "pi" for call in recorder.calls for part in call)) + self.assertFalse(any("npm" == part for call in recorder.calls for part in call)) + if __name__ == "__main__": unittest.main()