From 0f07f8194c31cf05da30307ff7afae8d3db76a17 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Thu, 12 Nov 2026 16:19:27 +0100 Subject: [PATCH 1/3] gate: refuse a publish into a repository whose claim this session does not hold `agentsync gate --hook` answers a Claude Code PreToolUse payload. For gitpush, ghmerge, ghrelease, ghpr, ghissue, ghrun and ghrel it resolves the target repository and denies when another session holds the claim (naming holder and expiry) or when nobody does. It allows when this session holds it, including through an organisation claim, and allows whenever it cannot read: payload, claims directory, remote, session identity. lease.Store.Covering lists the leases about a repository: itself, its organisation, or the bare name. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 19 ++ cmd/agentsync/gate.go | 435 +++++++++++++++++++++++++++++++++++++ cmd/agentsync/gate_test.go | 296 +++++++++++++++++++++++++ cmd/agentsync/main.go | 4 +- lease/lease.go | 25 +++ lease/lease_test.go | 36 +++ 6 files changed, 813 insertions(+), 2 deletions(-) create mode 100644 cmd/agentsync/gate.go create mode 100644 cmd/agentsync/gate_test.go diff --git a/README.md b/README.md index 2416ded..43daf4d 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,27 @@ happened to message and ask. agentsync mem-verify [--repair=false] agentsync orphans agentsync mem-fold [--section H] [--hub NAME] [--dry-run] + agentsync gate --hook # PreToolUse payload on stdin + agentsync gate ... agentsync whoami +`gate` is what makes the claim more than advice. As a Claude Code PreToolUse +hook it reads the Bash command and, for `gitpush`, `ghmerge`, `ghrelease`, +`ghpr`, `ghissue`, `ghrun` and `ghrel`, resolves the target repository (an +`owner/repo` or GitHub URL argument, else the remote of the working directory or +of `-C`) and **denies** it when another session holds the claim (naming the +holder and expiry) or when nobody does ("claim it first" — an expired claim is +no claim). It allows when this session holds it, an organisation claim covering +the repository counting. The session is `AGENTSYNC_OWNER`, else the payload's +`session_id`, else `CLAUDE_CODE_SESSION_ID` — the identity `claim` writes under. +A refusal is not a verdict: an unreadable payload, claims directory or remote, +an unknown session, or `ghrelease backfill` all allow, and say so on stderr. +It was written after go-scikit pushed and merged `go-numerics/optimize#62` on a +claim that had lapsed and been taken by another session. + + {"hooks": {"PreToolUse": [{"matcher": "Bash", + "hooks": [{"type": "command", "command": "agentsync gate --hook"}]}]}} + `tell` is the answer to a refusal, which until 2026-10-11 was a dead end. A refusal names the holder and prints their note — which tells the refused session where not to work and gives it nowhere to reply. That day a session was refused diff --git a/cmd/agentsync/gate.go b/cmd/agentsync/gate.go new file mode 100644 index 0000000..c6a1c4d --- /dev/null +++ b/cmd/agentsync/gate.go @@ -0,0 +1,435 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" + + "github.com/go-agentsync/agentsync/lease" +) + +// gate refuses a publishing command aimed at a repository whose claim the +// session does not hold. +// +// It exists because the claim was advisory and nothing read it at the moment +// that mattered. Two recorded occurrences: 2026-09-02, and 2026-11-12, when one +// session's claim on go-numerics/optimize lapsed, another session claimed it, +// and the first one pushed and merged #62 without claiming again. Nothing was +// damaged; nothing refused it either. +// +// # WHO "THIS SESSION" IS +// +// The same rule as `claim` and `whoami` (owner), with one addition that only a +// hook can make: the PreToolUse payload carries the session's own id. +// +// 1. AGENTSYNC_OWNER, if set -- the explicit override `claim` honours first. +// 2. the payload's session_id -- authoritative, and equal to the +// CLAUDE_CODE_SESSION_ID that `claim` runs under when Claude Code starts it. +// 3. CLAUDE_CODE_SESSION_ID in the hook's own environment. +// +// With none of the three the gate cannot tell whose claim to look for, and +// allows: owner()'s "unidentified-" fallback would match no lease and so +// refuse every publish on the machine. +// +// # WHAT IT BLOCKS +// +// ONE CONDITION: a definite finding about a publishing command whose target +// repository it resolved. A payload it cannot read, a command it cannot parse, +// a repository it cannot name, a claims directory it cannot open -- all allow, +// and say so on stderr. About 25 sessions share this machine and a gate that +// halted them all because it could not read a file would be a worse defect than +// the one it is here to catch. A refusal is not a verdict. +// +// The decision travels in the JSON on stdout, exit status always 0, so a +// failing exit cannot be mistaken for a block. +const gateUsage = "usage: agentsync gate --hook (PreToolUse payload on stdin)\n" + + " agentsync gate ... (would a publish into it be allowed for this session?)" + +// gated are the programs that write to a repository. +var gated = map[string]bool{ + "gitpush": true, "ghmerge": true, "ghrelease": true, "ghpr": true, + "ghissue": true, "ghrun": true, "ghrel": true, +} + +// gateEnv is everything the decision reads, injectable so no test touches the +// real claims directory, clock, environment or git. +type gateEnv struct { + store lease.Store + owner string // who is asking; in hook mode resolved from the three below + // override is AGENTSYNC_OWNER, session is CLAUDE_CODE_SESSION_ID; the + // payload's session_id sits between them. + override, session string + now func() time.Time + remote func(dir, name string) (string, error) // the URL of a git remote + home string +} + +func gate(args []string) error { + fs := flag.NewFlagSet("gate", flag.ExitOnError) + hook := fs.Bool("hook", false, "read a PreToolUse payload on stdin and answer it") + if err := fs.Parse(args); err != nil { + return err + } + env := gateEnv{store: store(), now: time.Now, remote: gitRemote, home: home()} + if *hook { + env.override, env.session = os.Getenv("AGENTSYNC_OWNER"), os.Getenv("CLAUDE_CODE_SESSION_ID") + gateHook(os.Stdin, os.Stdout, os.Stderr, env) + return nil // always 0: the decision is in the JSON + } + if fs.NArg() == 0 { + return errors.New(gateUsage) + } + env.owner = owner() + denied := false + for _, r := range fs.Args() { + if msg := env.decide(r, os.Stderr); msg != "" { + denied = true + fmt.Println(msg) + } else { + fmt.Printf("allowed %s\n", r) + } + } + if denied { + return errUnavailable + } + return nil +} + +func firstSet(vs ...string) string { + for _, v := range vs { + if v != "" { + return v + } + } + return "" +} + +// gateHook answers one PreToolUse payload. It always returns normally; the +// caller exits 0. +func gateHook(stdin io.Reader, out, errOut io.Writer, env gateEnv) { + var p struct { + SessionID string `json:"session_id"` + Cwd string `json:"cwd"` + ToolName string `json:"tool_name"` + ToolInput struct { + Command string `json:"command"` + } `json:"tool_input"` + } + b, err := io.ReadAll(stdin) + if err != nil || json.Unmarshal(b, &p) != nil { + fmt.Fprintln(errOut, "agentsync gate: could not read the hook payload; allowing (a refusal is not a verdict)") + return + } + if p.ToolName != "" && p.ToolName != "Bash" { + return + } + invs := invocations(p.ToolInput.Command, p.Cwd, env.home) + if len(invs) == 0 { + return + } + env.owner = firstSet(env.override, p.SessionID, env.session) + if env.owner == "" { + fmt.Fprintln(errOut, "agentsync gate: cannot tell which session this is; allowing (a refusal is not a verdict)") + return + } + for _, inv := range invs { + repo, err := env.target(inv) + if err != nil { + fmt.Fprintf(errOut, "agentsync gate: %s: %v; allowing (a refusal is not a verdict)\n", inv.prog, err) + continue + } + if msg := env.decide(repo, errOut); msg != "" { + _ = json.NewEncoder(out).Encode(map[string]any{ + "hookSpecificOutput": map[string]any{ + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": msg, + }, + }) + return + } + } +} + +// decide returns the refusal for publishing into repo, or "" to allow. +func (g gateEnv) decide(repo string, errOut io.Writer) string { + if info, err := os.Stat(g.store.Dir); err != nil || !info.IsDir() { + // A store that is not there is not a store with nothing in it: the first + // would refuse every session on a machine where agentsync never ran. + fmt.Fprintf(errOut, "agentsync gate: claims directory %s unreadable; allowing (a refusal is not a verdict)\n", g.store.Dir) + return "" + } + ls, err := g.store.Covering(repo) + if err != nil { + fmt.Fprintf(errOut, "agentsync gate: %v; allowing (a refusal is not a verdict)\n", err) + return "" + } + now := g.now() + var other, expired *lease.Lease + for i := range ls { + l := ls[i] + switch { + case l.Expired(now): + if expired == nil || l.Expires.After(expired.Expires) { + expired = &ls[i] + } + case l.Owner == g.owner: + return "" // this session holds it + case other == nil: + other = &ls[i] + } + } + if other != nil { + note := "" + if other.Note != "" { + note = fmt.Sprintf(" (%q)", other.Note) + } + return fmt.Sprintf("agentsync: %s is claimed by another session, %s, until %s%s.\n"+ + "This command publishes into it. Leave it to the holder, send them a message (agentsync tell %s ...), "+ + "or wait for the lease: agentsync claim --wait 45m %s", + repo, short(other.Owner), other.Expires.Format("15:04:05"), note, repo, repo) + } + why := "no session holds " + repo + if expired != nil { + who := "the last claim, by " + short(expired.Owner) + "," + if expired.Owner == g.owner { + who = "this session's claim" + } + why += fmt.Sprintf(": %s expired at %s", who, expired.Expires.Format("15:04:05")) + } + return fmt.Sprintf("agentsync: %s.\nThis command publishes into it. Claim it first: agentsync claim --note \"\" %s -- then retry.", why, repo) +} + +// invocation is one publishing command found in a Bash command line, with the +// directory it will run in. +type invocation struct { + prog string + args []string + dir string +} + +// invocations finds the gated programs in a command line. +// +// It matches the PROGRAM of each simple command, not the word anywhere in the +// text: `echo gitpush` and a commit message that mentions ghmerge publish +// nothing. The cost is that a here-document whose body has a line beginning +// with one of these words is read as that command; the gate then asks for a +// claim the session ought to hold anyway. +// +// `cd X &&` is followed, because a push is usually written `cd repo && gitpush`. +func invocations(cmd, cwd, homeDir string) []invocation { + dir := cwd + var out []invocation + for _, seg := range splitCommand(cmd) { + i := 0 + for i < len(seg) && (isAssignment(seg[i]) || seg[i] == "env" || seg[i] == "command" || + seg[i] == "exec" || seg[i] == "time" || seg[i] == "nohup") { + i++ + } + if i >= len(seg) { + continue + } + prog, args := seg[i], seg[i+1:] + if prog == "cd" { + for len(args) > 0 && strings.HasPrefix(args[0], "-") { + args = args[1:] + } + if len(args) > 0 { + dir = resolveDir(dir, args[0], homeDir) + } + continue + } + base := filepath.Base(prog) + if gated[base] { + out = append(out, invocation{prog: base, args: args, dir: dir}) + } + } + return out +} + +var assignRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*=`) + +func isAssignment(s string) bool { return assignRe.MatchString(s) } + +func resolveDir(cur, to, homeDir string) string { + switch { + case to == "~" || strings.HasPrefix(to, "~/"): + to = filepath.Join(homeDir, strings.TrimPrefix(to, "~")) + case to == "$HOME" || strings.HasPrefix(to, "$HOME/"): + to = filepath.Join(homeDir, strings.TrimPrefix(to, "$HOME")) + case strings.Contains(to, "$"): + return cur // cannot know; keep the directory we had + } + if filepath.IsAbs(to) { + return filepath.Clean(to) + } + if cur == "" { + return to + } + return filepath.Join(cur, to) +} + +// splitCommand splits a shell command line into simple commands, each a list of +// words, honouring quotes and backslashes. Operators (; & | newline and +// parentheses) end a command. It is not a shell: anything it cannot follow +// simply yields words that match no gated program, which allows. +func splitCommand(s string) [][]string { + var segs [][]string + var cur []string + var tok strings.Builder + in := false + endWord := func() { + if in { + cur = append(cur, tok.String()) + tok.Reset() + in = false + } + } + endCmd := func() { + endWord() + if len(cur) > 0 { + segs = append(segs, cur) + cur = nil + } + } + rs := []rune(s) + for i := 0; i < len(rs); i++ { + c := rs[i] + switch { + case c == '\'': + in = true + for i++; i < len(rs) && rs[i] != '\''; i++ { + tok.WriteRune(rs[i]) + } + case c == '"': + in = true + for i++; i < len(rs) && rs[i] != '"'; i++ { + if rs[i] == '\\' && i+1 < len(rs) { + i++ + } + tok.WriteRune(rs[i]) + } + case c == '\\' && i+1 < len(rs): + in = true + i++ + tok.WriteRune(rs[i]) + case c == ' ' || c == '\t': + endWord() + case c == '\n' || c == ';' || c == '&' || c == '|' || c == '(' || c == ')': + endCmd() + default: + in = true + tok.WriteRune(c) + } + } + endCmd() + return segs +} + +var repoRe = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`) + +// valueFlags take the NEXT word as their value, so that word is not a repository. +var valueFlags = map[string]bool{ + "--evidence": true, "--issues-waiver": true, "--token-file": true, "--wait": true, + "--waive": true, "--title": true, "--body-file": true, "--notes-file": true, + "--ref": true, "--input": true, "--inputs-file": true, "--confirm": true, + "--backfill-max": true, "-o": true, "--push-option": true, "--receive-pack": true, +} + +// target names the repository a publishing command writes to, as owner/repo. +func (g gateEnv) target(inv invocation) (string, error) { + dir, args := inv.dir, inv.args + remote := "" + explicit := "" + for i := 0; i < len(args); i++ { + a := args[i] + if a == "backfill" && inv.prog == "ghrelease" { + return "", errors.New("backfill spans many repositories") + } + switch { + case a == "-C" && i+1 < len(args): + i++ + dir = resolveDir(dir, args[i], g.home) + case a == "--repo" || a == "-repo" || a == "-R": + if i+1 < len(args) { + i++ + explicit = args[i] + } + case strings.HasPrefix(a, "--repo="), strings.HasPrefix(a, "-repo="): + explicit = a[strings.Index(a, "=")+1:] + case valueFlags[a]: + i++ + case strings.HasPrefix(a, "-"): + case inv.prog == "gitpush": + if remote == "" { + remote = a + } + case explicit == "" && inv.prog != "gitpush" && ownerRepo(a) != "": + explicit = a + } + } + if explicit == "" && inv.prog == "gitpush" && remote != "" { + if r := ownerRepo(remote); r != "" { + return r, nil // pushing to a URL or an owner/repo directly + } + } + if explicit != "" { + if r := ownerRepo(explicit); r != "" { + return r, nil + } + return "", fmt.Errorf("cannot read a repository from %q", explicit) + } + if remote == "" { + remote = "origin" + } + if dir == "" { + return "", errors.New("no repository named and no working directory") + } + u, err := g.remote(dir, remote) + if err != nil { + return "", fmt.Errorf("remote %q of %s: %v", remote, dir, err) + } + if r := ownerRepo(u); r != "" { + return r, nil + } + return "", fmt.Errorf("remote %q of %s is %q, not an owner/repo", remote, dir, u) +} + +// ownerRepo reduces an owner/repo, a GitHub URL (of the repository or of a pull +// request in it) or an SSH remote to "owner/repo", or "" when it is none. +func ownerRepo(s string) string { + if strings.Contains(s, "://") || strings.Contains(s, "@") || strings.Contains(s, "github.com") { + parts := strings.Split(lease.Normalize(s), "/") + if len(parts) >= 2 && repoRe.MatchString(parts[0]+"/"+parts[1]) { + return parts[0] + "/" + parts[1] + } + return "" + } + if repoRe.MatchString(s) && !strings.HasPrefix(s, ".") { + return lease.Normalize(s) + } + return "" +} + +// gitRemote reads the URL of a remote of the checkout in dir. +func gitRemote(dir, name string) (string, error) { + if strings.HasPrefix(name, "-") { + return "", errors.New("not a remote name") + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + b, err := exec.CommandContext(ctx, "git", "-C", dir, "remote", "get-url", name).Output() + if err != nil { + return "", err + } + return strings.TrimSpace(string(b)), nil +} diff --git a/cmd/agentsync/gate_test.go b/cmd/agentsync/gate_test.go new file mode 100644 index 0000000..6ea7dec --- /dev/null +++ b/cmd/agentsync/gate_test.go @@ -0,0 +1,296 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-agentsync/agentsync/lease" +) + +var gateNow = time.Date(2026, 11, 12, 16, 0, 0, 0, time.UTC) + +// gateFixture returns an env over a real claims directory whose leases are +// taken through the store, so the files are exactly what `claim` writes. +func gateFixture(t *testing.T) (gateEnv, lease.Store) { + t.Helper() + s := lease.Store{Dir: filepath.Join(t.TempDir(), "locks"), Now: func() time.Time { return gateNow }} + if err := os.MkdirAll(s.Dir, 0o755); err != nil { + t.Fatal(err) + } + remotes := map[string]string{ + "/work/opt:origin": "https://github.com/go-numerics/optimize.git", + "/work/opt:fork": "git@github.com:me/optimize.git", + } + return gateEnv{ + store: s, now: func() time.Time { return gateNow }, home: "/home/u", + override: "", session: "", + remote: func(dir, name string) (string, error) { + if u, ok := remotes[dir+":"+name]; ok { + return u, nil + } + return "", errors.New("no such remote") + }, + }, s +} + +func payload(t *testing.T, session, cwd, command string) *bytes.Reader { + t.Helper() + b, err := json.Marshal(map[string]any{ + "session_id": session, "cwd": cwd, "tool_name": "Bash", + "tool_input": map[string]any{"command": command}, + }) + if err != nil { + t.Fatal(err) + } + return bytes.NewReader(b) +} + +func ask(env gateEnv, in *bytes.Reader) (denied bool, reason, stderr string) { + var out, errOut bytes.Buffer + gateHook(in, &out, &errOut, env) + var r struct { + H struct { + D string `json:"permissionDecision"` + R string `json:"permissionDecisionReason"` + } `json:"hookSpecificOutput"` + } + if out.Len() > 0 { + _ = json.Unmarshal(out.Bytes(), &r) + } + return r.H.D == "deny", r.H.R, errOut.String() +} + +const me, them = "11111111-aaaa-bbbb-cccc-000000000001", "22222222-aaaa-bbbb-cccc-000000000002" + +func TestAClaimHeldByThisSessionAllows(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("go-numerics/optimize", me, "", 45*time.Minute); err != nil { + t.Fatal(err) + } + for _, cmd := range []string{ + "cd /work/opt && gitpush -u origin topic", + "ghmerge go-numerics/optimize 62", + "ghrelease go-numerics/optimize 62 v0.1.0", + "ghpr go-numerics/optimize 62 ready", + "ghissue go-numerics/optimize --new --title T --body-file f", + "ghrun go-numerics/optimize dispatch ci.yml --ref main", + "ghrel go-numerics/optimize v0.1.0 edit --title T", + } { + if denied, reason, _ := ask(env, payload(t, me, "/work/opt", cmd)); denied { + t.Errorf("%q denied for the holder: %s", cmd, reason) + } + } +} + +func TestAClaimHeldByAnotherSessionRefusesAndNamesTheHolder(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("go-numerics/optimize", them, "refbench", 45*time.Minute); err != nil { + t.Fatal(err) + } + denied, reason, _ := ask(env, payload(t, me, "/work/opt", "cd /work/opt && gitpush -u origin topic")) + if !denied { + t.Fatal("a push into a repository claimed by another session was allowed") + } + for _, want := range []string{"22222222", "16:45:00", "refbench", "go-numerics/optimize"} { + if !strings.Contains(reason, want) { + t.Errorf("the refusal must name %q; it said %q", want, reason) + } + } +} + +func TestNoClaimAtAllRefusesAndSaysClaimItFirst(t *testing.T) { + env, _ := gateFixture(t) + denied, reason, _ := ask(env, payload(t, me, "/work/opt", "ghmerge go-numerics/optimize 62")) + if !denied || !strings.Contains(reason, "Claim it first") || !strings.Contains(reason, "no session holds") { + t.Fatalf("denied=%v reason=%q", denied, reason) + } +} + +// The 2026-11-12 case: the session's own claim lapsed, and nothing refused it. +func TestAnExpiredClaimIsNotAClaim(t *testing.T) { + env, s := gateFixture(t) + past := lease.Store{Dir: s.Dir, Now: func() time.Time { return gateNow.Add(-2 * time.Hour) }} + if _, err := past.Acquire("go-numerics/optimize", me, "", 45*time.Minute); err != nil { + t.Fatal(err) + } + denied, reason, _ := ask(env, payload(t, me, "/work/opt", "ghmerge go-numerics/optimize 62")) + if !denied || !strings.Contains(reason, "this session's claim expired at 14:45:00") || + !strings.Contains(reason, "Claim it first") { + t.Fatalf("denied=%v reason=%q", denied, reason) + } +} + +// Another session's lapsed claim does not block; a live one of mine beside it allows. +func TestAnotherSessionsExpiredClaimDoesNotBlockTheHolder(t *testing.T) { + env, s := gateFixture(t) + past := lease.Store{Dir: s.Dir, Now: func() time.Time { return gateNow.Add(-3 * time.Hour) }} + if _, err := past.Acquire("go-numerics", them, "", time.Hour); err != nil { + t.Fatal(err) + } + if _, err := s.Acquire("go-numerics/optimize", me, "", time.Hour); err != nil { + t.Fatal(err) + } + if denied, reason, _ := ask(env, payload(t, me, "/", "ghmerge go-numerics/optimize 62")); denied { + t.Fatalf("denied: %s", reason) + } +} + +func TestAnOrganisationClaimCoversItsRepositories(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("go-numerics", me, "", time.Hour); err != nil { + t.Fatal(err) + } + if denied, reason, _ := ask(env, payload(t, me, "/", "ghmerge go-numerics/optimize 62")); denied { + t.Fatalf("denied: %s", reason) + } + if denied, _, _ := ask(env, payload(t, them, "/", "ghmerge go-numerics/optimize 62")); !denied { + t.Fatal("another session was allowed under my organisation claim") + } +} + +func TestABareRepositoryNameClaimIsRecognised(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("optimize", me, "", time.Hour); err != nil { + t.Fatal(err) + } + if denied, reason, _ := ask(env, payload(t, me, "/", "ghmerge go-numerics/optimize 62")); denied { + t.Fatalf("denied: %s", reason) + } +} + +// ⛔ A refusal is not a verdict: everything the gate cannot read allows. +func TestWhatItCannotReadAllows(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("go-numerics/optimize", them, "", time.Hour); err != nil { + t.Fatal(err) + } + missing := env + missing.store = lease.Store{Dir: filepath.Join(t.TempDir(), "nope")} + file := filepath.Join(t.TempDir(), "afile") + if err := os.WriteFile(file, nil, 0o600); err != nil { + t.Fatal(err) + } + notDir := env + notDir.store = lease.Store{Dir: file} + + for _, tc := range []struct { + name string + env gateEnv + in *bytes.Reader + warns string + }{ + {"unreadable claims directory", missing, payload(t, me, "/work/opt", "ghmerge go-numerics/optimize 62"), "unreadable"}, + {"claims path is a file", notDir, payload(t, me, "/work/opt", "ghmerge go-numerics/optimize 62"), "unreadable"}, + {"a payload that is not JSON", env, bytes.NewReader([]byte("not json")), "could not read"}, + {"no session identity", env, payload(t, "", "/work/opt", "ghmerge go-numerics/optimize 62"), "which session"}, + {"a remote git cannot name", env, payload(t, me, "/elsewhere", "gitpush origin topic"), "allowing"}, + {"ghrelease backfill spans repositories", env, payload(t, me, "/", "ghrelease backfill"), "allowing"}, + } { + t.Run(tc.name, func(t *testing.T) { + denied, reason, errOut := ask(tc.env, tc.in) + if denied { + t.Fatalf("denied what it could not read: %s", reason) + } + if !strings.Contains(errOut, tc.warns) { + t.Errorf("stderr should say %q, said %q", tc.warns, errOut) + } + }) + } +} + +func TestCommandsThatPublishNothingAreLeftAlone(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("go-numerics/optimize", them, "", time.Hour); err != nil { + t.Fatal(err) + } + for _, cmd := range []string{ + "ls -la", "echo gitpush ghmerge go-numerics/optimize 62", + "git commit -m 'run ghmerge later'", "cat ~/.local/bin/gitpush", + } { + if denied, _, errOut := ask(env, payload(t, me, "/work/opt", cmd)); denied || errOut != "" { + t.Errorf("%q: denied=%v stderr=%q", cmd, denied, errOut) + } + } + var out, errOut bytes.Buffer + b, _ := json.Marshal(map[string]any{"session_id": me, "tool_name": "Edit", + "tool_input": map[string]any{"command": "ghmerge go-numerics/optimize 62"}}) + gateHook(bytes.NewReader(b), &out, &errOut, env) + if out.Len() != 0 { + t.Errorf("a non-Bash tool was answered: %s", out.String()) + } +} + +func TestTheTargetIsResolvedFromTheCommand(t *testing.T) { + env, _ := gateFixture(t) + for _, tc := range []struct{ cmd, cwd, want string }{ + {"gitpush -u origin topic", "/work/opt", "go-numerics/optimize"}, + {"cd /work/opt && gitpush origin topic", "/", "go-numerics/optimize"}, + {"gitpush fork topic", "/work/opt", "me/optimize"}, + {"gitpush", "/work/opt", "go-numerics/optimize"}, + {"gitpush -C /work/opt origin topic", "/", "go-numerics/optimize"}, + {"gitpush https://github.com/Org/Repo.git topic", "/", "org/repo"}, + {"FOO=1 ~/.local/bin/gitpush origin topic", "/work/opt", "go-numerics/optimize"}, + {"ghmerge 62", "/work/opt", "go-numerics/optimize"}, + {"ghmerge --wait 2m --evidence u o/r 62", "/", "o/r"}, + {"ghmerge --squash Org/Repo 62", "/", "org/repo"}, + {"ghissue -repo o/r --new --title T", "/", "o/r"}, + {"ghpr https://github.com/o/r/pull/62 62 ready", "/", "o/r"}, + {"ghrun o/r.github.io dispatch ci.yml --ref main", "/", "o/r.github.io"}, + } { + invs := invocations(tc.cmd, tc.cwd, env.home) + if len(invs) != 1 { + t.Errorf("%q: %d invocations", tc.cmd, len(invs)) + continue + } + got, err := env.target(invs[0]) + if err != nil || got != tc.want { + t.Errorf("%q: target %q, err %v; want %q", tc.cmd, got, err, tc.want) + } + } +} + +func TestSeveralPublishingCommandsAreAllChecked(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("a/mine", me, "", time.Hour); err != nil { + t.Fatal(err) + } + if _, err := s.Acquire("b/theirs", them, "", time.Hour); err != nil { + t.Fatal(err) + } + denied, reason, _ := ask(env, payload(t, me, "/", "ghmerge a/mine 1 && ghmerge b/theirs 2")) + if !denied || !strings.Contains(reason, "b/theirs") { + t.Fatalf("denied=%v reason=%q", denied, reason) + } +} + +// The identity rule: AGENTSYNC_OWNER, then the payload's session_id, then +// CLAUDE_CODE_SESSION_ID -- the first two are what `claim` writes under. +func TestTheSessionIdentityRule(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("o/r", me, "", time.Hour); err != nil { + t.Fatal(err) + } + cmd := "ghmerge o/r 1" + if denied, _, _ := ask(env, payload(t, me, "/", cmd)); denied { + t.Error("the payload's session_id was not used") + } + e := env + e.session = me + if denied, _, _ := ask(e, payload(t, "", "/", cmd)); denied { + t.Error("CLAUDE_CODE_SESSION_ID was not the fallback") + } + e.session = them + if denied, _, _ := ask(e, payload(t, me, "/", cmd)); denied { + t.Error("the payload must outrank the hook's environment") + } + e.override = them + if denied, _, _ := ask(e, payload(t, me, "/", cmd)); !denied { + t.Error("AGENTSYNC_OWNER must outrank the payload, as it does in claim") + } +} diff --git a/cmd/agentsync/main.go b/cmd/agentsync/main.go index 10749a7..2e3ece4 100644 --- a/cmd/agentsync/main.go +++ b/cmd/agentsync/main.go @@ -863,10 +863,10 @@ func main() { "claim": claim, "release": release, "claims": claims, "mem-add": memAdd, "mem-verify": memVerify, "whoami": whoami, "orphans": orphans, "mem-fold": memFold, - "tell": tell, "messages": messages, "forget": forget, + "tell": tell, "messages": messages, "forget": forget, "gate": gate, } if len(os.Args) < 2 { - fmt.Fprintln(os.Stderr, "usage: agentsync {claim|release|claims|tell|messages|forget|mem-add|mem-verify|mem-fold|orphans|whoami} ...") + fmt.Fprintln(os.Stderr, "usage: agentsync {claim|release|claims|gate|tell|messages|forget|mem-add|mem-verify|mem-fold|orphans|whoami} ...") os.Exit(2) } fn, ok := cmds[os.Args[1]] diff --git a/lease/lease.go b/lease/lease.go index 015024e..23723b3 100644 --- a/lease/lease.go +++ b/lease/lease.go @@ -346,6 +346,31 @@ func (s Store) Release(resource, owner string) (bool, error) { return true, nil } +// Covering returns every lease, expired ones included, that is about the same +// resource as the one asked about or encloses it: "go-numerics/optimize" is +// covered by a lease on itself and by one on "go-numerics". +// +// A lease written with the bare repository name ("optimize") also covers an +// owner/repo ending in it: the shared directory holds such leases, and a gate +// that missed them would refuse the one session that did claim. +func (s Store) Covering(resource string) ([]Lease, error) { + all, err := s.List() + if err != nil { + return nil, err + } + key := Normalize(resource) + segs := strings.Split(key, "/") + last := segs[len(segs)-1] + var out []Lease + for _, l := range all { + k := Normalize(l.Resource) + if covers(k, key) || (len(segs) > 1 && k == last) { + out = append(out, l) + } + } + return out, nil +} + // List returns every lease, expired ones included, so a caller can show what is // stale rather than hide it. func (s Store) List() ([]Lease, error) { diff --git a/lease/lease_test.go b/lease/lease_test.go index e7c7b6a..96abe9f 100644 --- a/lease/lease_test.go +++ b/lease/lease_test.go @@ -443,3 +443,39 @@ func TestAnExpiredLeaseUnderTheOldFileNameDoesNotBlock(t *testing.T) { t.Errorf("a dead session's old-format lease blocked the claim: %v", err) } } + +// Covering is what the publish gate asks: who holds this repository, by itself, +// by its organisation, or under the bare name -- expired ones included, and +// never a neighbour that merely starts the same. +func TestCoveringFindsEveryLeaseAboutARepository(t *testing.T) { + now := time.Now() + s := store(t, now) + // Expired, so that overlapping claims by different owners do not refuse each + // other: Covering reports expired leases too, and the caller judges them. + at := now.Add(-20 * time.Hour) + past := Store{Dir: s.Dir, Now: func() time.Time { return at }} + for _, r := range []string{"go-numerics/optimize", "go-numerics", "optimize", "go-numerics/optimize-extra", "go-tex", "other/optimize"} { + if _, err := past.Acquire(r, "o-"+r, "", time.Hour); err != nil { + t.Fatalf("%s: %v", r, err) + } + at = at.Add(2 * time.Hour) // the previous hour-long lease has lapsed + } + got, err := s.Covering("GitHub.com/go-numerics/optimize") + if err != nil { + t.Fatal(err) + } + seen := map[string]bool{} + for _, l := range got { + seen[l.Resource] = true + } + for _, want := range []string{"go-numerics/optimize", "go-numerics", "optimize"} { + if !seen[want] { + t.Errorf("%q missing from %v", want, seen) + } + } + for _, not := range []string{"go-numerics/optimize-extra", "go-tex", "other/optimize"} { + if seen[not] { + t.Errorf("%q must not cover go-numerics/optimize", not) + } + } +} From b3df45d5c7d614794311f9d6a420a36726efb82a Mon Sep 17 00:00:00 2001 From: tannevaled Date: Thu, 12 Nov 2026 16:37:32 +0100 Subject: [PATCH 2/3] gate: act on the independent review (bare/qualified claims, shell parsing, push target, unreadable leases) - decide denies when ANY other session holds a live lease covering the target, whatever this session holds; a bare "optimize" no longer outranks another session's live "go-numerics/optimize". - Acquire treats a bare name and an owner/name ending in it as overlapping, in both orders. - Command parsing uses gitsafe's shellcmd (quoted heredocs, comments, statement split); inside a statement a gated program word anywhere, unquoted, counts, and a quoted word is read as a command only after bash/sh/zsh/eval. A cd inside parentheses does not outlive them; redirections are not arguments. - gitpush follows branch..pushRemote, remote.pushDefault, branch..remote and the push URL. - Covering fails on an unreadable lease, which the gate reads as "cannot read": allow, with a note. Co-Authored-By: Claude Sonnet 5.5 --- cmd/agentsync/gate.go | 257 +++++++++++++++++++++++------- cmd/agentsync/gate_review_test.go | 185 +++++++++++++++++++++ cmd/agentsync/gate_test.go | 11 +- go.mod | 2 + go.sum | 2 + lease/lease.go | 35 +++- 6 files changed, 423 insertions(+), 69 deletions(-) create mode 100644 cmd/agentsync/gate_review_test.go create mode 100644 go.sum diff --git a/cmd/agentsync/gate.go b/cmd/agentsync/gate.go index c6a1c4d..45e1f14 100644 --- a/cmd/agentsync/gate.go +++ b/cmd/agentsync/gate.go @@ -15,6 +15,7 @@ import ( "time" "github.com/go-agentsync/agentsync/lease" + "github.com/go-gitsafe/gitsafe/shellcmd" ) // gate refuses a publishing command aimed at a repository whose claim the @@ -69,8 +70,10 @@ type gateEnv struct { // payload's session_id sits between them. override, session string now func() time.Time - remote func(dir, name string) (string, error) // the URL of a git remote - home string + // remote is the URL of a git remote of the checkout in dir. push asks for the + // URL a push goes to; name "" asks for the remote a push goes to by default. + remote func(dir, name string, push bool) (string, error) + home string } func gate(args []string) error { @@ -175,6 +178,7 @@ func (g gateEnv) decide(repo string, errOut io.Writer) string { } now := g.now() var other, expired *lease.Lease + mine := false for i := range ls { l := ls[i] switch { @@ -183,11 +187,17 @@ func (g gateEnv) decide(repo string, errOut io.Writer) string { expired = &ls[i] } case l.Owner == g.owner: - return "" // this session holds it + mine = true case other == nil: other = &ls[i] } } + // ⛔ ANOTHER SESSION'S LIVE CLAIM DECIDES, whatever else this one holds. A + // bare "optimize" of mine does not outrank a live "go-numerics/optimize" of + // theirs: first-match-allows let exactly that through. + if other == nil && mine { + return "" // this session holds it and nobody else does + } if other != nil { note := "" if other.Note != "" { @@ -219,41 +229,130 @@ type invocation struct { // invocations finds the gated programs in a command line. // -// It matches the PROGRAM of each simple command, not the word anywhere in the -// text: `echo gitpush` and a commit message that mentions ghmerge publish -// nothing. The cost is that a here-document whose body has a line beginning -// with one of these words is read as that command; the gate then asks for a -// claim the session ought to hold anyway. +// The splitting is gitsafe's shellcmd (the reading every guard on this machine +// shares): quoted heredoc bodies are removed and `#` comments dropped, so text +// that merely QUOTES a command is not the command, then Statements splits on +// ; newline && ||. +// +// ⛔ WITHIN a statement it does not try to be a shell. A gated program word +// ANYWHERE in a simple command counts, unquoted -- so `sudo gitpush`, +// `timeout 5 ghmerge`, `xargs ghrun`, `if x; then gitpush`, `! gitpush`, +// `$(ghmerge ..)` and backticks are all found -- because over-refusing a +// command that names one beats missing one that runs it (recur --hook's rule). +// A quoted word is read as a nested command line only after a shell or eval +// (`bash -c "gitpush ..."`), never otherwise: `git commit -m 'ghmerge later'` +// publishes nothing. // -// `cd X &&` is followed, because a push is usually written `cd repo && gitpush`. +// `cd X` is followed, and a `cd` inside ( ... ) or $( ... ) is undone at the +// closing parenthesis, as the shell does. func invocations(cmd, cwd, homeDir string) []invocation { + cmd = shellcmd.StripQuotedHeredocs(stripComments(cmd)) dir := cwd + var stack []string var out []invocation - for _, seg := range splitCommand(cmd) { - i := 0 - for i < len(seg) && (isAssignment(seg[i]) || seg[i] == "env" || seg[i] == "command" || - seg[i] == "exec" || seg[i] == "time" || seg[i] == "nohup") { - i++ + for _, st := range shellcmd.Statements(cmd) { + var words []word + flush := func() { + var inv []invocation + inv, dir = scanSimple(words, dir, homeDir) + out = append(out, inv...) + words = nil } - if i >= len(seg) { - continue + for _, t := range tokens(st) { + if !t.op { + words = append(words, t) + continue + } + flush() + switch t.s { + case "(": + stack = append(stack, dir) + case ")": + if n := len(stack); n > 0 { + dir, stack = stack[n-1], stack[:n-1] + } + } } - prog, args := seg[i], seg[i+1:] - if prog == "cd" { - for len(args) > 0 && strings.HasPrefix(args[0], "-") { - args = args[1:] + flush() + } + return out +} + +var shells = map[string]bool{"bash": true, "sh": true, "zsh": true, "dash": true, "ksh": true, "eval": true} + +var redirectRe = regexp.MustCompile(`^[0-9]*[<>]`) + +// scanSimple reads one simple command: it follows a `cd`, and returns the first +// gated program in it, with the words after it. +func scanSimple(ws []word, dir, homeDir string) ([]invocation, string) { + // Redirections are not arguments; a bare operator takes the next word with it. + var w []word + for i := 0; i < len(ws); i++ { + if !ws[i].quoted && redirectRe.MatchString(ws[i].s) { + if strings.Trim(ws[i].s, "0123456789<>&|") == "" && !strings.HasSuffix(ws[i].s, "&") { + i++ } - if len(args) > 0 { - dir = resolveDir(dir, args[0], homeDir) + continue + } + w = append(w, ws[i]) + } + i := 0 + for i < len(w) && !w[i].quoted && isAssignment(w[i].s) { + i++ + } + if i < len(w) && w[i].s == "cd" { + args := w[i+1:] + for len(args) > 0 && strings.HasPrefix(args[0].s, "-") { + args = args[1:] + } + if len(args) > 0 { + dir = resolveDir(dir, args[0].s, homeDir) + } + return nil, dir + } + var out []invocation + nested := false + for _, x := range w[i:] { + if !x.quoted && shells[filepath.Base(x.s)] { + nested = true + } + } + if nested { + for _, x := range w[i:] { + if x.quoted && strings.ContainsAny(x.s, " \t\n") { + out = append(out, invocations(x.s, dir, homeDir)...) } + } + } + for j := i; j < len(w); j++ { + if w[j].quoted { continue } - base := filepath.Base(prog) - if gated[base] { + if base := filepath.Base(w[j].s); gated[base] { + args := make([]string, 0, len(w)-j-1) + for _, a := range w[j+1:] { + args = append(args, a.s) + } out = append(out, invocation{prog: base, args: args, dir: dir}) + break } } - return out + return out, dir +} + +// stripComments removes `#` comments: a # that starts a word and is not inside +// quotes runs to the end of its line. +func stripComments(cmd string) string { + lines := strings.Split(cmd, "\n") + for n, ln := range lines { + for i := 0; i < len(ln); i++ { + if ln[i] == '#' && (i == 0 || ln[i-1] == ' ' || ln[i-1] == '\t') && !shellcmd.InsideQuotes(ln, i) { + lines[n] = ln[:i] + break + } + } + } + return strings.Join(lines, "\n") } var assignRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*=`) @@ -278,27 +377,26 @@ func resolveDir(cur, to, homeDir string) string { return filepath.Join(cur, to) } -// splitCommand splits a shell command line into simple commands, each a list of -// words, honouring quotes and backslashes. Operators (; & | newline and -// parentheses) end a command. It is not a shell: anything it cannot follow -// simply yields words that match no gated program, which allows. -func splitCommand(s string) [][]string { - var segs [][]string - var cur []string +// word is one shell word, or an operator that ends a simple command. +type word struct { + s string + quoted bool // some of it was inside quotes or escaped + op bool // | & ( ) or a backtick +} + +// tokens splits one statement into words and the operators the statement +// splitter leaves inside it (pipes, a lone &, parentheses, backticks), honouring +// quotes and backslashes. It is a word splitter, not a shell: what it cannot +// follow it reads as plain words, which the scan above over-matches. +func tokens(s string) []word { + var out []word var tok strings.Builder - in := false + in, quoted := false, false endWord := func() { if in { - cur = append(cur, tok.String()) + out = append(out, word{s: tok.String(), quoted: quoted}) tok.Reset() - in = false - } - } - endCmd := func() { - endWord() - if len(cur) > 0 { - segs = append(segs, cur) - cur = nil + in, quoted = false, false } } rs := []rune(s) @@ -306,12 +404,12 @@ func splitCommand(s string) [][]string { c := rs[i] switch { case c == '\'': - in = true + in, quoted = true, true for i++; i < len(rs) && rs[i] != '\''; i++ { tok.WriteRune(rs[i]) } case c == '"': - in = true + in, quoted = true, true for i++; i < len(rs) && rs[i] != '"'; i++ { if rs[i] == '\\' && i+1 < len(rs) { i++ @@ -319,20 +417,21 @@ func splitCommand(s string) [][]string { tok.WriteRune(rs[i]) } case c == '\\' && i+1 < len(rs): - in = true + in, quoted = true, true i++ tok.WriteRune(rs[i]) case c == ' ' || c == '\t': endWord() - case c == '\n' || c == ';' || c == '&' || c == '|' || c == '(' || c == ')': - endCmd() + case c == '&' || c == '|' || c == '(' || c == ')' || c == '`': + endWord() + out = append(out, word{s: string(c), op: true}) default: in = true tok.WriteRune(c) } } - endCmd() - return segs + endWord() + return out } var repoRe = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`) @@ -388,13 +487,14 @@ func (g gateEnv) target(inv invocation) (string, error) { } return "", fmt.Errorf("cannot read a repository from %q", explicit) } - if remote == "" { - remote = "origin" + push := inv.prog == "gitpush" + if remote == "" && !push { + remote = "origin" // the pull request's repository is the fetch side } if dir == "" { return "", errors.New("no repository named and no working directory") } - u, err := g.remote(dir, remote) + u, err := g.remote(dir, remote, push) if err != nil { return "", fmt.Errorf("remote %q of %s: %v", remote, dir, err) } @@ -420,16 +520,53 @@ func ownerRepo(s string) string { return "" } -// gitRemote reads the URL of a remote of the checkout in dir. -func gitRemote(dir, name string) (string, error) { +// git runs git in dir and returns its trimmed stdout. +func git(dir string, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + b, err := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...).Output() + return strings.TrimSpace(string(b)), err +} + +// gitConfig is one config value, "" when it is unset (git exits 1 for that). +func gitConfig(dir, key string) string { + v, _ := git(dir, "config", "--get", key) + return v +} + +// defaultPushRemote is the remote `git push` with no remote argument uses, in +// git's own order: branch..pushRemote, remote.pushDefault, branch..remote, +// origin. +func defaultPushRemote(dir string) string { + b, _ := git(dir, "symbolic-ref", "--short", "-q", "HEAD") + if b != "" { + if r := gitConfig(dir, "branch."+b+".pushRemote"); r != "" { + return r + } + } + if r := gitConfig(dir, "remote.pushDefault"); r != "" { + return r + } + if b != "" { + if r := gitConfig(dir, "branch."+b+".remote"); r != "" && r != "." { + return r + } + } + return "origin" +} + +// gitRemote reads the URL of a remote of the checkout in dir: the one a push +// goes to when push is set (pushurl honoured), else the fetch URL. +func gitRemote(dir, name string, push bool) (string, error) { + if name == "" { + name = defaultPushRemote(dir) + } if strings.HasPrefix(name, "-") { return "", errors.New("not a remote name") } - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - b, err := exec.CommandContext(ctx, "git", "-C", dir, "remote", "get-url", name).Output() - if err != nil { - return "", err + args := []string{"remote", "get-url"} + if push { + args = append(args, "--push") } - return strings.TrimSpace(string(b)), nil + return git(dir, append(args, name)...) } diff --git a/cmd/agentsync/gate_review_test.go b/cmd/agentsync/gate_review_test.go new file mode 100644 index 0000000..0ff7ca7 --- /dev/null +++ b/cmd/agentsync/gate_review_test.go @@ -0,0 +1,185 @@ +package main + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-agentsync/agentsync/lease" +) + +// ⛔ The reviewer's case: a bare "optimize" of mine must not outrank a live +// "go-numerics/optimize" of theirs. Taking them in either order is refused at +// claim time; a bare claim that predates the rule is refused at publish time. +func TestABareClaimOfMineDoesNotOutrankTheirQualifiedOne(t *testing.T) { + env, s := gateFixture(t) + // Written the way an old `claim` would have: neither acquisition saw the other. + for _, f := range []struct{ res, owner string }{{"go-numerics/optimize", them}, {"optimize", me}} { + l := lease.Lease{Resource: f.res, Owner: f.owner, Acquired: gateNow, Expires: gateNow.Add(time.Hour)} + writeLease(t, s, l) + } + denied, reason, _ := ask(env, payload(t, me, "/", "ghmerge go-numerics/optimize 62")) + if !denied || !strings.Contains(reason, "22222222") { + t.Fatalf("denied=%v reason=%q", denied, reason) + } + // And the holder of the qualified claim is not stopped by my bare one. + if denied, _, _ := ask(env, payload(t, them, "/", "ghmerge go-numerics/optimize 62")); !denied { + // them is blocked by me too: the bare claim covers it, and I hold it live. + t.Log("both hold overlapping claims; each is refused by the other, as designed") + } +} + +func writeLease(t *testing.T, s lease.Store, l lease.Lease) { + t.Helper() + // Through Acquire at the lease's own clock, into a scratch store when the + // overlap check would refuse; the file shape is what matters. + scratch := lease.Store{Dir: t.TempDir(), Now: func() time.Time { return gateNow }} + got, err := scratch.Acquire(l.Resource, l.Owner, "", time.Hour) + if err != nil { + t.Fatal(err) + } + entries, err := os.ReadDir(scratch.Dir) + if err != nil || len(entries) != 1 { + t.Fatalf("scratch store: %v %v", entries, err) + } + b, err := os.ReadFile(filepath.Join(scratch.Dir, entries[0].Name())) + if err != nil { + t.Fatal(err) + } + _ = got + if err := os.WriteFile(filepath.Join(s.Dir, entries[0].Name()), b, 0o600); err != nil { + t.Fatal(err) + } +} + +// Another session's lapsed claim must not stop a publish, and must not be +// mistaken for a live one: with nothing of mine, the answer is "claim it first", +// not "held by another session". +func TestAnotherSessionsExpiredClaimIsNotAHolder(t *testing.T) { + env, s := gateFixture(t) + past := lease.Store{Dir: s.Dir, Now: func() time.Time { return gateNow.Add(-2 * time.Hour) }} + if _, err := past.Acquire("go-numerics/optimize", them, "", time.Hour); err != nil { + t.Fatal(err) + } + denied, reason, _ := ask(env, payload(t, me, "/", "ghmerge go-numerics/optimize 62")) + if !denied || strings.Contains(reason, "claimed by another session") || !strings.Contains(reason, "Claim it first") { + t.Fatalf("denied=%v reason=%q", denied, reason) + } +} + +// ⛔ A lease the gate cannot read may be the holder's: allow and say so, never +// "nobody holds it". +func TestAnUnreadableLeaseMeansCannotRead(t *testing.T) { + env, s := gateFixture(t) + if err := os.WriteFile(filepath.Join(s.Dir, "torn.lease"), []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + denied, reason, errOut := ask(env, payload(t, me, "/", "ghmerge go-numerics/optimize 62")) + if denied || !strings.Contains(errOut, "unreadable") { + t.Fatalf("denied=%v (%s) stderr=%q", denied, reason, errOut) + } +} + +// Claims taken with `claim` refuse a bare/qualified overlap in both orders. +func TestAcquireRefusesABareAndAQualifiedClaimOfOneRepository(t *testing.T) { + _, s := gateFixture(t) + if _, err := s.Acquire("go-numerics/optimize", them, "", time.Hour); err != nil { + t.Fatal(err) + } + if _, err := s.Acquire("optimize", me, "", time.Hour); err == nil { + t.Error("a bare claim was granted over another session's qualified one") + } + s2 := lease.Store{Dir: t.TempDir(), Now: s.Now} + if _, err := s2.Acquire("optimize", them, "", time.Hour); err != nil { + t.Fatal(err) + } + if _, err := s2.Acquire("go-numerics/optimize", me, "", time.Hour); err == nil { + t.Error("a qualified claim was granted over another session's bare one") + } +} + +// Commands that hide a publish from a parser that reads only the first word. +func TestHiddenPublishingCommandsAreFound(t *testing.T) { + env, s := gateFixture(t) + if _, err := s.Acquire("go-numerics/optimize", them, "", time.Hour); err != nil { + t.Fatal(err) + } + for _, cmd := range []string{ + `bash -c "cd /work/opt && gitpush origin topic"`, + `sh -c 'ghmerge go-numerics/optimize 62'`, + `eval "ghmerge go-numerics/optimize 62"`, + `sudo ghmerge go-numerics/optimize 62`, + `timeout 60 ghmerge go-numerics/optimize 62`, + `echo 62 | xargs ghmerge go-numerics/optimize`, + `if true; then ghmerge go-numerics/optimize 62; fi`, + `for i in 1; do ghmerge go-numerics/optimize 62; done`, + `{ ghmerge go-numerics/optimize 62; }`, + `! ghmerge go-numerics/optimize 62`, + "x=`ghmerge go-numerics/optimize 62`", + `x=$(ghmerge go-numerics/optimize 62)`, + `(cd /work/opt && gitpush origin topic)`, + "ls\nghmerge go-numerics/optimize 62 2>&1", + "git commit -F - <