From b094f0bc1e28c619d09c3a8db0601ce9a5df6c1f Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 15 Nov 2026 09:48:33 +0530 Subject: [PATCH 1/2] fix(publish): send committed content, refuse non-serving branches, push one branch push -server and publish read prompts from the working tree and sent them with no Branch or Message, so on git branch dev an uncommitted edit went live on the server's main (what agents read). push also used go-git's default refspec and pushed every local branch. - Inside a repo, prompts are read from the HEAD commit; a prompt with uncommitted changes is refused. A CRLF checkout of an LF blob is not a change (go-git ignores core.autocrlf when it hashes racy/touched files). - Without -branch, only git main/master/prod may publish to server main; other branches must name the server branch with -branch. - Each version carries the HEAD commit subject and hash as its message. - push pushes only the current branch and refuses a detached HEAD. - Outside a git repo, publish still sends plain files as they are on disk. Fixes #16 --- README.md | 5 + cmd/promptctl/main.go | 125 +++++++++++++++++++++--- cmd/promptctl/publish_committed_test.go | 117 ++++++++++++++++++++++ 3 files changed, 231 insertions(+), 16 deletions(-) create mode 100644 cmd/promptctl/publish_committed_test.go diff --git a/README.md b/README.md index a6abc56..2e325a4 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,11 @@ flowchart LR subscribed agents are notified in the same step. Publishing is idempotent (unchanged content is a no-op), so only real changes fire a notification. Git stays the source of truth; the server is the live serving copy. +- `push` / `publish` send what is **committed** at HEAD and refuse prompts with + uncommitted changes. They publish to the server's `main` (what agents read) + only from git `main`, `master` or `prod`; from any other branch pass + `-branch `. Each version records the HEAD commit subject as its + message. `push` pushes only the current branch. - `push` / `publish` accept `-tls` for TLS servers. The server certificate is verified against the system root CAs, or against `-ca-cert ` for a private CA. diff --git a/cmd/promptctl/main.go b/cmd/promptctl/main.go index bf77129..cfc4c1a 100644 --- a/cmd/promptctl/main.go +++ b/cmd/promptctl/main.go @@ -321,21 +321,36 @@ func commitFile(r *git.Repository, wt *git.Worktree, path, content, msg string) return wt.Commit(msg, &git.CommitOptions{Author: author(r)}) } -// pushCmd validates, pushes to the git remote, and — if -server is given — -// publishes every prompt to that live server so subscribers are notified. -// Publishing is idempotent server-side, so only actually-changed prompts notify. +// pushCmd validates, pushes the current branch to the git remote, and — if +// -server is given — publishes every prompt committed at HEAD to that live +// server so subscribers are notified. Publishing is idempotent server-side, so +// only actually-changed prompts notify. func pushCmd(args []string) { fs := flag.NewFlagSet("push", flag.ExitOnError) server := fs.String("server", "", "after pushing, publish prompts to this live server (host:port)") useTLS := fs.Bool("tls", false, "use TLS for -server") caCert := fs.String("ca-cert", "", "CA cert for TLS -server (default: system roots)") + branch := fs.String("branch", "", "server branch to publish to (default: main, only from git main/master/prod)") fs.Parse(args) validateAll() r := openRepo() - reportSync("pushed", r.Push(&git.PushOptions{Auth: authFor(r), Progress: os.Stdout})) + head, err := r.Head() + if err != nil { + log.Fatal(err) + } + if !head.Name().IsBranch() { + log.Fatal("push needs a checked-out branch (HEAD is detached)") + } + var plan []publication + if *server != "" { + // Decide what would be published before anything leaves the machine. + plan = committedPublications(r, diskPromptFiles(), *branch) + } + spec := config.RefSpec(head.Name().String() + ":" + head.Name().String()) + reportSync("pushed", r.Push(&git.PushOptions{Auth: authFor(r), Progress: os.Stdout, RefSpecs: []config.RefSpec{spec}})) if *server != "" { - publishToServer(*server, *useTLS, *caCert, diskPromptFiles()) + publishToServer(*server, *useTLS, *caCert, plan) } } @@ -346,6 +361,7 @@ func publishCmd(args []string) { server := fs.String("server", "", "live server address (host:port)") useTLS := fs.Bool("tls", false, "use TLS") caCert := fs.String("ca-cert", "", "CA cert for TLS (default: system roots)") + branch := fs.String("branch", "", "server branch to publish to (default: main, only from git main/master/prod)") fs.Parse(args) if *server == "" { log.Fatal("publish needs -server host:port") @@ -362,26 +378,103 @@ func publishCmd(args []string) { } } } - publishToServer(*server, *useTLS, *caCert, paths) + var plan []publication + if r, err := git.PlainOpen("."); err == nil { + plan = committedPublications(r, paths, *branch) + } else { + // Not a git repo: plain files, published as they are on disk. + for _, p := range paths { + plan = append(plan, publication{path: p, template: diskContent(p), branch: *branch}) + } + } + publishToServer(*server, *useTLS, *caCert, plan) +} + +// publication is one prompt version headed for the server. +type publication struct { + path, template, message, branch string +} + +// servingBranches may publish to the server's main, the branch agents read. +// dev -> staging -> prod are git branches and prod is what gets published. +var servingBranches = []string{"main", "master", "prod"} + +// committedPublications reads each prompt from the HEAD commit, so git stays the +// source of truth: uncommitted edits are refused rather than silently going +// live. Without -branch, only a serving git branch may publish to server main; +// anything else (dev, a feature branch) has to name the server branch it means. +func committedPublications(r *git.Repository, paths []string, serverBranch string) []publication { + head, err := r.Head() + if err != nil { + log.Fatalf("nothing committed to publish: %v", err) + } + if serverBranch == "" && !(head.Name().IsBranch() && slices.Contains(servingBranches, head.Name().Short())) { + log.Fatalf("on %s: refusing to publish to the server's main (what agents read) from a non-serving branch; "+ + "switch to %s, or pass -branch ", head.Name().Short(), strings.Join(servingBranches, "/")) + } + c, err := r.CommitObject(head.Hash()) + if err != nil { + log.Fatal(err) + } + tree, err := c.Tree() + if err != nil { + log.Fatal(err) + } + st, err := worktree(r).Status() + if err != nil { + log.Fatal(err) + } + msg := fmt.Sprintf("%s (%s)", firstLine(c.Message), c.Hash.String()[:12]) + var plan []publication + for _, p := range paths { + if uncommitted(st, tree, p) { + log.Fatalf("%s has uncommitted changes; commit them first (publish sends what is committed)", p) + } + t := blobContent(tree, p) + if t == "" { + log.Fatalf("%s is not in the HEAD commit", p) + } + plan = append(plan, publication{path: p, template: t, message: msg, branch: serverBranch}) + } + return plan } -// publishToServer validates and PublishPrompts each prompt file to the server. -func publishToServer(server string, useTLS bool, caCert string, paths []string) { +// uncommitted reports whether p differs from the commit whose tree is given. +// Clean files are absent from the status map (st.File would invent an +// "untracked" entry for them). go-git ignores core.autocrlf whenever it has to +// hash a file (a racy index entry, a touched file), so a CRLF checkout of an LF +// blob shows as modified on Windows; such a file only counts when it differs by +// more than line endings. +func uncommitted(st git.Status, tree *object.Tree, p string) bool { + fs, ok := st[p] + if !ok { + return false + } + if fs.Staging == git.Unmodified && fs.Worktree == git.Modified { + _, _, changed := changedLines(blobContent(tree, p), diskContent(p)) + return changed + } + return fs.Staging != git.Unmodified || fs.Worktree != git.Unmodified +} + +// publishToServer validates and PublishPrompts each prompt to the server. +func publishToServer(server string, useTLS bool, caCert string, plan []publication) { conn := dial(server, useTLS, caCert) defer conn.Close() client := pb.NewPromptServiceClient(conn) ctx := authCtx() - for _, p := range paths { - t := diskContent(p) - slots := deriveSlots(t) - if err := validate.Prompt(pathToURI(p), t, slots); err != nil { - log.Fatalf("invalid %s: %v", p, err) + for _, p := range plan { + slots := deriveSlots(p.template) + if err := validate.Prompt(pathToURI(p.path), p.template, slots); err != nil { + log.Fatalf("invalid %s: %v", p.path, err) } - resp, err := client.PublishPrompt(ctx, &pb.PublishPromptRequest{Uri: pathToURI(p), Template: t, Slots: slots}) + resp, err := client.PublishPrompt(ctx, &pb.PublishPromptRequest{ + Uri: pathToURI(p.path), Template: p.template, Slots: slots, Message: p.message, Branch: p.branch, + }) if err != nil { - log.Fatalf("publish %s: %v", p, err) + log.Fatalf("publish %s: %v", p.path, err) } - fmt.Printf("published %s (%s)\n", pathToURI(p), resp.GetVersionHash()[:12]) + fmt.Printf("published %s (%s)\n", pathToURI(p.path), resp.GetVersionHash()[:12]) } } diff --git a/cmd/promptctl/publish_committed_test.go b/cmd/promptctl/publish_committed_test.go new file mode 100644 index 0000000..739b506 --- /dev/null +++ b/cmd/promptctl/publish_committed_test.go @@ -0,0 +1,117 @@ +package main + +import ( + "os" + "os/exec" + "strings" + "testing" + + "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/plumbing" + "github.com/go-git/go-git/v5/plumbing/object" +) + +// publishRepo makes a repo with acme/a.prompt committed on prod and dev +// (different content), checked out on the given branch, and chdirs into it. +func publishRepo(t *testing.T, branch string) *git.Repository { + t.Helper() + dir := t.TempDir() + t.Chdir(dir) + r, err := git.PlainInit(dir, false) + if err != nil { + t.Fatal(err) + } + wt, _ := r.Worktree() + sig := &object.Signature{Name: "t", Email: "t@t"} + commit := func(content, msg string) { + t.Helper() + os.MkdirAll("acme", 0o755) + if err := os.WriteFile("acme/a.prompt", []byte(content), 0o644); err != nil { + t.Fatal(err) + } + wt.Add("acme/a.prompt") + if _, err := wt.Commit(msg, &git.CommitOptions{Author: sig}); err != nil { + t.Fatal(err) + } + } + commit("A prod {x}\n", "ship a\n\nbody") + head, _ := r.Head() + for _, b := range []string{"prod", "dev"} { + r.Storer.SetReference(plumbing.NewHashReference(plumbing.NewBranchReferenceName(b), head.Hash())) + } + wt.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName("dev")}) + commit("A dev {x}\n", "dev work") + if err := wt.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName(branch)}); err != nil { + t.Fatal(err) + } + return r +} + +func TestPublishSendsCommittedContentWithMessage(t *testing.T) { + r := publishRepo(t, "prod") + plan := committedPublications(r, []string{"acme/a.prompt"}, "") + if len(plan) != 1 { + t.Fatalf("plan = %+v", plan) + } + p := plan[0] + if p.template != "A prod {x}\n" || p.branch != "" || !strings.HasPrefix(p.message, "ship a (") { + t.Errorf("publication = %+v, want prod's committed content, server main, HEAD subject as message", p) + } +} + +func TestPublishFromDevNeedsExplicitBranch(t *testing.T) { + r := publishRepo(t, "dev") + plan := committedPublications(r, []string{"acme/a.prompt"}, "dev") + if plan[0].branch != "dev" || plan[0].template != "A dev {x}\n" { + t.Errorf("with -branch dev: %+v, want dev content on server branch dev", plan[0]) + } + + out, failed := runPublishCase(t, "dev-to-main") + if !failed || !strings.Contains(out, "non-serving branch") { + t.Errorf("dev without -branch: failed=%v out=%q, want refusal", failed, out) + } +} + +// A CRLF checkout of an LF blob (core.autocrlf on Windows) is not an +// uncommitted change, even when go-git's status reports it as modified. +func TestPublishIgnoresLineEndingOnlyDifferences(t *testing.T) { + r := publishRepo(t, "prod") + if err := os.WriteFile("acme/a.prompt", []byte("A prod {x}\r\n"), 0o644); err != nil { + t.Fatal(err) + } + plan := committedPublications(r, []string{"acme/a.prompt"}, "") + if plan[0].template != "A prod {x}\n" { + t.Errorf("template = %q, want the committed LF content", plan[0].template) + } +} + +func TestPublishRefusesUncommittedChanges(t *testing.T) { + out, failed := runPublishCase(t, "dirty-prod") + if !failed || !strings.Contains(out, "uncommitted changes") { + t.Errorf("dirty prompt on prod: failed=%v out=%q, want refusal", failed, out) + } +} + +// runPublishCase runs one refusal scenario in a child process, since +// committedPublications exits via log.Fatal. +func runPublishCase(t *testing.T, name string) (string, bool) { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestPublishHelperProcess$") + cmd.Env = append(os.Environ(), "PROMPTCTL_PUBLISH_CASE="+name) + out, err := cmd.CombinedOutput() + return string(out), err != nil +} + +func TestPublishHelperProcess(t *testing.T) { + switch os.Getenv("PROMPTCTL_PUBLISH_CASE") { + case "dev-to-main": + committedPublications(publishRepo(t, "dev"), []string{"acme/a.prompt"}, "") + case "dirty-prod": + r := publishRepo(t, "prod") + os.WriteFile("acme/a.prompt", []byte("A UNCOMMITTED {x}\n"), 0o644) + committedPublications(r, []string{"acme/a.prompt"}, "") + default: + t.Skip("helper for runPublishCase") + } + os.Exit(0) +} From ea43336f1137d6d2d625da7eae172f2b01cb5c6b Mon Sep 17 00:00:00 2001 From: unknown Date: Sun, 15 Nov 2026 10:40:34 +0530 Subject: [PATCH 2/2] refactor(publish): compare line endings with a local helper changedLines came from #12, reverted in #33; use sameIgnoringLineEndings and import slices directly. --- cmd/promptctl/main.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/promptctl/main.go b/cmd/promptctl/main.go index cfc4c1a..c7a3e64 100644 --- a/cmd/promptctl/main.go +++ b/cmd/promptctl/main.go @@ -23,6 +23,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "sort" "strings" "time" @@ -451,8 +452,7 @@ func uncommitted(st git.Status, tree *object.Tree, p string) bool { return false } if fs.Staging == git.Unmodified && fs.Worktree == git.Modified { - _, _, changed := changedLines(blobContent(tree, p), diskContent(p)) - return changed + return !sameIgnoringLineEndings(blobContent(tree, p), diskContent(p)) } return fs.Staging != git.Unmodified || fs.Worktree != git.Unmodified }