Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <server-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 <file>` for a
private CA.
Expand Down
125 changes: 109 additions & 16 deletions cmd/promptctl/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"time"
Expand Down Expand Up @@ -321,21 +322,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)
}
}

Expand All @@ -346,6 +362,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")
Expand All @@ -362,26 +379,102 @@ 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 <server-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 {
return !sameIgnoringLineEndings(blobContent(tree, p), diskContent(p))
}
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])
}
}

Expand Down
117 changes: 117 additions & 0 deletions cmd/promptctl/publish_committed_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
Loading