diff --git a/config.example.toml b/config.example.toml index 5b2d11082..9425d4ee2 100644 --- a/config.example.toml +++ b/config.example.toml @@ -101,11 +101,13 @@ target = "127.0.0.1:9090" # [[curators]] # name = "self-intake" # interval = "1h" -# tools = ["run_list", "run_events"] +# tools = ["run_list", "run_events", "issue_list"] # instructions = """ # You are archie's self-intake curator, in dry run. Each pass: list recent # task runs with run_list, inspect anything parked or failed with run_events, -# then report candidate follow-up issues — concrete, each tied to the run -# that produced it. Do not create issues; this pass reports only (no -# issue-creating tool is declared, so it cannot). +# check issue_list for each repo so nothing already open is repeated, then +# report candidate follow-up issues, each tied to the run that produced it. +# Do not create issues. # """ +# To let it file: add "issue_create" to tools and tell it to file each +# candidate (citing the run) instead of only reporting it. diff --git a/deployments/dev.toml b/deployments/dev.toml index b505b4bcf..11dc77fff 100644 --- a/deployments/dev.toml +++ b/deployments/dev.toml @@ -52,7 +52,7 @@ listen = "127.0.0.1:8587" [[curators]] name = "self-intake" interval = "1h" -tools = ["run_list", "run_events"] +tools = ["run_list", "run_events", "issue_list"] instructions = """ -You are archie's self-intake curator, in dry run. Each pass: list recent task runs with run_list, inspect anything parked or failed with run_events, then report candidate follow-up issues — concrete, each tied to the run that produced it. Do not create issues; this pass reports only (no issue-creating tool is declared, so it cannot). End your reply with the report. +You are archie's self-intake curator, in dry run. Each pass: list recent task runs with run_list, inspect anything parked or failed with run_events, check issue_list for each repo so nothing already open is repeated, then report candidate follow-up issues — concrete, each tied to the run that produced it. Do not create issues; this pass reports only (no issue-creating tool is declared, so it cannot). End your reply with the report. """ diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 3f2772aad..840d00d64 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -50,6 +50,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/controlplanestore" "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" "github.com/samcharles93/archie-core/internal/infrastructure/extension" + "github.com/samcharles93/archie-core/internal/infrastructure/issuerpc" "github.com/samcharles93/archie-core/internal/infrastructure/kitrun" "github.com/samcharles93/archie-core/internal/infrastructure/logrpc" "github.com/samcharles93/archie-core/internal/infrastructure/messagingrpc" @@ -587,9 +588,30 @@ func (b *boot) registerNATSRPC() error { return err } b.addCleanup(unsubscribeTaskActions) + + unsubscribeIssues, err := (&issuerpc.Server{Forge: b.issueForge, Allowed: b.managedRepository, Log: log}).Register(coreConn) + if err != nil { + log.Error("issue RPC register failed", "err", err) + return err + } + b.addCleanup(unsubscribeIssues) return nil } +// issueForge is the instance forge, or nil while none is configured. +func (b *boot) issueForge() forge.IssueForge { + if b.forgeClient == nil { + return nil + } + return b.forgeClient +} + +// managedRepository refuses a repository the organisation has not added. +func (b *boot) managedRepository(ctx context.Context, owner, repo string) error { + _, err := b.repositoryBinding(ctx, owner, repo) + return err +} + func (b *boot) buildDaemon() { log := b.log b.d = &daemon.Daemon{ diff --git a/internal/app/archiegateway/tools.go b/internal/app/archiegateway/tools.go index 791857dca..fbcc4966a 100644 --- a/internal/app/archiegateway/tools.go +++ b/internal/app/archiegateway/tools.go @@ -18,6 +18,7 @@ import ( "github.com/samcharles93/archie-core/internal/gateway" infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc" + "github.com/samcharles93/archie-core/internal/infrastructure/issuerpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/taskmcp" "github.com/samcharles93/archie-core/internal/plugin" @@ -112,6 +113,11 @@ func (b *server) registerWorkflowTools(ctx context.Context) { // Run-inspection tools back long-running curators (self-intake first); // the State Store client satisfies the source directly. entries = append(entries, gateway.RunTools(b.stateStore, authz)...) + // Issue tools reach the forge through the daemon, which alone holds its + // credentials; without the broker connection they are not registered. + if b.taskActionsConn != nil { + entries = append(entries, gateway.IssueTools(issuerpc.Client{Conn: b.taskActionsConn, Timeout: 30 * time.Second}, authz)...) + } for _, entry := range entries { if err := b.toolReg.Register(entry); err != nil { b.log.WarnContext(ctx, "workflow tool registration failed", "tool", entry.Name, "err", err) diff --git a/internal/gateway/issue_tools.go b/internal/gateway/issue_tools.go new file mode 100644 index 000000000..29f86f26e --- /dev/null +++ b/internal/gateway/issue_tools.go @@ -0,0 +1,129 @@ +package gateway + +import ( + "context" + "fmt" + "strings" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/forge" + "github.com/samcharles93/archie-core/internal/tools" +) + +// maxIssueListed bounds what issue_list returns, so a large backlog does not +// land in the context window whole. +const maxIssueListed = 200 + +// IssueSource is the forge surface the issue tools use, reached through the +// daemon. +type IssueSource interface { + OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error) + CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) +} + +// IssueSummary is one open issue as issue_list shows it. +type IssueSummary struct { + Number int `json:"number"` + Title string `json:"title"` + Labels []string `json:"labels,omitempty"` +} + +// IssueTools returns issue_list and issue_create for curators. Filing work +// feeds the daemon's issue intake, so both are checked as acting on tasks. +// Nil source or authorizer registers none. +func IssueTools(source IssueSource, authz access.Authorizer) []tools.ToolEntry { + if source == nil || authz == nil { + return nil + } + return []tools.ToolEntry{ + guarded(authz, access.ActionRead, access.KindTask, nil, issueListTool(source)), + guarded(authz, access.ActionCreate, access.KindTask, nil, issueCreateTool(source)), + } +} + +var repoProperty = map[string]any{ + "type": "string", + "description": "The repository as owner/name, as run_list reports it.", +} + +func splitRepo(input map[string]any) (owner, repo string, err error) { + raw, _ := input["repo"].(string) + owner, repo, ok := strings.Cut(strings.TrimSpace(raw), "/") + if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") { + return "", "", fmt.Errorf("repo must be owner/name") + } + return owner, repo, nil +} + +func issueListTool(source IssueSource) tools.ToolEntry { + return tools.ToolEntry{ + Name: "issue_list", + Toolset: "issues", + Description: "List a repository's open issues (number, title, labels). Check it before filing so you never duplicate one.", + Classification: tools.ClassIdempotent, + Schema: tools.JSONSchema{ + "type": "object", + "properties": map[string]any{"repo": repoProperty}, + "required": []string{"repo"}, + }, + Handler: func(ctx context.Context, input map[string]any) (any, error) { + owner, repo, err := splitRepo(input) + if err != nil { + return nil, fmt.Errorf("issue_list: %w", err) + } + issues, err := source.OpenIssues(ctx, owner, repo) + if err != nil { + return nil, fmt.Errorf("issue_list: %w", err) + } + out := make([]IssueSummary, 0, min(len(issues), maxIssueListed)) + for _, is := range issues[:min(len(issues), maxIssueListed)] { + out = append(out, IssueSummary{Number: is.Number, Title: is.Title, Labels: is.Labels}) + } + return out, nil + }, + } +} + +func issueCreateTool(source IssueSource) tools.ToolEntry { + return tools.ToolEntry{ + Name: "issue_create", + Toolset: "issues", + Description: "File a new issue in a repository. List open issues first and file only work no open issue covers. " + + "The body must cite the run that produced it.", + Classification: tools.ClassMutating, + Schema: tools.JSONSchema{ + "type": "object", + "properties": map[string]any{ + "repo": repoProperty, + "title": map[string]any{"type": "string"}, + "body": map[string]any{"type": "string"}, + "labels": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, + }, + "required": []string{"repo", "title", "body"}, + }, + Handler: func(ctx context.Context, input map[string]any) (any, error) { + owner, repo, err := splitRepo(input) + if err != nil { + return nil, fmt.Errorf("issue_create: %w", err) + } + title, _ := input["title"].(string) + body, _ := input["body"].(string) + if strings.TrimSpace(title) == "" || strings.TrimSpace(body) == "" { + return nil, fmt.Errorf("issue_create: title and body are required") + } + var labels []string + if raw, ok := input["labels"].([]any); ok { + for _, l := range raw { + if s, ok := l.(string); ok && s != "" { + labels = append(labels, s) + } + } + } + number, err := source.CreateIssue(ctx, owner, repo, title, body, labels) + if err != nil { + return nil, fmt.Errorf("issue_create: %w", err) + } + return map[string]any{"number": number}, nil + }, + } +} diff --git a/internal/infrastructure/issuerpc/issuerpc.go b/internal/infrastructure/issuerpc/issuerpc.go new file mode 100644 index 000000000..18bb14fd3 --- /dev/null +++ b/internal/infrastructure/issuerpc/issuerpc.go @@ -0,0 +1,123 @@ +// Package issuerpc lets the Gateway's curators list and file issues through +// the daemon, which alone holds forge credentials. +package issuerpc + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/nats-io/nats.go" + + "github.com/samcharles93/archie-core/internal/forge" + "github.com/samcharles93/archie-core/internal/natsrpc" +) + +const ( + listSubject = "archie.gateway.issue-list" + createSubject = "archie.gateway.issue-create" +) + +type request struct { + Owner string `json:"owner"` + Repo string `json:"repo"` + Title string `json:"title,omitempty"` + Body string `json:"body,omitempty"` + Labels []string `json:"labels,omitempty"` +} + +type listResponse struct { + natsrpc.Envelope + Issues []forge.Issue `json:"issues,omitempty"` +} + +type createResponse struct { + natsrpc.Envelope + Number int `json:"number,omitempty"` +} + +// Server is the daemon side. Forge returns the instance forge, or nil while +// none is configured; Allowed refuses a repository the instance does not manage. +type Server struct { + Forge func() forge.IssueForge + Allowed func(ctx context.Context, owner, repo string) error + Log *slog.Logger +} + +func (s *Server) forge(ctx context.Context, req request) (forge.IssueForge, error) { + if err := s.Allowed(ctx, req.Owner, req.Repo); err != nil { + return nil, err + } + f := s.Forge() + if f == nil { + return nil, errors.New("forge is not configured") + } + return f, nil +} + +// Register serves the issue subjects on nc. +func (s *Server) Register(nc *nats.Conn) (func(), error) { + return natsrpc.RegisterAll(nc, []natsrpc.Registration{ + {Subject: listSubject, Handler: func(ctx context.Context, msg *nats.Msg) { + var req request + if err := json.Unmarshal(msg.Data, &req); err != nil { + natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err)}) + return + } + f, err := s.forge(ctx, req) + var issues []forge.Issue + if err == nil { + issues, err = f.IssuesWithLabel(ctx, req.Owner, req.Repo, "") + } + natsrpc.Respond(msg, s.Log, "issuerpc", listResponse{Envelope: natsrpc.NewEnvelope(err), Issues: issues}) + }}, + {Subject: createSubject, Handler: func(ctx context.Context, msg *nats.Msg) { + var req request + if err := json.Unmarshal(msg.Data, &req); err != nil { + natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err)}) + return + } + f, err := s.forge(ctx, req) + var number int + if err == nil { + number, err = f.CreateIssue(ctx, req.Owner, req.Repo, req.Title, req.Body, req.Labels) + } + natsrpc.Respond(msg, s.Log, "issuerpc", createResponse{Envelope: natsrpc.NewEnvelope(err), Number: number}) + }}, + }) +} + +// Client is the Gateway side. +type Client struct { + Conn *nats.Conn + Timeout time.Duration +} + +func (c Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} } + +// OpenIssues lists every open issue (not PR) of owner/repo. +func (c Client) OpenIssues(ctx context.Context, owner, repo string) ([]forge.Issue, error) { + resp, err := natsrpc.Call[listResponse](ctx, c.rpc(), listSubject, request{Owner: owner, Repo: repo}) + if err != nil { + return nil, err + } + if err := resp.Err(); err != nil { + return nil, fmt.Errorf("list issues: %w", err) + } + return resp.Issues, nil +} + +// CreateIssue files an issue and returns its number. +func (c Client) CreateIssue(ctx context.Context, owner, repo, title, body string, labels []string) (int, error) { + resp, err := natsrpc.Call[createResponse](ctx, c.rpc(), createSubject, request{Owner: owner, Repo: repo, Title: title, Body: body, Labels: labels}) + if err != nil { + return 0, err + } + if err := resp.Err(); err != nil { + return 0, fmt.Errorf("create issue: %w", err) + } + return resp.Number, nil +}