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
1 change: 1 addition & 0 deletions changelog.d/added-18493-topic-pr-claims.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Long-lived agents can claim a topic for one pull request with `bd topic claim <key> --repo <owner/name> --pr <n>`: the claim is stored in the agent's bead store, a second open claim for the same topic is refused, the kick lists the agent's claims (also as `${TOPIC_CLAIMS}`) so it finds its PR by number after a branch rename, the FIX-BEFORE-NEW and held-PR blocks show the topic next to the PR, and hive releases the claim when the PR merges or closes.
6 changes: 6 additions & 0 deletions src/cmd/bd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ func main() {
cmdRemember(os.Args[2:])
case "kb":
cmdKB(os.Args[2:])
case "topic":
cmdTopic(os.Args[2:])
case "dolt":
cmdDolt(os.Args[2:])
case "init":
Expand Down Expand Up @@ -110,6 +112,10 @@ Commands:
kb import-file <path> [--name <n>] Import document from file
kb list-docs List imported documents
remember "<fact>" Quick-add an advisory bead
topic claim <key> --repo o/r --pr N [--branch B]
Claim a topic for one PR (refused if held by another PR)
topic get <key> [--json] | list [--json] | release <key>
Read, list or release topic claims
close <id> Close a bead
decompose <epic-id> [--plan <file>] [--actor <lane>]
Decompose an epic into a DAG of child task beads
Expand Down
167 changes: 167 additions & 0 deletions src/cmd/bd/topic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
package main

import (
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"

"github.com/hivecommons/hive/pkg/beads"
)

// bd topic: durable one-PR-per-topic claims (hivecommons/hive#18493).
//
// bd topic claim <key> --repo owner/name --pr N [--branch B] [--actor A]
// bd topic get <key> [--json]
// bd topic list [--json]
// bd topic release <key>
//
// Exit codes: 0 success, 1 usage or store error, 2 refused (the topic is
// held by a different PR) or not found on get.
const (
topicExitOK = 0
topicExitError = 1
topicExitRefused = 2
)

const topicUsage = `Usage:
bd topic claim <key> --repo owner/name --pr N [--branch B] [--actor A]
bd topic get <key> [--json]
bd topic list [--json]
bd topic release <key>`

func cmdTopic(args []string) {
if code := runTopic(args, openStore, os.Stdout, os.Stderr); code != topicExitOK {
os.Exit(code)
}
}

// runTopic is cmdTopic without the process exit, so every path is testable
// in-process.
func runTopic(args []string, open func() *beads.Store, stdout, stderr io.Writer) int {
if len(args) < 1 {
fmt.Fprintln(stderr, topicUsage)
return topicExitError
}
sub, rest := args[0], args[1:]
switch sub {
case "list":
return topicList(rest, open, stdout, stderr)
case "claim", "get", "release":
default:
fmt.Fprintf(stderr, "bd topic: unknown subcommand %q\n%s\n", sub, topicUsage)
return topicExitError
}
if len(rest) < 1 || rest[0] == "" || rest[0][0] == '-' {
fmt.Fprintf(stderr, "bd topic %s: requires a topic key\n", sub)
return topicExitError
}
key, flags := rest[0], rest[1:]
switch sub {
case "claim":
return topicClaim(key, flags, open, stdout, stderr)
case "get":
return topicGet(key, flags, open, stdout, stderr)
default:
return topicRelease(key, open, stdout, stderr)
}
}

func topicClaim(key string, args []string, open func() *beads.Store, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("topic claim", flag.ContinueOnError)
fs.SetOutput(stderr)
repo := fs.String("repo", "", "Repository as owner/name (required)")
pr := fs.Int("pr", 0, "Pull request number (required)")
branch := fs.String("branch", "", "Current head branch")
actor := fs.String("actor", os.Getenv("HIVE_AGENT"), "Claiming agent (default $HIVE_AGENT)")
if err := fs.Parse(args); err != nil {
return topicExitError
}
claim, err := open().ClaimTopic(*actor, beads.TopicClaim{Key: key, Repo: *repo, PR: *pr, Branch: *branch})
if errors.Is(err, beads.ErrTopicClaimed) {
fmt.Fprintf(stderr, "bd topic claim: refused: %v (work on that PR, or release the topic first)\n", err)
return topicExitRefused
}
if err != nil {
fmt.Fprintf(stderr, "bd topic claim: %v\n", err)
return topicExitError
}
return writeTopicJSON(stdout, stderr, claim)
}

func topicGet(key string, args []string, open func() *beads.Store, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("topic get", flag.ContinueOnError)
fs.SetOutput(stderr)
jsonOut := fs.Bool("json", false, "Output as JSON")
if err := fs.Parse(args); err != nil {
return topicExitError
}
claim, ok := open().Topic(key)
if !ok {
fmt.Fprintf(stderr, "bd topic get: no open claim for %q\n", key)
return topicExitRefused
}
if *jsonOut {
return writeTopicJSON(stdout, stderr, claim)
}
fmt.Fprintln(stdout, formatTopicLine(claim))
return topicExitOK
}

func topicList(args []string, open func() *beads.Store, stdout, stderr io.Writer) int {
fs := flag.NewFlagSet("topic list", flag.ContinueOnError)
fs.SetOutput(stderr)
jsonOut := fs.Bool("json", false, "Output as JSON")
if err := fs.Parse(args); err != nil {
return topicExitError
}
claims := open().OpenTopics()
if *jsonOut {
if claims == nil {
claims = []beads.TopicClaim{}
}
return writeTopicJSON(stdout, stderr, claims)
}
if len(claims) == 0 {
fmt.Fprintln(stdout, "No open topic claims.")
return topicExitOK
}
for _, c := range claims {
fmt.Fprintln(stdout, formatTopicLine(c))
}
return topicExitOK
}

func topicRelease(key string, open func() *beads.Store, stdout, stderr io.Writer) int {
released, err := open().ReleaseTopic(key, beads.TopicStateReleased)
if err != nil {
fmt.Fprintf(stderr, "bd topic release: %v\n", err)
return topicExitError
}
if !released {
fmt.Fprintf(stdout, "No open claim for %q\n", key)
return topicExitOK
}
fmt.Fprintf(stdout, "Released topic %q\n", key)
return topicExitOK
}

func formatTopicLine(c beads.TopicClaim) string {
line := fmt.Sprintf("%s → %s#%d", c.Key, c.Repo, c.PR)
if c.Branch != "" {
line += " (branch " + c.Branch + ")"
}
return line
}

func writeTopicJSON(stdout, stderr io.Writer, v interface{}) int {
enc := json.NewEncoder(stdout)
enc.SetIndent("", " ")
if err := enc.Encode(v); err != nil {
fmt.Fprintf(stderr, "bd topic: json encode error: %v\n", err)
return topicExitError
}
return topicExitOK
}
103 changes: 103 additions & 0 deletions src/cmd/bd/topic_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package main

import (
"bytes"
"encoding/json"
"strings"
"testing"

"github.com/hivecommons/hive/pkg/beads"
)

func topicStoreOpener(t *testing.T) func() *beads.Store {
t.Helper()
dir := t.TempDir()
return func() *beads.Store {
s, err := beads.NewStore(dir)
if err != nil {
t.Fatal(err)
}
return s
}
}

func runTopicT(open func() *beads.Store, args ...string) (int, string, string) {
var out, errOut bytes.Buffer
code := runTopic(args, open, &out, &errOut)
return code, out.String(), errOut.String()
}

func TestTopicClaimGetListRelease(t *testing.T) {
open := topicStoreOpener(t)
t.Setenv("HIVE_AGENT", "deps")

code, out, errOut := runTopicT(open, "claim", "deps-bump", "--repo", "acme/widget", "--pr", "12", "--branch", "deps/a")
if code != topicExitOK {
t.Fatalf("claim exit %d: %s", code, errOut)
}
var claim beads.TopicClaim
if err := json.Unmarshal([]byte(out), &claim); err != nil || claim.PR != 12 || claim.Actor != "deps" {
t.Fatalf("claim output %q (%v)", out, err)
}

code, _, errOut = runTopicT(open, "claim", "deps-bump", "--repo", "acme/widget", "--pr", "13")
if code != topicExitRefused || !strings.Contains(errOut, "refused") || !strings.Contains(errOut, "acme/widget#12") {
t.Fatalf("second claim exit %d: %s", code, errOut)
}

if code, out, _ = runTopicT(open, "get", "deps-bump"); code != topicExitOK || !strings.Contains(out, "deps-bump → acme/widget#12 (branch deps/a)") {
t.Fatalf("get exit %d: %q", code, out)
}
if code, out, _ = runTopicT(open, "get", "deps-bump", "--json"); code != topicExitOK || !strings.Contains(out, `"pr": 12`) {
t.Fatalf("get --json exit %d: %q", code, out)
}
if code, out, _ = runTopicT(open, "list"); code != topicExitOK || !strings.Contains(out, "deps-bump → acme/widget#12") {
t.Fatalf("list exit %d: %q", code, out)
}
if code, out, _ = runTopicT(open, "list", "--json"); code != topicExitOK || !strings.Contains(out, `"key": "deps-bump"`) {
t.Fatalf("list --json exit %d: %q", code, out)
}

if code, out, _ = runTopicT(open, "release", "deps-bump"); code != topicExitOK || !strings.Contains(out, "Released") {
t.Fatalf("release exit %d: %q", code, out)
}
if code, out, _ = runTopicT(open, "release", "deps-bump"); code != topicExitOK || !strings.Contains(out, "No open claim") {
t.Fatalf("second release exit %d: %q", code, out)
}
if code, _, _ = runTopicT(open, "get", "deps-bump"); code != topicExitRefused {
t.Fatalf("get after release exit %d", code)
}
if code, out, _ = runTopicT(open, "list"); code != topicExitOK || !strings.Contains(out, "No open topic claims.") {
t.Fatalf("empty list exit %d: %q", code, out)
}
if code, out, _ = runTopicT(open, "list", "--json"); code != topicExitOK || strings.TrimSpace(out) != "[]" {
t.Fatalf("empty list --json exit %d: %q", code, out)
}
}

func TestTopicUsageErrors(t *testing.T) {
open := topicStoreOpener(t)
for name, args := range map[string][]string{
"no subcommand": {},
"unknown": {"frob"},
"missing key": {"claim"},
"flag as key": {"get", "--json"},
"bad claim flag": {"claim", "k", "--nope"},
"claim no pr": {"claim", "k", "--repo", "a/b"},
"bad get flag": {"get", "k", "--nope"},
"bad list flag": {"list", "--nope"},
"bad release key": {"release", "a b"},
} {
if code, _, _ := runTopicT(open, args...); code != topicExitError {
t.Errorf("%s: exit %d, want %d", name, code, topicExitError)
}
}
}

func TestMainDispatchTopic(t *testing.T) {
t.Setenv("BD_DIR", t.TempDir())
out := runMain(t, "topic", "list")
if !strings.Contains(out, "No open topic claims.") {
t.Fatalf("main(topic list) = %q", out)
}
}
8 changes: 8 additions & 0 deletions src/cmd/hive/github_client_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,9 +382,17 @@ func (b *boot) applyGitHubClientDashboardHooks(client *github.Client) {
// governor's cached snapshot now, instead of waiting for GitHub's
// `closed` delivery to come back round through the hub.
evictHiveClosedPR(b.dashSrv, rec, time.Now())
// #18493: a PR the hive merged or closed releases its topic claim.
if state := topicStateForAudit(rec.Action); state != "" {
releaseTopicClaimsForPR(b.beadStores, rec.Repo, rec.Target, state, b.logger)
}
})
client.SetPRTerminalObservedHook(func(obs github.PRTerminalObservation) {
ts := obs.ObservedAt.UTC().Format(time.RFC3339)
// #18493: an observed merge or close releases the PR's topic claim.
if state := topicStateForTerminal(obs.State); state != "" {
releaseTopicClaimsForPR(b.beadStores, obs.Repo, obs.Number, state, b.logger)
}
switch obs.State {
case github.PRStateMerged:
path := obs.Attribution
Expand Down
4 changes: 4 additions & 0 deletions src/cmd/hive/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3518,6 +3518,10 @@ func (b *boot) bootSupervision() {
// Dashboard maintainer notes on a listed item ride its kick as private
// context (pkg/scheduler/kick_maintainer_notes.go).
b.sched.SetMaintainerNotesLookup(maintainernotes.Default().List)
// #18493: agents' durable topic claims (bd topic) ride their kicks and tag
// the PR rows of the FIX-BEFORE-NEW and held-PR blocks. Read b.beadStores
// at call time, not at wire time.
b.sched.SetTopicClaimLookup(func() []scheduler.TopicClaim { return topicClaimLookup(b.beadStores)() })
// #9584: close answered question issues unless the author objects (default off).
b.questionAutoclose.Store(wireQuestionAutoclose(b.ctx, b.cfg, b.sched, func() *github.Client { return b.ghClient }, b.logger))
// The pr-request watcher's PR-opened hook (Linear session narration, the
Expand Down
3 changes: 3 additions & 0 deletions src/cmd/hive/main_eval_cycle.go
Original file line number Diff line number Diff line change
Expand Up @@ -1344,6 +1344,9 @@ func runEvalCycle(
// stores can become stale between eval cycles. Reload failures are deduped
// (WARN once per distinct error, then DEBUG) — see beads_reload.go (#5505).
reloadBeadStores(beadStores, logger)
// #18493: release topic claims whose PR merged or closed, and follow a
// claimed PR's renamed head branch.
syncTopicClaims(beadStores, actionable, logger)

// Phase 4 Part B: `plan`/`epic` label trigger. An actionable issue carrying a
// plan label auto-mints an epic and requests decomposition — the same flow as
Expand Down
Loading
Loading