From 12dd3084e57155f614a411e9fde78762e0bd62aa Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 26 Oct 2026 00:56:07 +1100 Subject: [PATCH] feat(workflow): message.send step delivers text through archied's messaging client --- WORKFLOWS.md | 17 ++ internal/app/agentworker/task_execution.go | 12 +- internal/app/agentworker/worker.go | 2 + internal/app/archied/bootstrap.go | 5 + internal/app/archied/main.go | 12 +- internal/app/archied/task_broker.go | 2 + internal/domain/workflow/message_send.go | 53 +++++++ internal/domain/workflow/workflow.go | 2 + .../agenttransport/nats/transport.go | 6 + .../workflowsteps/workflowsteps.go | 2 +- internal/messagerpc/messagerpc.go | 145 ++++++++++++++++++ internal/messagerpc/messagerpc_test.go | 49 ++++++ 12 files changed, 299 insertions(+), 8 deletions(-) create mode 100644 internal/domain/workflow/message_send.go create mode 100644 internal/messagerpc/messagerpc.go create mode 100644 internal/messagerpc/messagerpc_test.go diff --git a/WORKFLOWS.md b/WORKFLOWS.md index 91dc85ec7..be148bd1b 100644 --- a/WORKFLOWS.md +++ b/WORKFLOWS.md @@ -217,6 +217,23 @@ _runs without a repository._ | `body` | text | The comment text. | | `on` | `issue` \| `pr` | Comment on the issue or the pull request. Empty means issue. | +### `message.send` + +_runs without a repository._ + +Sends text to one chat on a messaging channel. Only workflows in the system +organisation may send, and a package's workflow may not. A test run records the +message instead of sending it. + +| Setting | Type | Meaning | +|---|---|---| +| `channel` | text | The messaging channel to send through. | +| `chat_id` | text | The channel's identifier for the chat. | +| `text` | text | The message. References are filled in. | + +A scheduled message is a schedule bound to a workflow whose only step is +`message.send`. + ### `workflow.approve` _runs without a repository._ diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index c6e610df4..6cc45e0b4 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -135,11 +135,12 @@ func worktreeOwnerID(env string) int { } type taskDependencies struct { - forge workflow.Forger - store workflow.Store - calls task.Caller - trees remoteTrees - events agentexec.EventPublisher + forge workflow.Forger + messenger workflow.Messenger + store workflow.Store + calls task.Caller + trees remoteTrees + events agentexec.EventPublisher // steps is the workflow step vocabulary pinned definitions are compiled // against, registered at the composition root and injected: this is the // executing half of the contract whose validating half is the control @@ -255,6 +256,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen Forge: dependencies.forge, Store: dependencies.store, Calls: dependencies.calls, + Messenger: dependencies.messenger, Trees: trees, Agent: agent, Bus: bus, diff --git a/internal/app/agentworker/worker.go b/internal/app/agentworker/worker.go index c68d35518..aba58cb35 100644 --- a/internal/app/agentworker/worker.go +++ b/internal/app/agentworker/worker.go @@ -188,6 +188,7 @@ func run(ctx context.Context, settings Settings, log *slog.Logger, dependencies type taskServiceTransport interface { Forger(identity, credential string, timeout time.Duration) workflow.Forger + Messenger(identity, credential string, timeout time.Duration) workflow.Messenger Store(time.Duration) workflow.Store Calls(time.Duration) task.Caller Trees(string, string, time.Duration) agentnats.RemoteTrees @@ -198,6 +199,7 @@ func executeTaskRequest(ctx context.Context, request taskrun.Request, transport log.InfoContext(ctx, "running task", "task", request.Task.ID, "repo", request.Repo.FullName(), "issue", request.Task.IssueNumber) dependencies := taskDependencies{ forge: transport.Forger(request.Task.Identity, request.RunCredential, rpcTimeout), + messenger: transport.Messenger(request.Task.Identity, request.RunCredential, rpcTimeout), store: transport.Store(rpcTimeout), calls: transport.Calls(rpcTimeout), trees: transport.Trees(request.Task.Identity, request.RunCredential, rpcTimeout), diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 820204de0..a2633e3b3 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -550,6 +550,11 @@ func (b *boot) registerNATSRPC() error { return daemon.RepositoryAccess{}, errors.New("repository connections starting") } return b.d.Repository(ctx, t, op) + }, func(ctx context.Context, channel, chatID, text string) error { + if b.messaging == nil { + return errors.New("messaging service not configured") + } + return b.messaging.Deliver(ctx, channel, chatID, text) }, b.stateStoreGrants.Client, installedAuthorities{b.stateStoreGrants.Client}, log) if err != nil { log.Error("task RPC server registration failed", "err", err) diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 9efb4445d..c80d25d6f 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -40,6 +40,7 @@ import ( "github.com/samcharles93/archie-core/internal/infrastructure/configuration" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/logging" + "github.com/samcharles93/archie-core/internal/messagerpc" "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/worktree" @@ -348,7 +349,7 @@ func subscribeAgentEvents(nc *natsio.Conn, bus *events.Bus, log *slog.Logger) (u // registerTaskRPCServers routes each request through the current task binding. // Wildcard subjects serve identities created after daemon startup; credentials // and repository bounds are checked before the connection is resolved. -func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *workflow.Task, string) (daemon.RepositoryAccess, error), runs worktreerpc.Runs, authorities forgerpc.Authorities, log *slog.Logger) (func(), error) { +func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *workflow.Task, string) (daemon.RepositoryAccess, error), deliver func(ctx context.Context, channel, chatID, text string) error, runs worktreerpc.Runs, authorities forgerpc.Authorities, log *slog.Logger) (func(), error) { var unsubs []func() unsubscribe := func() { for _, stop := range unsubs { @@ -363,8 +364,15 @@ func registerTaskRPCServers(nc *natsio.Conn, resolve func(context.Context, *work resolved, err := resolve(ctx, t, config.OperationPush) return resolved.Trees, err }} + messages := &messagerpc.Server{Runs: runs, Deliver: deliver, Log: log} for _, identity := range []string{"", "*"} { - stop, err := fg.RegisterFor(nc, identity) + stop, err := messages.RegisterFor(nc, identity) + if err != nil { + unsubscribe() + return nil, err + } + unsubs = append(unsubs, stop) + stop, err = fg.RegisterFor(nc, identity) if err != nil { unsubscribe() return nil, err diff --git a/internal/app/archied/task_broker.go b/internal/app/archied/task_broker.go index b54c63ff8..90fde30fa 100644 --- a/internal/app/archied/task_broker.go +++ b/internal/app/archied/task_broker.go @@ -10,6 +10,7 @@ import ( agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats" "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" "github.com/samcharles93/archie-core/internal/infrastructure/spanrelay" + "github.com/samcharles93/archie-core/internal/messagerpc" "github.com/samcharles93/archie-core/internal/worktreerpc" ) @@ -34,6 +35,7 @@ func (b taskBroker) TaskSubjects(ctx context.Context, taskID int64, credential s agentexec.SubjectForEvents(taskID), spanrelay.Subject(taskID), worktreerpc.SubjectFor(task.Identity, worktreerpc.SubjectPush), + messagerpc.SubjectFor(task.Identity), }, forgerpc.Subjects(task.Identity)...) return nats.TaskSubjects{Publish: publish, Subscribe: []string{agentnats.SubjectForTask(taskID)}}, nil } diff --git a/internal/domain/workflow/message_send.go b/internal/domain/workflow/message_send.go new file mode 100644 index 000000000..fcc09ed6b --- /dev/null +++ b/internal/domain/workflow/message_send.go @@ -0,0 +1,53 @@ +package workflow + +import ( + "context" + "errors" + "fmt" + "strings" + + "gopkg.in/yaml.v3" +) + +// MessageSendStepName is the step type that sends text to a chat on a +// messaging channel. +const MessageSendStepName = "message.send" + +// Messenger delivers text to one chat on a named messaging channel. +type Messenger interface { + Deliver(ctx context.Context, channel, chatID, text string) error +} + +type messageSendSettings struct { + Channel string `yaml:"channel" doc:"The messaging channel to send through."` + ChatID string `yaml:"chat_id" title:"Chat ID" doc:"The channel's identifier for the chat."` + Text string `yaml:"text" doc:"The message. References to earlier steps and the event are filled in."` +} + +// MessageSendStepType contributes the message.send step type. +func MessageSendStepType() StepType { + return StepType{Name: MessageSendStepName, Factory: newMessageSendStage, Settings: messageSendSettings{}} +} + +func newMessageSendStage(settings yaml.Node) (Stage, error) { + s, err := decodeSettings[messageSendSettings](MessageSendStepName, settings) + if err != nil { + return Stage{}, err + } + if strings.TrimSpace(s.Channel) == "" || strings.TrimSpace(s.ChatID) == "" || strings.TrimSpace(s.Text) == "" { + return Stage{}, fmt.Errorf("%s: settings.channel, settings.chat_id and settings.text are required", MessageSendStepName) + } + return Stage{Name: MessageSendStepName, Run: func(ctx context.Context, tc *TaskContext) error { + if tc.Deliveries != nil { + tc.Deliveries.Record(ctx, fmt.Sprintf("send to %s chat %s: %s", s.Channel, s.ChatID, s.Text)) + return nil + } + if tc.Messenger == nil { + return errors.New("message.send: this runner cannot reach the messaging service") + } + if err := tc.Messenger.Deliver(ctx, s.Channel, s.ChatID, s.Text); err != nil { + return fmt.Errorf("message.send to %s chat %s: %w", s.Channel, s.ChatID, err) + } + return nil + }}, nil +} diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index ed973ca8b..59b88e7bd 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -110,6 +110,8 @@ type TaskContext struct { // workflow.call step: such a step in a runner with no capability // fails the run with a named error. Calls task.Caller + // Messenger sends message.send steps' text. Nil fails those steps. + Messenger Messenger // PRSource fetches pull requests for the pr-review workflow. Nil fails those // stages. PRSource PRSource diff --git a/internal/infrastructure/agenttransport/nats/transport.go b/internal/infrastructure/agenttransport/nats/transport.go index 525e51442..e79232c24 100644 --- a/internal/infrastructure/agenttransport/nats/transport.go +++ b/internal/infrastructure/agenttransport/nats/transport.go @@ -24,6 +24,7 @@ import ( "github.com/samcharles93/archie-core/internal/forgerpc" eventbus "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" + "github.com/samcharles93/archie-core/internal/messagerpc" "github.com/samcharles93/archie-core/internal/natsrpc" "github.com/samcharles93/archie-core/internal/taskrun" "github.com/samcharles93/archie-core/internal/worktreerpc" @@ -154,6 +155,11 @@ func (t *Transport) Forger(identity, credential string, timeout time.Duration) w return &forgerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity, Credential: credential} } +// Messenger constructs the identity-scoped message.send RPC client. +func (t *Transport) Messenger(identity, credential string, timeout time.Duration) workflow.Messenger { + return &messagerpc.Client{Conn: t.conn, Timeout: timeout, Identity: identity, Credential: credential} +} + // Store returns the State Store client, bounding each call by timeout when // ctx has no deadline. func (t *Transport) Store(timeout time.Duration) workflow.Store { diff --git a/internal/infrastructure/workflowsteps/workflowsteps.go b/internal/infrastructure/workflowsteps/workflowsteps.go index 7699e8d33..395a9cf02 100644 --- a/internal/infrastructure/workflowsteps/workflowsteps.go +++ b/internal/infrastructure/workflowsteps/workflowsteps.go @@ -32,7 +32,7 @@ type eventSteps struct{} func (eventSteps) Name() string { return "event" } func (eventSteps) StepTypes() []workflow.StepType { - return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType(), workflow.FinishStepType()} + return []workflow.StepType{workflow.AgentRunStepType(), workflow.WorkflowCallStepType(), workflow.FinishStepType(), workflow.MessageSendStepType()} } // commandSteps provides the command.run step type: operator-authored commands diff --git a/internal/messagerpc/messagerpc.go b/internal/messagerpc/messagerpc.go new file mode 100644 index 000000000..4a41d444b --- /dev/null +++ b/internal/messagerpc/messagerpc.go @@ -0,0 +1,145 @@ +// Package messagerpc lets archie-agent run a message.send step over NATS +// request/reply, so only archied reaches the Messaging Service. +package messagerpc + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "github.com/nats-io/nats.go" + + domainidentity "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/natsrpc" +) + +// SubjectDeliver is the root subject a task's message.send publishes to. +const SubjectDeliver = "archie.message.deliver" + +// SubjectFor returns SubjectDeliver scoped to identity, or the root subject +// when identity is empty. Keyed by the identity's ID, as forgerpc.SubjectFor is. +func SubjectFor(identity string) string { + if identity == "" { + return SubjectDeliver + } + return "archie.message." + string(domainidentity.StableID(identity)) + ".deliver" +} + +func serverSubject(identity string) string { + if identity == "*" { + return "archie.message.*.deliver" + } + return SubjectFor(identity) +} + +// DeliverRequest is one message, with the run credential of the task sending it. +type DeliverRequest struct { + Credential string + Channel string + ChatID string + Text string +} + +// Response is a bare success/error envelope. +type Response struct { + natsrpc.Envelope +} + +// Runs resolves a run credential to the task it was issued for. +type Runs interface { + TaskForCredential(ctx context.Context, token string) (*workflow.Task, error) +} + +// Server delivers authorized requests through Deliver. +type Server struct { + Runs Runs + Deliver func(ctx context.Context, channel, chatID, text string) error + Log *slog.Logger +} + +// RegisterFor registers the handler under the subject scoped to identity; +// "*" answers every identity. +func (s *Server) RegisterFor(nc *nats.Conn, identity string) (func(), error) { + return natsrpc.RegisterAll(nc, []natsrpc.Registration{{ + Subject: serverSubject(identity), + Handler: func(ctx context.Context, msg *nats.Msg) { + scoped := identity + if identity == "*" { + scoped = strings.Split(msg.Subject, ".")[2] + } + s.handleDeliver(ctx, scoped, msg) + }, + }}) +} + +func (s *Server) handleDeliver(ctx context.Context, identity string, msg *nats.Msg) { + var req DeliverRequest + if err := json.Unmarshal(msg.Data, &req); err != nil { + s.respond(msg, fmt.Errorf("decode deliver request: %w", err)) + return + } + if err := s.authorize(ctx, identity, req.Credential); err != nil { + s.respond(msg, err) + return + } + if s.Deliver == nil { + s.respond(msg, errors.New("messaging service unavailable")) + return + } + s.respond(msg, s.Deliver(ctx, req.Channel, req.ChatID, req.Text)) +} + +// authorize admits a live, non-test run of this server's identity in the +// system org. Channels are instance-owned, and a package's workflow has no +// accepted authority to message them. +func (s *Server) authorize(ctx context.Context, identity, credential string) error { + if s.Runs == nil || credential == "" { + return errors.New("message request needs a run credential") + } + task, err := s.Runs.TaskForCredential(ctx, credential) + if err != nil { + return fmt.Errorf("message request credential is invalid: %w", err) + } + switch { + case identity != "" && task.Identity != identity && domainidentity.StableID(task.Identity) != domainidentity.IdentityID(identity): + return errors.New("message request is outside its run's identity") + case task.IsTestRun(): + return errors.New("a test run records deliveries instead of performing them") + case task.OrgOrDefault() != string(org.DefaultOrgID): + return errors.New("messaging channels belong to the instance; only system organisation workflows may send") + case workflow.PackageOf(task.WorkflowDefinitionYAML) != "": + return errors.New("a package's workflow may not send messages") + } + return nil +} + +func (s *Server) respond(msg *nats.Msg, err error) { + natsrpc.Respond(msg, s.Log, "messagerpc", Response{Envelope: natsrpc.NewEnvelope(err)}) +} + +// Client sends message.send steps' text from archie-agent's process. +type Client struct { + Conn *nats.Conn + // Timeout bounds each call when ctx has no deadline of its own. + Timeout time.Duration + Identity string + Credential string +} + +var _ workflow.Messenger = (*Client)(nil) + +// Deliver asks archied to send text to chatID on channel. +func (c *Client) Deliver(ctx context.Context, channel, chatID, text string) error { + req := DeliverRequest{Credential: c.Credential, Channel: channel, ChatID: chatID, Text: text} + resp, err := natsrpc.Call[Response](ctx, &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout}, SubjectFor(c.Identity), req) + if err != nil { + return err + } + return resp.Err() +} diff --git a/internal/messagerpc/messagerpc_test.go b/internal/messagerpc/messagerpc_test.go new file mode 100644 index 000000000..8b3c4bd89 --- /dev/null +++ b/internal/messagerpc/messagerpc_test.go @@ -0,0 +1,49 @@ +package messagerpc + +import ( + "context" + "errors" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" +) + +type fakeRuns map[string]*workflow.Task + +func (f fakeRuns) TaskForCredential(_ context.Context, token string) (*workflow.Task, error) { + if task, ok := f[token]; ok { + return task, nil + } + return nil, errors.New("unknown credential") +} + +func TestAuthorize(t *testing.T) { + runs := fakeRuns{ + "sys": {Identity: "archie"}, + "org": {Identity: "archie", Org: "org-acme"}, + "test": {Identity: "archie", Source: task.SourceTest}, + "package": {Identity: "archie", WorkflowDefinitionYAML: "package: vendor/thing\nname: x\n"}, + } + tests := []struct { + name, identity, credential string + ok bool + }{ + {"system org run", "archie", "sys", true}, + {"no credential", "archie", "", false}, + {"unknown credential", "archie", "nope", false}, + {"other identity", "someone-else", "sys", false}, + {"non-system org", "archie", "org", false}, + {"test run", "archie", "test", false}, + {"package workflow", "archie", "package", false}, + } + s := &Server{Runs: runs} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := s.authorize(context.Background(), tt.identity, tt.credential) + if (err == nil) != tt.ok { + t.Fatalf("authorize() err = %v, want ok %v", err, tt.ok) + } + }) + } +}