refactor(controlplane): move the store-backed server out of internal/app

This commit is contained in:
sam committed 2026-10-25 22:49:27 +11:00
1 parent 81f379346e
commit 29a2a782c9
59 files changed
+154 -154

No files matched your search

@@ -18,7 +18,7 @@ import (
// ChannelSettingsKind is the control-plane resource kind holding the channel
// settings document. It is declared here because this package owns the document
// and the client names the kind; internal/app/controlplane re-exports it, so the
// and the client names the kind; internal/infrastructure/controlplanestore re-exports it, so the
// store-backed side and its callers keep one name for one kind.
const ChannelSettingsKind = "channel-settings"
@@ -39,7 +39,7 @@ func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { return &Client{
// ResourceReader is the read side of the control-plane client: one resource
// query per kind. The store-backed server implements it too, which is why the
// layering functions here are shared with internal/app/controlplane.
// layering functions here are shared with internal/infrastructure/controlplanestore.
type ResourceReader interface {
Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error)
}
@@ -0,0 +1,58 @@
package controlplanestore
import "github.com/samcharles93/archie-core/internal/config"
// AgentProfileKind is the control-plane resource holding agent profiles. Its
// document is the snake_case agentProfile wire type, not config.AgentProfile,
// which has no json tags.
const AgentProfileKind = "agent-profiles"
func agentProfileDefinition() Definition {
return Definition{
Kind: AgentProfileKind,
Title: "Agent profiles",
ApplyMode: "live",
Document: map[string]agentProfile{},
Seed: seedAgentProfiles,
Validate: validateAgentProfiles,
}
}
func seedAgentProfiles(cfg config.Config) any {
return agentProfilesDocument(cfg.Containers.Profiles)
}
// agentProfilesDocument maps the internal type to the document's wire type.
func agentProfilesDocument(profiles map[string]config.AgentProfile) map[string]agentProfile {
if profiles == nil {
return nil
}
out := make(map[string]agentProfile, len(profiles))
for name, p := range profiles {
out[name] = agentProfile{Image: p.Image, Kit: p.Kit, Adapter: p.Adapter, Tools: p.Tools}
}
return out
}
// agentProfilesSettings reverses agentProfilesDocument, for the layering in
// runtime_config.go and for validation against config.ValidateAgentProfiles.
func agentProfilesSettings(profiles map[string]agentProfile) map[string]config.AgentProfile {
if profiles == nil {
return nil
}
out := make(map[string]config.AgentProfile, len(profiles))
for name, p := range profiles {
out[name] = config.AgentProfile{Image: p.Image, Kit: p.Kit, Adapter: p.Adapter, Tools: p.Tools}
}
return out
}
func validateAgentProfiles(input []byte) error {
// The rules live in the config package and are shared with the file
// document's own validation (config.ContainerConfig.ValidateProfiles):
// which profiles are valid cannot differ between the file that seeds
// this resource and the resource that replaces it.
return validateAs(input, func(profiles map[string]agentProfile) error {
return config.ValidateAgentProfiles(agentProfilesSettings(profiles))
})
}
@@ -0,0 +1,103 @@
package controlplanestore
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/samcharles93/archie-core/internal/config"
)
const (
AuditRetentionKind = "audit-retention"
// MinimumAuditRetention is the shortest retention the resource accepts:
// below a week the audit trail is unlikely to outlive the investigation
// that needs it.
MinimumAuditRetention = 7 * 24 * time.Hour
// auditRetentionSeed keeps observability events for 90 days.
auditRetentionSeed = "2160h"
)
// auditRetention is the audit-retention document. Zero keeps the observability
// trail forever; any other value is a Go duration of at least a week.
type auditRetention struct {
RuntimeEventRetention string `json:"runtime_event_retention"`
}
func auditRetentionDefinition() Definition {
return Definition{
Kind: AuditRetentionKind, Title: "Audit retention", ApplyMode: "live",
Document: auditRetention{},
Seed: func(config.Config) any { return auditRetention{RuntimeEventRetention: auditRetentionSeed} },
Validate: validateAuditRetention,
Normalize: normalizeAuditRetention,
}
}
func validateAuditRetention(input []byte) error {
return validateAs(input, func(document auditRetention) error {
_, err := parseRuntimeEventRetention(document.RuntimeEventRetention)
return err
})
}
// RuntimeEventRetention decodes a stored audit-retention document and returns
// how long observability events are kept. Zero means keep forever. The sweep
// uses this same parser, so a value the control plane accepted is one the
// sweep can run.
func RuntimeEventRetention(document []byte) (time.Duration, error) {
decoded, err := auditRetentionDocument(document)
if err != nil {
return 0, err
}
return parseRuntimeEventRetention(decoded.RuntimeEventRetention)
}
func auditRetentionDocument(document []byte) (auditRetention, error) {
var decoded auditRetention
reader := json.NewDecoder(bytes.NewReader(document))
reader.DisallowUnknownFields()
if err := reader.Decode(&decoded); err != nil {
return auditRetention{}, fmt.Errorf("decode %s: %w", AuditRetentionKind, err)
}
return decoded, nil
}
// normalizeAuditRetention stores the retention in whole hours: the audit page
// parses "<n>h" only, so a value such as 604800s would read as zero there and
// the next save would disable pruning. Zero stays "0".
func normalizeAuditRetention(input []byte) ([]byte, error) {
decoded, err := auditRetentionDocument(input)
if err != nil {
return nil, err
}
retention, err := parseRuntimeEventRetention(decoded.RuntimeEventRetention)
if err != nil {
return nil, err
}
decoded.RuntimeEventRetention = formatRuntimeEventRetention(retention)
return json.Marshal(decoded)
}
func formatRuntimeEventRetention(retention time.Duration) string {
if retention == 0 {
return "0"
}
return strconv.FormatInt(int64(retention/time.Hour), 10) + "h"
}
func parseRuntimeEventRetention(value string) (time.Duration, error) {
retention, err := time.ParseDuration(value)
if err != nil {
return 0, fmt.Errorf("runtime_event_retention must be a duration such as 2160h: %w", err)
}
if retention < 0 {
return 0, fmt.Errorf("runtime_event_retention must not be negative")
}
if retention > 0 && retention < MinimumAuditRetention {
return 0, fmt.Errorf("runtime_event_retention must be at least 168h, or 0 to keep forever")
}
return retention, nil
}
@@ -0,0 +1,48 @@
package controlplanestore
import (
"encoding/json"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// Aliases for the channel-settings document defined in controlplanerpc.
type (
channelSettings = controlplanerpc.ChannelSettings
telegramSettings = controlplanerpc.TelegramSettings
rateLimitSettings = controlplanerpc.RateLimitSettings
channelDuration = controlplanerpc.ChannelDuration
)
// ChannelSettingsKind is re-exported so the store-backed side and its callers
// keep naming one kind by one name.
const ChannelSettingsKind = controlplanerpc.ChannelSettingsKind
func seedChannels(cfg config.Config) any {
chat := cfg.Chat
return channelSettings{
Operator: chat.Operator, Workspace: chat.Workspace, UnrestrictedFilesystem: chat.UnrestrictedFilesystem, ShowToolCalls: chat.ShowToolCalls, MaxSteps: chat.MaxSteps,
Telegram: telegramSettings{AllowedUserIDs: chat.Telegram.AllowedUserIDs, Token: chat.Telegram.Token, CredentialConfigured: chat.Telegram.Token != (config.SecretRef{})},
RateLimit: rateLimitSettings{Window: channelDuration(chat.RateLimit.Window), MaxRequests: chat.RateLimit.MaxRequests},
}
}
func validateChannels(input []byte) error {
return validateAs(input, func(settings channelSettings) error {
if settings.MaxSteps < 0 || settings.RateLimit.MaxRequests < 0 || settings.RateLimit.Window < 0 {
return fmt.Errorf("channel limits must not be negative")
}
return nil
})
}
// normalizeChannels re-encodes the stored document with snake_case keys.
func normalizeChannels(input []byte) ([]byte, error) {
var settings channelSettings
if err := json.Unmarshal(input, &settings); err != nil {
return nil, err
}
return json.Marshal(settings)
}
@@ -0,0 +1,248 @@
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"time"
"google.golang.org/grpc"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// Client reads and watches control-plane resources. It embeds the Messaging
// Service's client and adds resource-specific reads.
type Client struct {
*controlplanerpc.Client
rpc pb.ControlPlaneServiceClient
ApplyStatus *applystatus.Reporter
}
// NewRPCClient wraps an already-constructed generated client.
func NewRPCClient(client pb.ControlPlaneServiceClient) *Client {
return &Client{Client: controlplanerpc.NewRPCClient(client), rpc: client}
}
// WorkflowDefinitionsClient reads and replaces the workflow-definitions
// resource, resolving step types against the given vocabulary.
type WorkflowDefinitionsClient struct {
rpc pb.ControlPlaneServiceClient
steps workflow.StepRegistry
ApplyStatus *applystatus.Reporter
}
func NewWorkflowDefinitionsClient(client pb.ControlPlaneServiceClient, steps *workflow.Manager) (*WorkflowDefinitionsClient, error) {
registry, err := stepRegistry(steps)
if err != nil {
return nil, err
}
return &WorkflowDefinitionsClient{rpc: client, steps: registry}, nil
}
func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error) {
response, err := c.rpc.Catalog(ctx, &pb.CatalogRequest{})
if err != nil {
return nil, controlplanerpc.ClientError(err)
}
return response.Resources, nil
}
func (c *WorkflowDefinitionsClient) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowDefinitionsKind})
if err != nil {
c.ApplyStatus.Report(ctx, WorkflowDefinitionsKind, 0, err)
return workflow.WorkflowDefinitionCollection{}, 0, controlplanerpc.ClientError(err)
}
definitions, err := workflow.DecodeDefinitionCollection(response.Resource.ValueJson, c.steps)
c.ApplyStatus.Report(ctx, WorkflowDefinitionsKind, response.Resource.Version, err)
return definitions, response.Resource.Version, err
}
// Keep reads the collection now and every interval after, so the apply status
// is reported without waiting for the first workflow to resolve.
func (c *WorkflowDefinitionsClient) Keep(ctx context.Context, interval time.Duration) {
keepLoading(ctx, interval, func() { _, _, _ = c.WorkflowDefinitions(ctx) })
}
// ReplaceWorkflowDefinitions replaces the collection, keeping the previous
// value in history.
func (c *WorkflowDefinitionsClient) ReplaceWorkflowDefinitions(ctx context.Context, definitions workflow.WorkflowDefinitionCollection, expectedVersion int64, actor, source, requestID string) (int64, error) {
value, err := encodeWorkflowDefinitions(definitions, c.steps)
if err != nil {
return 0, err
}
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: WorkflowDefinitionsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
if err != nil {
return 0, controlplanerpc.ClientError(err)
}
return response.Resource.Version, nil
}
func (c *Client) WorkflowExecutionSettings(ctx context.Context) (workflow.ExecutionSettings, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowExecutionSettingsKind})
if err != nil {
return workflow.ExecutionSettings{}, 0, controlplanerpc.ClientError(err)
}
settings, err := decodeSettings(response.Resource.ValueJson)
return settings, response.Resource.Version, err
}
func (c *Client) ReplaceWorkflowExecutionSettings(ctx context.Context, settings workflow.ExecutionSettings, expectedVersion int64, actor, source, requestID string) (int64, error) {
if err := settings.Validate(); err != nil {
return 0, fmt.Errorf("%w: %w", ErrValidation, err)
}
value, err := encodeSettings(settings)
if err != nil {
return 0, err
}
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: WorkflowExecutionSettingsKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
if err != nil {
return 0, controlplanerpc.ClientError(err)
}
return response.Resource.Version, nil
}
func (c *Client) WatchWorkflowExecutionSettings(ctx context.Context, afterVersion int64) (<-chan AppliedSettings, error) {
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: WorkflowExecutionSettingsKind, AfterVersion: afterVersion})
if err != nil {
return nil, controlplanerpc.ClientError(err)
}
return watchUpdates(ctx, stream,
func(resource *pb.Resource) AppliedSettings {
settings, err := decodeSettings(resource.ValueJson)
return AppliedSettings{Settings: settings, Version: resource.Version, Err: err}
},
func(err error) AppliedSettings { return AppliedSettings{Err: err} }), nil
}
// AppliedResource is a watched resource's version, without its document.
type AppliedResource struct {
Version int64
Err error
}
// WatchResource streams version updates for a resource kind without decoding
// documents.
func (c *Client) WatchResource(ctx context.Context, kind string, afterVersion int64) (<-chan AppliedResource, error) {
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: kind, AfterVersion: afterVersion})
if err != nil {
return nil, controlplanerpc.ClientError(err)
}
return watchUpdates(ctx, stream,
func(resource *pb.Resource) AppliedResource { return AppliedResource{Version: resource.Version} },
func(err error) AppliedResource { return AppliedResource{Err: err} }), nil
}
type AppliedSettings struct {
Settings workflow.ExecutionSettings
Version int64
Err error
}
func (c *Client) Soul(ctx context.Context) (agent.Soul, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SoulKind})
if err != nil {
return agent.Soul{}, 0, controlplanerpc.ClientError(err)
}
soul, err := decodeSoul(response.Resource.ValueJson)
return soul, response.Resource.Version, err
}
type AppliedSoul struct {
Soul agent.Soul
Version int64
Err error
}
func (c *Client) WatchSoul(ctx context.Context, afterVersion int64) (<-chan AppliedSoul, error) {
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: SoulKind, AfterVersion: afterVersion})
if err != nil {
return nil, controlplanerpc.ClientError(err)
}
return watchUpdates(ctx, stream,
func(resource *pb.Resource) AppliedSoul {
soul, err := decodeSoul(resource.ValueJson)
return AppliedSoul{Soul: soul, Version: resource.Version, Err: err}
},
func(err error) AppliedSoul { return AppliedSoul{Err: err} }), nil
}
// watchUpdates turns one Watch stream into the channel a watch loop reads: every
// document the stream carries, decoded, and then a single update carrying the
// error that ended it -- unless the stream ended cleanly or the context did, in
// which case the channel just closes.
func watchUpdates[T any](
ctx context.Context,
stream grpc.ServerStreamingClient[pb.WatchResponse],
update func(resource *pb.Resource) T,
failed func(err error) T,
) <-chan T {
out := make(chan T)
go func() {
defer close(out)
for {
response, err := stream.Recv()
if err != nil {
if !errors.Is(err, io.EOF) && ctx.Err() == nil {
sendUpdate(ctx, out, failed(controlplanerpc.ClientError(err)))
}
return
}
if !sendUpdate(ctx, out, update(response.Resource)) {
return
}
}
}()
return out
}
// sendUpdate sends update to out, returning false if ctx ends first.
func sendUpdate[T any](ctx context.Context, out chan<- T, update T) bool {
select {
case out <- update:
return true
case <-ctx.Done():
return false
}
}
// KeepSchedules reads the schedules now and every interval after, so the apply
// status is reported before the scheduler first polls.
func (c *Client) KeepSchedules(ctx context.Context, interval time.Duration) {
keepLoading(ctx, interval, func() { _, _, _ = c.Schedules(ctx) })
}
func (c *Client) Schedules(ctx context.Context) ([]scheduling.JobSpec, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SchedulesKind})
if err != nil {
c.ApplyStatus.Report(ctx, SchedulesKind, 0, err)
return nil, 0, controlplanerpc.ClientError(err)
}
var jobs []scheduling.JobSpec
if err := json.Unmarshal(response.Resource.ValueJson, &jobs); err != nil {
c.ApplyStatus.Report(ctx, SchedulesKind, response.Resource.Version, err)
return nil, 0, err
}
c.ApplyStatus.Report(ctx, SchedulesKind, response.Resource.Version, nil)
return jobs, response.Resource.Version, nil
}
func (c *Client) ReplaceSchedules(ctx context.Context, jobs []scheduling.JobSpec, expectedVersion int64, actor, source, requestID string) (int64, error) {
value, err := json.Marshal(jobs)
if err != nil {
return 0, err
}
response, err := c.rpc.Command(ctx, &pb.CommandRequest{Kind: SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: expectedVersion, Actor: actor, Source: source, RequestId: requestID})
if err != nil {
return 0, controlplanerpc.ClientError(err)
}
return response.Resource.Version, nil
}
@@ -0,0 +1,126 @@
package controlplanestore
import (
"encoding/json"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// containerRuntimePolicies is the container-runtime-policies document, with
// snake_case JSON keys.
type containerRuntimePolicies struct {
Image string `json:"image"`
MaxConcurrency int `json:"max_concurrency"`
MaxUptime config.Duration `json:"max_uptime"`
VolumeTTL config.Duration `json:"volume_ttl"`
PullPolicy string `json:"pull_policy"`
Network string `json:"network"`
}
// agentProfile is one named execution environment as the document writes it.
type agentProfile struct {
Image string `json:"image,omitempty"`
Kit string `json:"kit,omitempty"`
Adapter string `json:"adapter,omitempty"`
Tools []string `json:"tools,omitempty"`
}
// legacyContainerKeys maps Go-cased keys from older stored documents to
// their current names.
var legacyContainerKeys = map[string]string{
"Image": "image", "MaxConcurrency": "max_concurrency", "MaxUptime": "max_uptime",
"VolumeTTL": "volume_ttl", "PullPolicy": "pull_policy", "Network": "network",
}
// legacyProfileKeys are the same fallback at the profile nesting level.
var legacyProfileKeys = map[string]string{
"Image": "image", "Kit": "kit", "Adapter": "adapter", "Tools": "tools",
}
func (p *agentProfile) UnmarshalJSON(data []byte) error {
type document agentProfile
var decoded document
err := controlplanerpc.DecodeRenamingLegacyKeys(data, legacyProfileKeys, &decoded)
if err != nil {
return err
}
*p = agentProfile(decoded)
return nil
}
func (p *containerRuntimePolicies) UnmarshalJSON(data []byte) error {
type document containerRuntimePolicies
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
// LegacyEnabled has no current field; drop it.
delete(raw, "LegacyEnabled")
// "profiles"/"Profiles" carried config.ContainerConfig.Profiles before it
// moved to its own resource, AgentProfileKind; a document stored under
// either name before that still decodes, with the key simply dropped.
delete(raw, "profiles")
delete(raw, "Profiles")
encoded, err := json.Marshal(raw)
if err != nil {
return err
}
var decoded document
if err := controlplanerpc.DecodeRenamingLegacyKeys(encoded, legacyContainerKeys, &decoded); err != nil {
return err
}
*p = containerRuntimePolicies(decoded)
return nil
}
// settings maps the document onto the internal config struct the daemon runs.
// Profiles is never set here: config.ContainerConfig.Profiles is json:"-",
// and AgentProfileKind's own layering step in runtime_config.go is what sets
// it, after this one runs.
func (p containerRuntimePolicies) settings() config.ContainerConfig {
return config.ContainerConfig{
Image: p.Image, MaxConcurrency: p.MaxConcurrency, MaxUptime: p.MaxUptime,
VolumeTTL: p.VolumeTTL, PullPolicy: p.PullPolicy, Network: p.Network,
}
}
func seedContainerPolicies(cfg config.Config) any {
containers := cfg.Containers
return containerRuntimePolicies{
Image: containers.Image, MaxConcurrency: containers.MaxConcurrency, MaxUptime: containers.MaxUptime,
VolumeTTL: containers.VolumeTTL, PullPolicy: containers.PullPolicy, Network: containers.Network,
}
}
func validateContainers(input []byte) error {
return validateAs(input, func(policies containerRuntimePolicies) error {
settings := policies.settings()
if settings.MaxConcurrency < 0 || settings.MaxUptime < 0 || settings.VolumeTTL < 0 {
return fmt.Errorf("container limits must not be negative")
}
if settings.PullPolicy != "" && settings.PullPolicy != "missing" && settings.PullPolicy != "always" {
return fmt.Errorf("pull_policy must be missing or always")
}
// The image is required for autonomous workflow workers; the same rule
// holds for the stored policies that replace the file's [containers].
if strings.TrimSpace(settings.Image) == "" {
return fmt.Errorf("container image is required for autonomous workflow workers")
}
// Profiles is json:"-" on config.ContainerConfig: it is
// AgentProfileKind's document now, validated there.
return nil
})
}
// normalizeContainerPolicies re-encodes the stored document with snake_case
// keys.
func normalizeContainerPolicies(input []byte) ([]byte, error) {
var policies containerRuntimePolicies
if err := json.Unmarshal(input, &policies); err != nil {
return nil, err
}
return json.Marshal(policies)
}
@@ -0,0 +1,262 @@
// Package controlplanestore owns control-plane resource registration, dispatch, and validation.
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// The control-plane wire sentinels cross gRPC matched on (code, canonical
// message), so their definitions live with the contract in
// internal/infrastructure/controlplanerpc. These are the same values re-exported,
// so every existing caller keeps one name and errors.Is keeps matching identity.
var (
ErrValidation = controlplanerpc.ErrValidation
ErrNotFound = controlplanerpc.ErrNotFound
ErrVersionConflict = controlplanerpc.ErrVersionConflict
ErrUnavailable = controlplanerpc.ErrUnavailable
)
// ResourceStore is the persistence the control plane requires. The composition
// root asserts the State Store against it, so this is the single definition of
// what a control-plane backing store must offer.
type ResourceStore interface {
ListResources(context.Context) ([]storecontract.Resource, error)
Resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error)
ResourceHistory(ctx context.Context, orgID, kind string, limit int) ([]storecontract.Resource, error)
PutResource(context.Context, storecontract.ResourceWrite) (storecontract.Resource, error)
}
// defaultHistoryLimit caps an unbounded request. A settings resource edited
// daily for a year still fits, and the dashboard pages rather than streams.
const defaultHistoryLimit = 200
type Server struct {
pb.UnimplementedControlPlaneServiceServer
store ResourceStore
definitions map[string]Definition
ordered []Definition
steps workflow.StepRegistry
}
// NewServer builds the control plane server the State Store serves. steps is
// the workflow step vocabulary the composition root registered; this is the
// validating side of the vocabulary archie-agent executes against in a
// matching build (see stepRegistry: a skewed deploy can still disagree).
func NewServer(resources ResourceStore, steps *workflow.Manager) (*Server, error) {
registry, err := stepRegistry(steps)
if err != nil {
return nil, err
}
definitions := builtinDefinitions(registry, steps.Settings())
byKind := make(map[string]Definition, len(definitions))
for _, definition := range definitions {
byKind[definition.Kind] = definition
}
return &Server{store: resources, definitions: byKind, ordered: definitions, steps: registry}, nil
}
// Catalog advertises the resources the caller's org can use. A definition is
// instance-only when the runtime layers it from the system org's copy alone,
// so another org would be offered a control whose write is refused; hide it
// there. Query and Command still enforce the same rule server-side.
func (s *Server) Catalog(ctx context.Context, _ *pb.CatalogRequest) (*pb.CatalogResponse, error) {
instanceOrg := requestOrg(ctx) == storecontract.DefaultOrgID
descriptors := make([]*pb.ResourceDescriptor, 0, len(s.ordered)+len(domainManagedDescriptors()))
for _, definition := range s.ordered {
if instanceOnlyKinds[definition.Kind] && !instanceOrg {
continue
}
descriptors = append(descriptors, definition.Descriptor())
}
for _, descriptor := range domainManagedDescriptors() {
if instanceOnlyKinds[descriptor.GetKind()] && !instanceOrg {
continue
}
descriptors = append(descriptors, descriptor)
}
return &pb.CatalogResponse{Resources: descriptors}, nil
}
func (s *Server) Query(ctx context.Context, request *pb.QueryRequest) (*pb.QueryResponse, error) {
if _, ok := s.definitions[request.GetKind()]; !ok {
return nil, status.Error(codes.NotFound, "resource not found")
}
resource, err := s.resource(ctx, requestOrg(ctx), request.Kind)
if err != nil {
return nil, mapError(err)
}
return &pb.QueryResponse{Resource: resourceProto(resource)}, nil
}
// History answers a resource's audit trail. The value of each revision comes
// back with it: restoring one is an ordinary replace of that value, so no
// rollback command of its own is needed.
func (s *Server) History(ctx context.Context, request *pb.HistoryRequest) (*pb.HistoryResponse, error) {
if _, ok := s.definitions[request.GetKind()]; !ok {
return nil, status.Error(codes.NotFound, "resource not found")
}
limit := int(request.GetLimit())
if limit <= 0 || limit > defaultHistoryLimit {
limit = defaultHistoryLimit
}
revisions, err := s.store.ResourceHistory(ctx, requestOrg(ctx), request.Kind, limit)
if err != nil {
return nil, mapError(err)
}
out := make([]*pb.Revision, 0, len(revisions))
for _, revision := range revisions {
out = append(out, &pb.Revision{
Version: revision.Version, ValueJson: revision.Value, Actor: revision.Actor,
Source: revision.Source, RequestId: revision.RequestID, At: timestamp(revision.At),
})
}
return &pb.HistoryResponse{Revisions: out}, nil
}
func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.CommandResponse, error) {
definition, ok := s.definitions[request.GetKind()]
command := request.GetCommand()
if !ok || (command != "replace" && command != "validate") {
return nil, status.Error(codes.NotFound, "resource or command not found")
}
if command == "validate" {
// The same checks a replace runs, without writing: a caller can learn
// that a document would be refused before it asks for the change.
value, err := definition.Decode(request.ValueJson)
if err == nil {
err = s.checkOrgWrite(ctx, requestOrg(ctx), request.Kind, value)
}
if err != nil {
return nil, mapError(err)
}
return &pb.CommandResponse{}, nil
}
if request.GetActor() == "" || request.GetSource() == "" || request.GetRequestId() == "" {
return nil, status.Error(codes.InvalidArgument, "actor, source, and request ID are required")
}
value, err := definition.Decode(request.ValueJson)
if err != nil {
return nil, mapError(err)
}
if err := s.checkOrgWrite(ctx, requestOrg(ctx), request.Kind, value); err != nil {
return nil, mapError(err)
}
resource, err := s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: requestOrg(ctx), Kind: request.Kind, Value: value, Actor: request.Actor, Source: request.Source, RequestID: request.RequestId, ExpectedVersion: request.ExpectedVersion, At: time.Now().UTC()})
if err != nil {
return nil, mapError(err)
}
return &pb.CommandResponse{Resource: resourceProto(resource)}, nil
}
func (s *Server) Watch(request *pb.WatchRequest, stream pb.ControlPlaneService_WatchServer) error {
if _, ok := s.definitions[request.GetKind()]; !ok {
return status.Error(codes.NotFound, "resource not found")
}
version := request.AfterVersion
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
for {
resource, err := s.resource(stream.Context(), requestOrg(stream.Context()), request.Kind)
if err == nil && resource.Version > version {
if err := stream.Send(&pb.WatchResponse{Resource: resourceProto(resource)}); err != nil {
return err
}
version = resource.Version
} else if err != nil && !errors.Is(err, storecontract.ErrResourceNotFound) {
return mapError(err)
}
select {
case <-stream.Context().Done():
return stream.Context().Err()
case <-ticker.C:
}
}
}
// orgSeededKinds are the kinds every organisation holds its own document of.
// Reading one an org has never written answers with the empty document: an
// org that has configured nothing has nothing, rather than the system org's
// configuration or a not-found the dashboard cannot tell from a failure.
var orgSeededKinds = map[string]bool{
WorkflowDefinitionsKind: true, WorkflowEnablementKind: true,
ForgeConnectionsKind: true, RepositoryPoliciesKind: true,
}
// resource seeds an org's workflow documents on first use, including orgs
// created after this process started. File-derived settings are never copied.
func (s *Server) resource(ctx context.Context, orgID, kind string) (storecontract.Resource, error) {
resource, err := s.store.Resource(ctx, orgID, kind)
if !errors.Is(err, storecontract.ErrResourceNotFound) || !orgSeededKinds[kind] {
// Serve the current channel schema so stored settings remain editable.
if err == nil && kind == ChannelSettingsKind {
resource.Value, err = normalizeChannels(resource.Value)
}
return resource, err
}
if _, err := s.seedKind(ctx, orgID, s.definitions[kind], config.Config{}); err != nil && !errors.Is(err, storecontract.ErrResourceVersionConflict) {
return storecontract.Resource{}, err
}
return s.store.Resource(ctx, orgID, kind)
}
func resourceProto(resource storecontract.Resource) *pb.Resource {
return &pb.Resource{OrgId: resource.OrgID, Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
}
// requestOrg is the org a request acts in, derived from the caller's
// principal when the call carried one (rpcidentity.Callers).
func requestOrg(ctx context.Context) string {
return string(org.OrgFromContext(ctx))
}
func timestamp(value time.Time) *timestamppb.Timestamp {
if value.IsZero() {
return nil
}
return timestamppb.New(value)
}
func mapError(err error) error {
switch {
case errors.Is(err, ErrValidation):
return status.Error(codes.InvalidArgument, err.Error())
case errors.Is(err, storecontract.ErrResourceNotFound):
return status.Error(codes.NotFound, err.Error())
case errors.Is(err, storecontract.ErrResourceVersionConflict):
return status.Error(codes.Aborted, err.Error())
default:
return status.Error(codes.Unavailable, err.Error())
}
}
// checkModelAliases refuses workflow definitions whose agent steps name a
// model alias the writing org cannot resolve.
func (s *Server) checkModelAliases(ctx context.Context, orgID string, value []byte) error {
models, err := s.ModelsFor(ctx, orgID)
if err != nil {
return err
}
var collection workflow.WorkflowDefinitionCollection
if err := json.Unmarshal(value, &collection); err != nil {
return err
}
if err := workflow.CheckModelAliases(collection, s.steps, models.Aliases); err != nil {
return fmt.Errorf("%w: %w", ErrValidation, err)
}
return nil
}
@@ -0,0 +1,73 @@
package controlplanestore
import "github.com/samcharles93/archie-core/internal/config"
// CredentialBindingsKind is the resource mapping Kit credential service
// names to org secrets. Applied live on each launch.
const CredentialBindingsKind = "credential-bindings"
// credentialBinding is one config.CredentialBinding as the document writes
// it: explicit snake_case json tags, following channel_settings.go /
// container_settings.go's precedent, never the internal config struct
// (which has no json tags and would fall back to Go field names).
type credentialBinding struct {
Service string `json:"service"`
Org string `json:"org,omitempty"`
Secret credentialValue `json:"secret"`
}
// credentialValue is config.SecretRef as this document writes it.
type credentialValue struct {
Engine string `json:"engine,omitempty"`
Key string `json:"key,omitempty"`
}
func credentialBindingsDefinition() Definition {
return Definition{
Kind: CredentialBindingsKind,
Title: "Credential bindings",
ApplyMode: "live",
Document: []credentialBinding{},
Seed: seedCredentialBindings,
Validate: validateCredentialBindings,
}
}
func seedCredentialBindings(cfg config.Config) any {
return credentialBindingsDocument(cfg.Containers.Credentials)
}
func credentialBindingsDocument(bindings []config.CredentialBinding) []credentialBinding {
if bindings == nil {
return nil
}
out := make([]credentialBinding, len(bindings))
for i, b := range bindings {
out[i] = credentialBinding{Service: b.Service, Org: b.Org, Secret: credentialValue{Engine: b.Secret.Engine, Key: b.Secret.Key}}
}
return out
}
// credentialBindingsSettings reverses credentialBindingsDocument, for the
// layering in runtime_config.go and for validation against
// config.ContainerConfig.ValidateCredentialBindings.
func credentialBindingsSettings(bindings []credentialBinding) []config.CredentialBinding {
if bindings == nil {
return nil
}
out := make([]config.CredentialBinding, len(bindings))
for i, b := range bindings {
out[i] = config.CredentialBinding{Service: b.Service, Org: b.Org, Secret: config.SecretRef{Engine: b.Secret.Engine, Key: b.Secret.Key}}
}
return out
}
func validateCredentialBindings(input []byte) error {
// The rules live in the config package and are shared with the file
// document's own validation (config.ContainerConfig.ValidateCredentialBindings):
// which bindings are valid cannot differ between the file that seeds this
// resource and the resource that replaces it.
return validateAs(input, func(bindings []credentialBinding) error {
return config.ContainerConfig{Credentials: credentialBindingsSettings(bindings)}.ValidateCredentialBindings()
})
}
@@ -0,0 +1,70 @@
package controlplanestore
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
const CuratorsKind = "curators"
func curatorDefinition() Definition {
return Definition{
Kind: CuratorsKind, Title: "Curators", Document: []config.CuratorDefinition{}, ApplyMode: "live",
Seed: func(cfg config.Config) any { return cfg.Curators },
Validate: func(input []byte) error {
return validateAs(input, func(defs []config.CuratorDefinition) error {
names := map[string]bool{"skill": true, "session-memory": true}
for _, def := range defs {
if strings.TrimSpace(def.Name) == "" || names[def.Name] {
return fmt.Errorf("curator name %q is empty, reserved or repeated", def.Name)
}
names[def.Name] = true
if def.Interval <= 0 {
return fmt.Errorf("curator %s: interval must be positive", def.Name)
}
if err := CuratorDefinition(def).Manifest.Validate(); err != nil {
return fmt.Errorf("curator %s: %w", def.Name, err)
}
}
return nil
})
},
}
}
func CuratorDefinition(def config.CuratorDefinition) curator.Definition {
return curator.Definition{Name: def.Name, Enabled: def.Enabled == nil || *def.Enabled, Instructions: def.Instructions, Manifest: curator.Manifest{
Interval: def.Interval.Std(), Cooldown: def.Cooldown.Std(), OnInput: def.OnInput, Tools: def.Tools, Skills: def.Skills, MemoryEngine: def.MemoryEngine, Conversations: def.Conversations, Model: def.Model,
}}
}
func (c *Client) Curators(ctx context.Context) ([]config.CuratorDefinition, int64, error) {
var defs []config.CuratorDefinition
version, _, err := c.Query(ctx, CuratorsKind, func(value []byte) error { return json.Unmarshal(value, &defs) })
return defs, version, err
}
type AppliedCurators struct {
Definitions []config.CuratorDefinition
Version int64
Err error
}
func (c *Client) WatchCurators(ctx context.Context, after int64) (<-chan AppliedCurators, error) {
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: CuratorsKind, AfterVersion: after})
if err != nil {
return nil, controlplanerpc.ClientError(err)
}
return watchUpdates(ctx, stream, func(resource *pb.Resource) AppliedCurators {
update := AppliedCurators{Version: resource.Version}
update.Err = json.Unmarshal(resource.ValueJson, &update.Definitions)
return update
}, func(err error) AppliedCurators { return AppliedCurators{Err: err} }), nil
}
@@ -0,0 +1,24 @@
package controlplanestore
import (
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// Schemas are not declared here: each Definition names its document type, and
// Definition.Descriptor derives the JSON Schema from it (internal/infrastructure/controlplanestore/schema.go).
func builtinDefinitions(steps workflow.StepRegistry, settings map[string]any) []Definition {
definitions := []Definition{taskPolicyDefinition(), workflowDefinition(), workflowDefinitionsDefinition(steps, settings), workflowDraftsDefinition(), workflowEnablementDefinition(), curatorDefinition(), soulDefinition(), scheduleDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), orgModelPolicyDefinition(), forgeConnectionsDefinition()}
definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...)
return definitions
}
func domainManagedDescriptors() []*pb.ResourceDescriptor {
return []*pb.ResourceDescriptor{
{Kind: "identities", Title: "Identities", ApplyMode: "domain-managed", QueryService: "state.v1.IdentityService/ListIdentities,GetIdentity", CommandService: "state.v1.IdentityService/CreateIdentity,RenameIdentity,SuspendIdentity,ReactivateIdentity,RetireIdentity"},
{Kind: "capture-events", Title: "Captured events", ApplyMode: "domain-managed", QueryService: "state.v1.CaptureService/StreamCaptures", CommandService: "state.v1.CaptureService/InsertCapture"},
{Kind: "capture-mappings", Title: "Capture mappings", ApplyMode: "domain-managed", QueryService: "state.v1.MappingService/ListMappings", CommandService: "state.v1.MappingService/InsertMapping,UpdateMapping,DeleteMapping"},
{Kind: "capture-bindings", Title: "Capture bindings", ApplyMode: "domain-managed", QueryService: "state.v1.BindingService/ListBindings", CommandService: "state.v1.BindingService/InsertBinding,UpdateBinding,DeleteBinding"},
}
}
@@ -0,0 +1,75 @@
package controlplanestore
import (
"context"
"testing"
"github.com/samcharles93/archie-core/internal/config"
)
// stubResources answers one kind and reports every other as absent, which is
// the shape a boot sees for a kind nothing has been stored for.
type stubResources map[string][]byte
func (s stubResources) Query(_ context.Context, kind string, decode func([]byte) error) (int64, bool, error) {
value, ok := s[kind]
if !ok {
return 0, false, nil
}
return 1, true, decode(value)
}
// TestForgeLayeringReadsTheConnection pins where the instance's forge comes
// from and what a missing connection means. The file's [forge] is only the
// seed: once the resource holds a document, that document is the forge, and a
// document without a root connection disables it rather than falling back to
// the file's credential -- which the operator may have withdrawn.
func TestForgeLayeringReadsTheConnection(t *testing.T) {
base := config.Config{
Forge: config.Forge{
Type: "github", Host: "file.example.com",
Token: config.SecretRef{Engine: "env", Key: "FILE_TOKEN"},
Intake: config.ForgeIntakeBoth,
WebhookSecret: config.SecretRef{Engine: "env", Key: "HOOK"},
},
}
tests := []struct {
name string
connections string
wantType string
wantHost string
wantKey string
wantWebhookKept bool
}{
{
name: "the root connection replaces the file's forge",
connections: `[{"id":"default","name":"Instance","type":"gitea","host":"gitea.example.com","token":{"engine":"vault","key":"forge/root"}}]`,
wantType: "gitea",
wantHost: "gitea.example.com",
wantKey: "forge/root",
wantWebhookKept: true,
},
{
name: "a document with no root connection disables the forge",
connections: `[{"id":"acme","name":"Acme","type":"github","host":"github.com"}]`,
wantType: "",
wantHost: "",
wantKey: "",
wantWebhookKept: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg, _, err := runtimeConfigFrom(t.Context(), stubResources{ForgeConnectionsKind: []byte(tt.connections)}, base)
if err != nil {
t.Fatalf("layer: %v", err)
}
if cfg.Forge.Type != tt.wantType || cfg.Forge.Host != tt.wantHost || cfg.Forge.Token.Key != tt.wantKey {
t.Fatalf("forge = %+v, want type %q host %q key %q", cfg.Forge, tt.wantType, tt.wantHost, tt.wantKey)
}
if kept := cfg.Forge.WebhookSecret.Key == "HOOK" && cfg.Forge.Intake == config.ForgeIntakeBoth; kept != tt.wantWebhookKept {
t.Fatalf("webhook intake/secret = %q/%q, want them kept from the file", cfg.Forge.Intake, cfg.Forge.WebhookSecret.Key)
}
})
}
}
@@ -0,0 +1,141 @@
package controlplanestore
import (
"fmt"
"maps"
"net/url"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/config"
)
// ForgeConnectionsKind is the resource holding an organisation's external
// forge connections. Its document is []config.ForgeConnection, the same shape
// the runtime resolves, so a stored connection and a resolved one cannot
// disagree about what a connection is.
const ForgeConnectionsKind = "forge-connections"
// rootConnectionID names the connection the file's [forge] section migrates
// into: the instance root's own account, used by root tasks.
const rootConnectionID = "default"
func forgeConnectionsDefinition() Definition {
return Definition{
Kind: ForgeConnectionsKind,
Title: "Forge connections",
ApplyMode: "live",
Document: []config.ForgeConnection{},
Seed: seedForgeConnections,
Validate: validateForgeConnections,
}
}
// seedForgeConnections migrates the file's [forge] into the root connection.
// It grants no execution identity a permit, so the migration neither widens
// nor narrows access. The file never recorded
// which external account a credential belongs to, so Account is seeded empty
// and is filled by a verification.
func seedForgeConnections(cfg config.Config) any {
out := []config.ForgeConnection{}
if c, ok := connectionFromForge(rootConnectionID, connectionDisplayName(cfg.Forge), cfg.Forge); ok {
// Root tasks act as the instance, not as an organisation execution
// identity, so they take this connection without a permit entry. An
// execution identity needs one, and the file granted it none.
out = append(out, c)
}
return out
}
// connectionDisplayName is the label an operator sees, so it names the thing
// that tells one connection from another -- the host it points at -- rather
// than the archie concept it was migrated from. The file never named the
// forge, so there is nothing better to carry over.
func connectionDisplayName(cfg config.Forge) string {
host := strings.TrimSpace(cfg.Host)
if u, err := url.Parse(host); err == nil && u.Hostname() != "" {
host = u.Hostname()
}
if host != "" {
return host
}
return strings.TrimSpace(cfg.Type)
}
// connectionFromForge reads one file forge section as a connection. A forge
// with no type is not configured and seeds nothing.
func connectionFromForge(id, name string, cfg config.Forge) (config.ForgeConnection, bool) {
if strings.TrimSpace(cfg.Type) == "" {
return config.ForgeConnection{}, false
}
return config.ForgeConnection{
ID: id, Name: name, Type: cfg.Type, Host: cfg.Host, Token: cfg.Token,
}, true
}
// rootConnection is the connection an instance's own tasks act through: the
// one the file's [forge] section migrated into.
func rootConnection(connections []config.ForgeConnection) (config.ForgeConnection, bool) {
for _, c := range connections {
if c.ID == rootConnectionID {
return c, true
}
}
return config.ForgeConnection{}, false
}
func validateForgeConnections(input []byte) error {
return validateAs(input, func(connections []config.ForgeConnection) error {
seen := make(map[string]struct{}, len(connections))
for _, c := range connections {
if err := validateForgeConnection(c); err != nil {
return err
}
if _, dup := seen[c.ID]; dup {
return fmt.Errorf("duplicate connection %q", c.ID)
}
seen[c.ID] = struct{}{}
}
return nil
})
}
func validateForgeConnection(c config.ForgeConnection) error {
// A slash would let an ID spell another resource's audit record key, the
// same reason resource keys refuse one.
if strings.TrimSpace(c.ID) == "" || strings.Contains(c.ID, "/") {
return fmt.Errorf("connection ID is required and may not contain %q", "/")
}
if strings.TrimSpace(c.Name) == "" {
return fmt.Errorf("connection %q needs a name", c.ID)
}
if strings.TrimSpace(c.Type) == "" {
return fmt.Errorf("connection %q needs a forge type", c.ID)
}
if strings.TrimSpace(c.Host) == "" {
return fmt.Errorf("connection %q needs a host", c.ID)
}
if (c.Token.Engine == "") != (c.Token.Key == "") {
return fmt.Errorf("connection %q: the credential reference needs both an engine and a key", c.ID)
}
for _, id := range slices.Sorted(maps.Keys(c.Permits)) {
operations := c.Permits[id]
if strings.TrimSpace(id) == "" {
return fmt.Errorf("connection %q: a permitted identity is empty", c.ID)
}
if len(operations) == 0 {
return fmt.Errorf("connection %q: identity %s is permitted nothing; remove the entry instead", c.ID, id)
}
seen := make(map[string]struct{}, len(operations))
for _, op := range operations {
if !config.ValidOperation(op) {
return fmt.Errorf("connection %q: identity %s: unknown operation %q (want clone, push or pr)", c.ID, id, op)
}
if _, dup := seen[op]; dup {
return fmt.Errorf("connection %q: identity %s lists %q twice", c.ID, id, op)
}
seen[op] = struct{}{}
}
}
return nil
}
@@ -0,0 +1,114 @@
package controlplanestore
import (
"encoding/json"
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/config"
)
func TestForgeConnectionValidation(t *testing.T) {
tests := []struct {
name string
doc string
refused bool
}{
{
name: "a host, a credential reference and a permitted operation",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com","token":{"engine":"env","key":"GH_TOKEN"},"permits":{"bot-1":["clone","push"]}}]`,
},
{
name: "a connection with no external account is still configurable",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com"}]`,
},
{
name: "no host",
doc: `[{"id":"gh","name":"GitHub","type":"github"}]`,
refused: true,
},
{
name: "no forge type",
doc: `[{"id":"gh","name":"GitHub","host":"github.com"}]`,
refused: true,
},
{
name: "an ID that would spell another record key",
doc: `[{"id":"org-sys/gh","name":"GitHub","type":"github","host":"github.com"}]`,
refused: true,
},
{
name: "two connections claiming one ID",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com"},{"id":"gh","name":"Other","type":"gitea","host":"gitea.example.com"}]`,
refused: true,
},
{
name: "half a credential reference",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com","token":{"key":"GH_TOKEN"}}]`,
refused: true,
},
{
name: "an operation the runtime cannot perform",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com","permits":{"bot-1":["clone","admin"]}}]`,
refused: true,
},
{
name: "the same operation twice",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com","permits":{"bot-1":["push","push"]}}]`,
refused: true,
},
{
name: "an identity permitted nothing",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com","permits":{"bot-1":[]}}]`,
refused: true,
},
{
name: "a connection with no name",
doc: `[{"id":"gh","type":"github","host":"github.com"}]`,
refused: true,
},
{
name: "a document that names a field the connection does not have",
doc: `[{"id":"gh","name":"GitHub","type":"github","host":"github.com","token_value":"ghp_literal"}]`,
refused: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := forgeConnectionsDefinition().Validate([]byte(tt.doc))
if refused := errors.Is(err, ErrValidation) || err != nil; refused != tt.refused {
t.Fatalf("refused = %v, want %v (err %v)", refused, tt.refused, err)
}
})
}
}
// TestConnectionMigrationKeepsTheFilesGrants is the migration's security
// claim: the root connection takes no permit entry, so no execution identity
// reaches it.
func TestConnectionMigrationKeepsTheFilesGrants(t *testing.T) {
cfg := config.Config{
Forge: config.Forge{Type: "github", Host: "github.com", Token: config.SecretRef{Engine: "env", Key: "ROOT_TOKEN"}},
}
seeded, err := forgeConnectionsDefinition().seededValue(cfg)
if err != nil {
t.Fatalf("seed: %v", err)
}
var connections []config.ForgeConnection
if err := json.Unmarshal(seeded, &connections); err != nil {
t.Fatalf("decode seed: %v", err)
}
if len(connections) != 1 {
t.Fatalf("seeded %d connections, want the root's alone: %+v", len(connections), connections)
}
root := connections[0]
if root.ID != rootConnectionID || len(root.Permits) != 0 {
t.Fatalf("root connection = %+v, want the root's forge and no permitted execution identity", root)
}
if root.Name != "github.com" {
t.Fatalf("root connection name = %q, want the host an operator recognises, not an internal label", root.Name)
}
if root.Token.Key != "ROOT_TOKEN" {
t.Fatalf("root connection credential = %+v, want the file's reference", root.Token)
}
}
@@ -0,0 +1,100 @@
package controlplanestore
import (
"context"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// IdentityGrantsKind is the resource naming the credential services each
// identity may use. Applied live on each launch.
const IdentityGrantsKind = "identity-grants"
// identityGrants is the document: the root identity's services, and per named
// identity a list that replaces the root's. An identity with no entry
// inherits the root's; an empty list grants none.
type identityGrants struct {
Root []string `json:"root"`
Identities map[string][]string `json:"identities,omitempty"`
}
func identityGrantsDefinition() Definition {
return Definition{
Kind: IdentityGrantsKind,
Title: "Identity grants",
ApplyMode: "live",
Document: identityGrants{},
Seed: seedIdentityGrants,
Validate: validateIdentityGrants,
}
}
func seedIdentityGrants(cfg config.Config) any {
doc := identityGrants{Root: cfg.GrantedCredentials, Identities: map[string][]string{}}
for _, id := range cfg.Identities {
if id.GrantedCredentials != nil {
doc.Identities[id.Name] = *id.GrantedCredentials
}
}
return doc
}
func validateIdentityGrants(input []byte) error {
return validateAs(input, func(doc identityGrants) error {
if err := validServices("root", doc.Root); err != nil {
return err
}
for name, services := range doc.Identities {
if strings.TrimSpace(name) == "" {
return fmt.Errorf("identity grants: an identity name is empty")
}
if err := validServices(name, services); err != nil {
return err
}
}
return nil
})
}
func validServices(owner string, services []string) error {
seen := make(map[string]bool, len(services))
for _, service := range services {
if strings.TrimSpace(service) == "" || seen[service] {
return fmt.Errorf("identity grants for %s: services must be non-empty and listed once", owner)
}
seen[service] = true
}
return nil
}
// layerCredentials layers the credential bindings and the identity grants:
// each is its own resource, applies without a restart, and a stored value
// replaces the file's outright.
func layerCredentials(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, out *config.Config) error {
if err := layerResource(ctx, reader, versions, CredentialBindingsKind, func(bindings []credentialBinding) error {
out.Containers.Credentials = credentialBindingsSettings(bindings)
return nil
}); err != nil {
return err
}
return layerResource(ctx, reader, versions, IdentityGrantsKind, func(doc identityGrants) error {
applyIdentityGrants(out, doc)
return nil
})
}
// applyIdentityGrants replaces every identity's grants with the document's.
func applyIdentityGrants(out *config.Config, doc identityGrants) {
out.GrantedCredentials = doc.Root
out.IdentityGrants = doc.Identities
for i := range out.Identities {
if services, ok := doc.Identities[out.Identities[i].Name]; ok {
out.Identities[i].GrantedCredentials = &services
} else {
out.Identities[i].GrantedCredentials = nil
}
}
}
@@ -0,0 +1,46 @@
package controlplanestore
import (
"slices"
"testing"
"github.com/samcharles93/archie-core/internal/config"
)
// TestIdentityGrantsReplaceTheFiles pins that the stored grants replace the
// file's: a listed identity gets exactly its list, an unlisted one is left to
// inherit the root's (nil), and an empty list grants nothing.
func TestIdentityGrantsReplaceTheFiles(t *testing.T) {
fileList := []string{"from-file"}
cfg := config.Config{
GrantedCredentials: []string{"file-root"},
Identities: []config.IdentityConfig{
{Name: "listed", GrantedCredentials: &fileList},
{Name: "unlisted", GrantedCredentials: &fileList},
{Name: "none"},
},
}
applyIdentityGrants(&cfg, identityGrants{
Root: []string{"github"},
Identities: map[string][]string{"listed": {"anthropic"}, "none": {}},
})
if !slices.Equal(cfg.GrantedCredentials, []string{"github"}) {
t.Fatalf("root granted %v", cfg.GrantedCredentials)
}
tests := []struct {
identity string
want []string // nil means inherit the root
}{
{"listed", []string{"anthropic"}},
{"unlisted", nil},
{"none", []string{}},
}
for i, tt := range tests {
t.Run(tt.identity, func(t *testing.T) {
got := cfg.Identities[i].GrantedCredentials
if (got == nil) != (tt.want == nil) || (got != nil && !slices.Equal(*got, tt.want)) {
t.Fatalf("granted %v, want %v", got, tt.want)
}
})
}
}
@@ -0,0 +1,68 @@
package controlplanestore
import (
"errors"
"testing"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
func TestInstanceOnlyKindsRefuseOtherOrgs(t *testing.T) {
tests := []struct {
name, org, kind string
refused bool
}{
{"another org writes an instance setting", "acme", ToolSettingsKind, true},
{"the system org writes an instance setting", storecontract.DefaultOrgID, ToolSettingsKind, false},
{"another org writes an org-scoped kind", "acme", SoulKind, false},
{"another org writes a forge connection", "acme", ForgeConnectionsKind, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := (&Server{}).checkOrgWrite(t.Context(), tt.org, tt.kind, []byte(`{}`))
if refused := errors.Is(err, ErrValidation); refused != tt.refused {
t.Fatalf("refused = %v, want %v (err %v)", refused, tt.refused, err)
}
})
}
}
// TestCatalogHidesInstanceOnlyKinds pins what the catalog advertises: the
// system org sees an instance setting, another org does not (its write would
// be refused), and an org-scoped kind stays visible to both.
func TestCatalogHidesInstanceOnlyKinds(t *testing.T) {
server := &Server{ordered: []Definition{
{Kind: AuditRetentionKind, Title: "Audit retention"},
{Kind: SoulKind, Title: "Soul"},
}}
tests := []struct {
name string
org org.OrgID
wantRetention bool
wantOrgResource bool
}{
{"system org sees the instance setting", org.DefaultOrgID, true, true},
{"another org does not", "acme", false, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := org.WithOrg(t.Context(), tt.org)
catalog, err := server.Catalog(ctx, &pb.CatalogRequest{})
if err != nil {
t.Fatalf("Catalog() error = %v", err)
}
visible := make(map[string]bool, len(catalog.GetResources()))
for _, descriptor := range catalog.GetResources() {
visible[descriptor.GetKind()] = true
}
if got := visible[AuditRetentionKind]; got != tt.wantRetention {
t.Fatalf("%s visible = %v, want %v", AuditRetentionKind, got, tt.wantRetention)
}
if got := visible[SoulKind]; got != tt.wantOrgResource {
t.Fatalf("%s visible = %v, want %v", SoulKind, got, tt.wantOrgResource)
}
})
}
}
@@ -0,0 +1,25 @@
package controlplanestore
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// InstructionsFor returns the system org's instructions and orgID's own.
// A system-org caller has no separate organisation layer.
func (s *Server) InstructionsFor(ctx context.Context, orgID string) (instance, organisation string, err error) {
var system agent.Soul
if err := s.readResource(ctx, storecontract.DefaultOrgID, SoulKind, &system); err != nil {
return "", "", err
}
if orgID == "" || orgID == storecontract.DefaultOrgID {
return system.Text, "", nil
}
var own agent.Soul
if err := s.readResource(ctx, orgID, SoulKind, &own); err != nil {
return "", "", err
}
return system.Text, own.Text, nil
}
@@ -0,0 +1,83 @@
package controlplanestore
import (
"fmt"
"net/url"
"regexp"
"strings"
"github.com/samcharles93/archie-core/internal/config"
)
const (
ProviderSettingsKind = "provider-settings"
ModelAliasesKind = "model-aliases"
)
var bootDerivedProviderEnv = regexp.MustCompile(`^ARCHIE_PROVIDER_[0-9A-F]{16}_API_KEY$`)
type providerDocument struct {
Class string `json:"class"`
APIKeyEnv string `json:"api_key_env,omitempty"`
APIKey config.SecretRef `json:"api_key_ref"`
BaseURL string `json:"base_url,omitempty"`
HasCredential bool `json:"has_credential"`
}
func modelDefinitions() []Definition {
return []Definition{
{Kind: ProviderSettingsKind, Title: "Providers", ApplyMode: "live", Document: map[string]providerDocument{}, Seed: seedProviders, Validate: validateProviders},
{Kind: ModelAliasesKind, Title: "Model aliases", ApplyMode: "live", Document: map[string]string{}, Seed: func(cfg config.Config) any { return cfg.Models }, Validate: validateModelAliases},
}
}
func seedProviders(cfg config.Config) any {
out := make(map[string]providerDocument, len(cfg.Providers))
for name, provider := range cfg.Providers {
out[name] = providerDocument{Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, APIKey: provider.APIKey, BaseURL: provider.BaseURL, HasCredential: provider.APIKeyEnv != "" || provider.APIKey != (config.SecretRef{})}
}
return out
}
func validateProviders(input []byte) error {
return validateAs(input, func(providers map[string]providerDocument) error {
for name, provider := range providers {
if err := rejectBootDerivedProviderEnv(name, provider); err != nil {
return err
}
if strings.TrimSpace(name) == "" || strings.TrimSpace(provider.Class) == "" {
return fmt.Errorf("provider name and class are required")
}
if provider.BaseURL != "" {
parsed, err := url.Parse(provider.BaseURL)
if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
return fmt.Errorf("provider %q has invalid base_url", name)
}
}
}
return nil
})
}
func rejectBootDerivedProviderEnv(name string, provider providerDocument) error {
if bootDerivedProviderEnv.MatchString(provider.APIKeyEnv) && provider.APIKey == (config.SecretRef{}) {
return fmt.Errorf("provider %q api_key_env %q is a boot-derived name; replace provider-settings with the operator's api_key_ref", name, provider.APIKeyEnv)
}
return nil
}
var modelAliasName = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]*$`)
func validateModelAliases(input []byte) error {
return validateAs(input, func(models map[string]string) error {
for alias, model := range models {
if !modelAliasName.MatchString(alias) {
return fmt.Errorf("model alias %q must be lowercase letters, digits, '.', '_' or '-'", alias)
}
if provider, name, ok := strings.Cut(model, "/"); !ok || provider == "" || name == "" {
return fmt.Errorf("model alias %q must reference provider/model", alias)
}
}
return nil
})
}
@@ -0,0 +1,135 @@
package controlplanestore
import (
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
"github.com/samcharles93/archie-core/internal/releaseupdate"
)
const (
RepositoryPoliciesKind = "repository-policies"
SchedulingPolicyKind = "scheduling-policy"
ToolSettingsKind = "tool-settings"
PluginSettingsKind = "plugin-settings"
ContainerRuntimePoliciesKind = "container-runtime-policies"
ExtensionSettingsKind = controlplanerpc.ExtensionSettingsKind
UpdateSettingsKind = controlplanerpc.UpdateSettingsKind
)
type schedulingPolicy struct {
PollInterval string `json:"poll_interval"`
MaxRetries int `json:"max_retries"`
// Label is the dispatch trigger label. Nil keeps the file's label.
Label *string `json:"label,omitempty"`
Dispatch config.Dispatch `json:"dispatch"`
}
type pluginSettings struct {
SkillsDir string `json:"skills_dir"`
}
func operationalDefinitions() []Definition {
return []Definition{
{Kind: RepositoryPoliciesKind, Title: "Repository policies", ApplyMode: "live", Document: []config.Repo{}, Seed: func(cfg config.Config) any { return append([]config.Repo{}, cfg.Repos...) }, Validate: validateRepositories},
// Restart-required: the Messaging Service, which owns the channel
// transports, reconciles them live and archied re-layers each update, but
// the Gateway's chat surfaces (workspace tools, rate limit, model
// catalogs) are boot-built, so a change cannot promise live apply
// everywhere the record reports it.
{Kind: ChannelSettingsKind, Title: "Channel settings", ApplyMode: "restart-required", Document: channelSettings{}, Seed: seedChannels, Validate: validateChannels, Normalize: normalizeChannels},
{Kind: SchedulingPolicyKind, Title: "Scheduling policy", ApplyMode: "live", Document: schedulingPolicy{}, Seed: func(cfg config.Config) any {
return schedulingPolicy{PollInterval: cfg.PollInterval.Std().String(), MaxRetries: cfg.MaxRetries, Label: &cfg.Label, Dispatch: cfg.Dispatch}
}, Validate: validateScheduling},
// Live: changed MCP servers are reconnected, rolling back to the old engine
// if the new one fails to start.
{Kind: ToolSettingsKind, Title: "Tool and MCP settings", ApplyMode: "live", Document: toolSettings{}, Seed: seedTools, Validate: validateTools},
// Restart-required: the one field, skills_dir, is read at boot, and the
// watch refuses a change rather than layering it into the running config
// while the boot-built consumers hold the old value
// (refuseSkillsDirChange).
{Kind: PluginSettingsKind, Title: "Plugin settings", ApplyMode: "restart-required", Document: pluginSettings{}, Seed: func(cfg config.Config) any {
return pluginSettings{cfg.SkillsDir}
}, Validate: validatePluginSettings},
// Live: each process that supervises extensions re-reads this on its sync
// tick, then starts, restarts or stops what changed.
{Kind: ExtensionSettingsKind, Title: "Extension settings", ApplyMode: "live", Document: controlplanerpc.ExtensionSettings{}, Seed: func(config.Config) any { return controlplanerpc.ExtensionSettings{} }, Validate: validateExtensions},
// Live: the container pool reads these on every acquire and the dispatcher
// is resized on publish.
// Live: every check and install reads the channel afresh.
{Kind: UpdateSettingsKind, Title: "Update settings", ApplyMode: "live", Document: controlplanerpc.UpdateSettings{}, Seed: func(config.Config) any { return controlplanerpc.UpdateSettings{Channel: "stable"} }, Validate: validateUpdateSettings},
{Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "live", Document: containerRuntimePolicies{}, Seed: seedContainerPolicies, Validate: validateContainers, Normalize: normalizeContainerPolicies},
// Live: the retention sweep reads the document on every tick, so a
// change applies to the next sweep without a restart.
auditRetentionDefinition(),
}
}
// validateExtensions refuses a blank or repeated extension name: the name is
// the installed package the setting enables.
func validateExtensions(input []byte) error {
return validateAs(input, func(doc controlplanerpc.ExtensionSettings) error {
seen := make(map[string]struct{}, len(doc.Extensions))
for _, setting := range doc.Extensions {
if strings.TrimSpace(setting.Name) == "" {
return fmt.Errorf("extension name is required")
}
if _, dup := seen[setting.Name]; dup {
return fmt.Errorf("extension %q is listed twice", setting.Name)
}
seen[setting.Name] = struct{}{}
}
return nil
})
}
// validatePluginSettings accepts every value.
func validatePluginSettings(input []byte) error {
return validateAs(input, func(pluginSettings) error { return nil })
}
func validateRepositories(input []byte) error {
// The rules live in the configuration package and are shared with the file
// document's own validation (configuration.ValidateRepositories): which
// repository lists are valid cannot differ between the file that seeds this
// resource and the resource that replaces it.
return validateAs(input, configuration.ValidateRepositories)
}
func validateScheduling(input []byte) error {
return validateAs(input, func(policy schedulingPolicy) error {
if policy.MaxRetries < 0 {
return fmt.Errorf("max_retries must not be negative")
}
// A positive interval, not a non-negative one: the file layer's rule is
// the same, and there is no defaulting behind a stored value -- a stored
// "0s" reaches cfg.PollInterval as zero and stops archied starting.
interval, err := time.ParseDuration(policy.PollInterval)
if err != nil || interval <= 0 {
return fmt.Errorf("poll_interval must be a positive duration")
}
// Same reason as the repository rules above: RuntimeConfig replaces
// cfg.Dispatch from this resource, and the daemon refuses to start with a
// trigger it does not know.
if !configuration.DispatchTriggerValid(policy.Dispatch.Trigger) {
return fmt.Errorf("dispatch.trigger %q is not a discovery rule the daemon can poll with", policy.Dispatch.Trigger)
}
// A label-requiring trigger needs a label.
if workintake.RequiresLabel(policy.Dispatch.Trigger) && (policy.Label == nil || *policy.Label == "") {
return fmt.Errorf("label is required when dispatch.trigger is %q (an empty label matches every open issue)", policy.Dispatch.Trigger)
}
return nil
})
}
// validateUpdateSettings refuses a channel the update scripts cannot select.
func validateUpdateSettings(input []byte) error {
return validateAs(input, func(doc controlplanerpc.UpdateSettings) error {
return releaseupdate.ValidateChannel(doc.Channel, doc.Pin)
})
}
@@ -0,0 +1,270 @@
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"strings"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// OrgModelPolicyKind is the instance's per-org model policy. Only the
// system org writes it.
const OrgModelPolicyKind = "org-model-policy"
// orgModelPolicy is what one org may use. An org with no entry may use
// nothing until the instance admin allows it; the system org is never
// restricted.
type orgModelPolicy struct {
// Allowed lists the "provider/model" refs the org may use; "provider/*"
// allows every model of an instance provider.
Allowed []string `json:"allowed"`
// OwnProviders lets the org add providers under its own credentials.
OwnProviders bool `json:"own_providers"`
}
func (p *orgModelPolicy) allows(ref string) bool {
if p == nil {
return false
}
provider, _, _ := strings.Cut(ref, "/")
return slices.Contains(p.Allowed, ref) || slices.Contains(p.Allowed, provider+"/*")
}
func orgModelPolicyDefinition() Definition {
return Definition{
Kind: OrgModelPolicyKind, Title: "Org model policy", ApplyMode: "live",
Document: map[string]orgModelPolicy{},
Seed: func(config.Config) any { return map[string]orgModelPolicy{} },
Validate: func(input []byte) error {
return validateAs(input, func(policies map[string]orgModelPolicy) error {
for orgID, policy := range policies {
if orgID == storecontract.DefaultOrgID {
return fmt.Errorf("the system org uses every instance model; it takes no policy")
}
for _, ref := range policy.Allowed {
if provider, model, ok := strings.Cut(ref, "/"); !ok || provider == "" || model == "" {
return fmt.Errorf("org %q allows %q; use provider/model or provider/*", orgID, ref)
}
}
}
return nil
})
},
}
}
// ModelsFor resolves orgID's effective aliases and its own providers: the
// instance aliases it may use, with its own aliases over them. An alias
// whose model the org may not use is left out, so it fails as unknown.
func (s *Server) ModelsFor(ctx context.Context, orgID string) (config.OrgModels, error) {
instance, err := s.modelAliases(ctx, storecontract.DefaultOrgID)
if err != nil {
return config.OrgModels{}, err
}
if orgID == "" || orgID == storecontract.DefaultOrgID {
// The instance's aliases name the instance's providers, so both
// resolve together: an alias without its provider builds no runtime.
providers, err := s.instanceProviders(ctx)
if err != nil {
return config.OrgModels{}, err
}
return config.OrgModels{Org: orgID, Aliases: instance, Providers: providers}, nil
}
policy, err := s.orgPolicy(ctx, orgID)
if err != nil {
return config.OrgModels{}, err
}
providers, err := s.orgProviders(ctx, orgID, policy)
if err != nil {
return config.OrgModels{}, err
}
own, err := s.modelAliases(ctx, orgID)
if err != nil {
return config.OrgModels{}, err
}
aliases := make(map[string]string, len(instance)+len(own))
for alias, ref := range instance {
if policy.allows(ref) {
aliases[alias] = ref
}
}
for alias, ref := range own {
if usable(ref, policy, providers) {
aliases[alias] = ref
} else {
delete(aliases, alias)
}
}
return config.OrgModels{Org: orgID, Aliases: aliases, Providers: providers}, nil
}
func usable(ref string, policy *orgModelPolicy, own map[string]config.Provider) bool {
provider, _, _ := strings.Cut(ref, "/")
if _, ok := own[provider]; ok {
return true
}
return policy.allows(ref)
}
func (s *Server) orgPolicy(ctx context.Context, orgID string) (*orgModelPolicy, error) {
var policies map[string]orgModelPolicy
if err := s.readResource(ctx, storecontract.DefaultOrgID, OrgModelPolicyKind, &policies); err != nil {
return nil, err
}
policy, ok := policies[orgID]
if !ok {
return nil, nil
}
return &policy, nil
}
// instanceProviders is the providers the instance configured, which are the
// ones the system org's aliases name.
func (s *Server) instanceProviders(ctx context.Context) (map[string]config.Provider, error) {
out := map[string]config.Provider{}
return out, s.readProviders(ctx, storecontract.DefaultOrgID, out)
}
// orgProviders is orgID's own providers, empty unless its policy allows them.
func (s *Server) orgProviders(ctx context.Context, orgID string, policy *orgModelPolicy) (map[string]config.Provider, error) {
out := map[string]config.Provider{}
if policy == nil || !policy.OwnProviders {
return out, nil
}
return out, s.readProviders(ctx, orgID, out)
}
// readProviders adds orgID's provider documents to out. The credential
// travels with the provider: without api_key_ref every call it serves is
// unauthenticated.
func (s *Server) readProviders(ctx context.Context, orgID string, out map[string]config.Provider) error {
var docs map[string]providerDocument
if err := s.readResource(ctx, orgID, ProviderSettingsKind, &docs); err != nil {
return err
}
for name, doc := range docs {
out[name] = config.Provider{Class: doc.Class, BaseURL: doc.BaseURL, APIKeyEnv: doc.APIKeyEnv, APIKey: doc.APIKey}
}
return nil
}
func (s *Server) modelAliases(ctx context.Context, orgID string) (map[string]string, error) {
aliases := map[string]string{}
return aliases, s.readResource(ctx, orgID, ModelAliasesKind, &aliases)
}
// readResource decodes orgID's kind into into, leaving it untouched when the
// org has none.
func (s *Server) readResource(ctx context.Context, orgID, kind string, into any) error {
resource, err := s.store.Resource(ctx, orgID, kind)
if errors.Is(err, storecontract.ErrResourceNotFound) {
return nil
}
if err != nil {
return err
}
if err := json.Unmarshal(resource.Value, into); err != nil {
return fmt.Errorf("read %s %s: %w", orgID, kind, err)
}
return nil
}
// instanceOnlyKinds are the kinds the runtime layers from the system org's
// copy alone. Another org's write would be stored and never applied.
var instanceOnlyKinds = map[string]bool{
ChannelSettingsKind: true, SchedulingPolicyKind: true,
TaskPolicyKind: true, ToolSettingsKind: true,
PluginSettingsKind: true, ContainerRuntimePoliciesKind: true, AgentProfileKind: true,
ExtensionSettingsKind: true, UpdateSettingsKind: true, WorkflowExecutionSettingsKind: true,
AuditRetentionKind: true,
}
// checkOrgWrite applies the rules a resource's static validation cannot: the
// policy is the system org's alone, an org's providers need its policy's
// leave and its own credentials, and every alias must name a model the
// writing org may use. Instance settings are refused from any other org.
func (s *Server) checkOrgWrite(ctx context.Context, orgID, kind string, value []byte) error {
if instanceOnlyKinds[kind] && orgID != storecontract.DefaultOrgID {
return fmt.Errorf("%w: %s is an instance setting and only the system org writes it", ErrValidation, kind)
}
switch kind {
case OrgModelPolicyKind:
if orgID != storecontract.DefaultOrgID {
return fmt.Errorf("%w: only the system org sets org model policy", ErrValidation)
}
case ProviderSettingsKind:
if orgID != storecontract.DefaultOrgID {
return s.checkOrgProviders(ctx, orgID, value)
}
case ModelAliasesKind:
return s.checkAliasWrite(ctx, orgID, value)
case WorkflowDefinitionsKind:
return s.checkModelAliases(ctx, orgID, value)
}
return nil
}
func (s *Server) checkOrgProviders(ctx context.Context, orgID string, value []byte) error {
var docs map[string]providerDocument
if err := json.Unmarshal(value, &docs); err != nil {
return err
}
if len(docs) == 0 {
return nil
}
policy, err := s.orgPolicy(ctx, orgID)
if err != nil {
return err
}
if policy == nil || !policy.OwnProviders {
return fmt.Errorf("%w: org %s may not add its own providers (instance Settings > Models > Org access)", ErrValidation, orgID)
}
var instance map[string]providerDocument
if err := s.readResource(ctx, storecontract.DefaultOrgID, ProviderSettingsKind, &instance); err != nil {
return err
}
for name, doc := range docs {
if _, taken := instance[name]; taken {
return fmt.Errorf("%w: provider %q is an instance provider; name yours differently", ErrValidation, name)
}
// The key comes from the org's own credential binding named after
// the provider, never a secret this org could point at elsewhere.
if doc.APIKey != (config.SecretRef{}) {
return fmt.Errorf("%w: provider %q: an org provider takes its key from the org's credential binding named %q, not a secret reference", ErrValidation, name, name)
}
}
return nil
}
func (s *Server) checkAliasWrite(ctx context.Context, orgID string, value []byte) error {
var aliases map[string]string
if err := json.Unmarshal(value, &aliases); err != nil {
return err
}
if orgID == storecontract.DefaultOrgID {
if _, ok := aliases[config.DefaultModelAlias]; !ok && len(aliases) > 0 {
return fmt.Errorf("%w: model alias %q is required", ErrValidation, config.DefaultModelAlias)
}
return nil
}
policy, err := s.orgPolicy(ctx, orgID)
if err != nil {
return err
}
providers, err := s.orgProviders(ctx, orgID, policy)
if err != nil {
return err
}
for _, alias := range slices.Sorted(maps.Keys(aliases)) {
if !usable(aliases[alias], policy, providers) {
return fmt.Errorf("%w: model alias %q: org %s may not use %q", ErrValidation, alias, orgID, aliases[alias])
}
}
return nil
}
@@ -0,0 +1,106 @@
package controlplanestore
import (
"context"
"maps"
"slices"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// resourceStore answers one document per org and kind and reports every other
// key as absent, the shape a settings read sees on an instance that has never
// written it.
type resourceStore map[string]map[string]string
func (s resourceStore) Resource(_ context.Context, orgID, kind string) (storecontract.Resource, error) {
value, ok := s[orgID][kind]
if !ok {
return storecontract.Resource{}, storecontract.ErrResourceNotFound
}
return storecontract.Resource{OrgID: orgID, Kind: kind, Value: []byte(value), Version: 1}, nil
}
func (resourceStore) ListResources(context.Context) ([]storecontract.Resource, error) {
return nil, nil
}
func (resourceStore) ResourceHistory(context.Context, string, string, int) ([]storecontract.Resource, error) {
return nil, nil
}
func (resourceStore) PutResource(context.Context, storecontract.ResourceWrite) (storecontract.Resource, error) {
return storecontract.Resource{}, nil
}
// TestModelsForResolvesTheProvidersItsAliasesName pins what a task builds its
// model runtime from: an alias is a "provider/model" ref, so a provider the
// instance configured has to come back beside the alias that names it --
// otherwise the ref resolves to nothing and no runtime is ever built. The
// instance's credentials are part of the provider: without them every call is
// unauthenticated.
func TestModelsForResolvesTheProvidersItsAliasesName(t *testing.T) {
store := resourceStore{storecontract.DefaultOrgID: {
ProviderSettingsKind: `{
"remote": {"class": "openai-compatible", "base_url": "https://models.example.com/v1", "api_key_ref": {"engine": "vault", "key": "providers/remote"}},
"local": {"class": "ollama", "api_key_env": "LOCAL_KEY"}
}`,
ModelAliasesKind: `{"default": "remote/large", "embedding": "local/embed"}`,
OrgModelPolicyKind: `{"beta": {"own_providers": true}}`,
}, "beta": {
ProviderSettingsKind: `{"own": {"class": "openai-compatible", "base_url": "https://own.example.com/v1", "api_key_ref": {"engine": "vault", "key": "providers/own"}}}`,
ModelAliasesKind: `{"default": "own/large"}`,
}}
tests := []struct {
name string
orgID string
wantAliases []string
wantProviders []string
}{
{name: "the system org holds the instance's aliases and providers", orgID: storecontract.DefaultOrgID, wantAliases: []string{"default", "embedding"}, wantProviders: []string{"local", "remote"}},
{name: "no org named means the system org", orgID: "", wantAliases: []string{"default", "embedding"}, wantProviders: []string{"local", "remote"}},
{name: "an org with no policy takes neither the instance's aliases nor its providers", orgID: "acme"},
{name: "an org allowed its own providers resolves them", orgID: "beta", wantAliases: []string{"default"}, wantProviders: []string{"own"}},
}
server := &Server{store: store}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
models, err := server.ModelsFor(t.Context(), tt.orgID)
if err != nil {
t.Fatalf("models for %q: %v", tt.orgID, err)
}
if got := slices.Sorted(maps.Keys(models.Aliases)); !slices.Equal(got, tt.wantAliases) {
t.Fatalf("aliases = %v, want %v", got, tt.wantAliases)
}
if got := slices.Sorted(maps.Keys(models.Providers)); !slices.Equal(got, tt.wantProviders) {
t.Fatalf("providers = %v, want %v", got, tt.wantProviders)
}
})
}
creds := []struct {
orgID, provider string
want config.SecretRef
}{
{orgID: storecontract.DefaultOrgID, provider: "remote", want: config.SecretRef{Engine: "vault", Key: "providers/remote"}},
{orgID: "beta", provider: "own", want: config.SecretRef{Engine: "vault", Key: "providers/own"}},
}
for _, c := range creds {
models, err := server.ModelsFor(t.Context(), c.orgID)
if err != nil {
t.Fatalf("models for %q: %v", c.orgID, err)
}
if got := models.Providers[c.provider].APIKey; got != c.want {
t.Fatalf("%s provider %s api_key_ref = %+v, want %+v (its only credential)", c.orgID, c.provider, got, c.want)
}
}
models, err := server.ModelsFor(t.Context(), storecontract.DefaultOrgID)
if err != nil {
t.Fatalf("models: %v", err)
}
if got := models.Providers["local"]; got.APIKeyEnv != "LOCAL_KEY" || got.Class != "ollama" {
t.Fatalf("local provider = %+v, want its class and api_key_env", got)
}
}
@@ -0,0 +1,135 @@
package controlplanestore
import (
"context"
"errors"
"fmt"
"slices"
"strconv"
"time"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
)
// projectDocument edits one org resource on behalf of an installed package.
// Each attempt re-reads the stored document and re-applies edit, so an
// operator edit made during the projection is folded in, and only a
// persistently moving document refuses it. edit receives nil for a resource
// the org never wrote.
func projectDocument(ctx context.Context, store ResourceStore, orgID, kind, source, requestPrefix string, edit func(current []byte) ([]byte, error)) error {
requestID := requestPrefix + ":" + strconv.FormatInt(time.Now().UTC().UnixNano(), 36)
for attempt := 0; ; attempt++ {
var current []byte
var version int64
resource, err := store.Resource(ctx, orgID, kind)
switch {
case errors.Is(err, storecontract.ErrResourceNotFound):
case err != nil:
return err
default:
current, version = resource.Value, resource.Version
}
value, err := edit(current)
if err != nil {
return err
}
_, err = store.PutResource(ctx, storecontract.ResourceWrite{
OrgID: orgID, Kind: kind, Value: value, ExpectedVersion: version,
Actor: projectionActor, Source: source, RequestID: requestID,
})
if errors.Is(err, storecontract.ErrResourceVersionConflict) && attempt < projectWriteAttempts-1 {
continue
}
if err != nil {
return fmt.Errorf("write %s: %w", kind, err)
}
return nil
}
}
// listFamily describes a family whose resource is a list of entries with
// stable ids, merged into by installed packages.
type listFamily[E any] struct {
kind, family string
decode func([]byte) ([]E, error)
// encode validates the merged list and returns the document.
encode func([]E) ([]byte, error)
id func(E) string
// parse reads one contributed file into an entry.
parse func(name string, content []byte) (E, error)
}
// listProjector merges an installed package's entries into the org's list
// resource. Ids owned by an operator or another package are refused.
type listProjector[E any] struct {
store ResourceStore
ledger storepkg.ProjectionLedger
listFamily[E]
}
func newListProjector[E any](resources ResourceStore, ledger storepkg.ProjectionLedger, family listFamily[E]) (*listProjector[E], error) {
if resources == nil || ledger == nil {
return nil, fmt.Errorf("control plane: %s projection needs a resource store and a contributions ledger", family.family)
}
return &listProjector[E]{store: resources, ledger: ledger, listFamily: family}, nil
}
func (p *listProjector[E]) Apply(ctx context.Context, orgID, name, digest string, contents map[string][]byte) error {
incoming := make([]E, 0, len(contents))
recorded := make([]storepkg.ProjectionEntry, 0, len(contents))
for contentName, content := range contents {
entry, err := p.parse(contentName, content)
if err != nil {
return fmt.Errorf("contributed %s %q: %w", p.family, contentName, err)
}
incoming = append(incoming, entry)
recorded = append(recorded, storepkg.ProjectionEntry{Family: p.family, EntryID: p.id(entry)})
}
err := projectDocument(ctx, p.store, orgID, p.kind, "package:"+name+"@"+digest, "package-project:"+digest, func(current []byte) ([]byte, error) {
entries, err := p.decode(current)
if err != nil {
return nil, err
}
for _, have := range entries {
if slices.ContainsFunc(incoming, func(in E) bool { return p.id(in) == p.id(have) }) {
return nil, fmt.Errorf("package %q: %w: %s %q", name, storepkg.ErrContributionCollision, p.family, p.id(have))
}
}
return p.encode(append(entries, incoming...))
})
if err != nil {
return err
}
if err := p.ledger.Record(ctx, orgID, name, recorded); err != nil {
return fmt.Errorf("record contributions of %q: %w", name, err)
}
return nil
}
func (p *listProjector[E]) Withdraw(ctx context.Context, orgID, name, digest string) error {
recorded, err := p.ledger.Entries(ctx, orgID, name)
if err != nil {
return fmt.Errorf("entries of package %q: %w", name, err)
}
var withdrawn []string
for _, entry := range recorded {
if entry.Family == p.family {
withdrawn = append(withdrawn, entry.EntryID)
}
}
if len(withdrawn) == 0 {
return nil
}
err = projectDocument(ctx, p.store, orgID, p.kind, "package-withdraw:"+name+"@"+digest, "package-withdraw:"+digest, func(current []byte) ([]byte, error) {
entries, err := p.decode(current)
if err != nil {
return nil, err
}
return p.encode(slices.DeleteFunc(entries, func(e E) bool { return slices.Contains(withdrawn, p.id(e)) }))
})
if err != nil {
return err
}
return p.ledger.Forget(ctx, orgID, name, p.family)
}
@@ -0,0 +1,99 @@
package controlplanestore
import (
"encoding/json"
"fmt"
"path"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/eda/module"
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
)
// PlaybooksKind is the control-plane resource holding the org's EDA playbook
// documents.
const PlaybooksKind = "eda-playbooks"
// PlaybookCollection is the eda-playbooks document: playbook sources under
// their stable ids.
type PlaybookCollection struct {
Playbooks []PlaybookEntry `json:"playbooks"`
}
type PlaybookEntry struct {
ID string `json:"id"`
YAML string `json:"yaml"`
}
func playbooksDefinition() Definition {
return Definition{
Kind: PlaybooksKind,
Title: "EDA playbooks",
Document: PlaybookCollection{},
ApplyMode: "live",
Seed: func(config.Config) any { return PlaybookCollection{Playbooks: []PlaybookEntry{}} },
Validate: func(input []byte) error {
return validateAs(input, func(c PlaybookCollection) error {
_, err := CompilePlaybooks(c)
return err
})
},
}
}
// CompilePlaybooks compiles a collection against the module vocabulary. Any
// invalid playbook fails the set.
func CompilePlaybooks(c PlaybookCollection) (*playbook.Store, error) {
docs := make([]playbook.Document, 0, len(c.Playbooks))
seen := map[string]bool{}
for _, entry := range c.Playbooks {
if entry.ID == "" || seen[entry.ID] {
return nil, fmt.Errorf("%w: playbook id %q is empty or repeated", ErrValidation, entry.ID)
}
seen[entry.ID] = true
docs = append(docs, playbook.Document{ID: entry.ID, YAML: []byte(entry.YAML)})
}
store, err := playbook.Compile(docs, module.New())
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
return store, nil
}
// NewPlaybookPackageProjector builds the projector for storepkg.FamilyPlaybooks.
func NewPlaybookPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger) (storepkg.FamilyProjector, error) {
return newListProjector(resources, ledger, listFamily[PlaybookEntry]{
kind: PlaybooksKind,
family: storepkg.FamilyPlaybooks,
decode: func(value []byte) ([]PlaybookEntry, error) {
c, err := decodePlaybooks(value)
return c.Playbooks, err
},
encode: func(entries []PlaybookEntry) ([]byte, error) {
return encodePlaybooks(PlaybookCollection{Playbooks: entries})
},
id: func(e PlaybookEntry) string { return e.ID },
parse: func(name string, content []byte) (PlaybookEntry, error) {
return PlaybookEntry{ID: path.Base(name), YAML: string(content)}, nil
},
})
}
func decodePlaybooks(value []byte) (PlaybookCollection, error) {
collection := PlaybookCollection{Playbooks: []PlaybookEntry{}}
if value == nil {
return collection, nil
}
if err := json.Unmarshal(value, &collection); err != nil {
return PlaybookCollection{}, fmt.Errorf("decode %s: %w", PlaybooksKind, err)
}
return collection, nil
}
func encodePlaybooks(collection PlaybookCollection) ([]byte, error) {
if _, err := CompilePlaybooks(collection); err != nil {
return nil, err
}
return json.Marshal(collection)
}
@@ -0,0 +1,114 @@
package controlplanestore
import (
"context"
"encoding/json"
"log/slog"
"sync"
"time"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
const playbookQueryTimeout = 5 * time.Second
// LivePlaybooks serves the daemon the org's eda-playbooks resource. Each call
// reads the resource's version and recompiles only when it moved, so an
// install or an operator edit applies to the next task. A control plane that
// cannot be reached, or a document that no longer compiles, leaves the last
// good set in force.
type LivePlaybooks struct {
rpc pb.ControlPlaneServiceClient
log *slog.Logger
ApplyStatus *applystatus.Reporter
mu sync.Mutex
orgs map[org.OrgID]*orgPlaybooks
}
// orgPlaybooks is one org's compiled set and the version it came from.
type orgPlaybooks struct {
version int64
store *playbook.Store
}
func NewLivePlaybooks(client pb.ControlPlaneServiceClient, log *slog.Logger) *LivePlaybooks {
return &LivePlaybooks{rpc: client, log: log, orgs: map[org.OrgID]*orgPlaybooks{}}
}
// Keep loads the default org's playbooks now and every interval after, so the
// apply status is reported without waiting for the first dispatch.
func (l *LivePlaybooks) Keep(ctx context.Context, interval time.Duration) {
keepLoading(ctx, interval, func() { l.current(ctx) })
}
// keepLoading runs load now and every interval until ctx ends.
func keepLoading(ctx context.Context, interval time.Duration, load func()) {
load()
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
load()
}
}
}()
}
// current reads the playbooks of the org ctx acts in; the query carries that
// org, so a task is matched against its own org's document.
func (l *LivePlaybooks) current(ctx context.Context) *playbook.Store {
l.mu.Lock()
defer l.mu.Unlock()
id := org.OrgFromContext(ctx)
held := l.orgs[id]
if held == nil {
held = &orgPlaybooks{}
l.orgs[id] = held
}
ctx, cancel := context.WithTimeout(ctx, playbookQueryTimeout)
defer cancel()
response, err := l.rpc.Query(ctx, &pb.QueryRequest{Kind: PlaybooksKind})
if err != nil {
l.ApplyStatus.Report(ctx, PlaybooksKind, 0, err)
l.log.Warn("eda playbooks unavailable; keeping the last good set", "err", controlplanerpc.ClientError(err))
return held.store
}
if held.store != nil && response.Resource.Version == held.version {
l.ApplyStatus.Report(ctx, PlaybooksKind, held.version, nil)
return held.store
}
var collection PlaybookCollection
if err := json.Unmarshal(response.Resource.ValueJson, &collection); err != nil {
l.ApplyStatus.Report(ctx, PlaybooksKind, response.Resource.Version, err)
l.log.Error("eda playbooks undecodable; keeping the last good set", "err", err)
return held.store
}
store, err := CompilePlaybooks(collection)
if err != nil {
l.ApplyStatus.Report(ctx, PlaybooksKind, response.Resource.Version, err)
l.log.Error("eda playbooks do not compile; keeping the last good set", "err", err)
return held.store
}
held.version, held.store = response.Resource.Version, store
l.ApplyStatus.Report(ctx, PlaybooksKind, held.version, nil)
l.log.Info("eda playbooks loaded", "org", id, "version", held.version, "playbooks", len(store.Playbooks))
return store
}
func (l *LivePlaybooks) Dispatch(ctx context.Context, input playbook.DispatchInput) (playbook.Decision, bool) {
return l.current(ctx).Dispatch(input)
}
func (l *LivePlaybooks) Run(ctx context.Context, ledger storecontract.PlaybookDispatcher, log *slog.Logger, input playbook.DispatchInput) error {
return l.current(ctx).Run(ctx, ledger, log, input)
}
@@ -0,0 +1,133 @@
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
)
// profileFile is one contributed profile: a name and the profile it defines.
// The image is a reference to a published image, never a build.
type profileFile struct {
Name string `yaml:"name"`
Image string `yaml:"image"`
Kit string `yaml:"kit"`
Adapter string `yaml:"adapter"`
Tools []string `yaml:"tools"`
}
// ProfileProjector merges an installed package's agent profiles into the
// org's agent-profiles resource. Names owned by an operator or another
// package are refused.
type ProfileProjector struct {
store ResourceStore
ledger storepkg.ProjectionLedger
}
var _ storepkg.FamilyProjector = (*ProfileProjector)(nil)
func NewProfilePackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger) (*ProfileProjector, error) {
if resources == nil || ledger == nil {
return nil, errors.New("control plane: profile projection needs a resource store and a contributions ledger")
}
return &ProfileProjector{store: resources, ledger: ledger}, nil
}
func (p *ProfileProjector) Apply(ctx context.Context, orgID, name, digest string, contents map[string][]byte) error {
incoming := make(map[string]agentProfile, len(contents))
recorded := make([]storepkg.ProjectionEntry, 0, len(contents))
for contentName, content := range contents {
var file profileFile
if err := yaml.Unmarshal(content, &file); err != nil {
return fmt.Errorf("contributed profile %q: %w", contentName, err)
}
if file.Name == "" {
return fmt.Errorf("contributed profile %q has no name", contentName)
}
incoming[file.Name] = agentProfile{Image: file.Image, Kit: file.Kit, Adapter: file.Adapter, Tools: file.Tools}
recorded = append(recorded, storepkg.ProjectionEntry{Family: storepkg.FamilyProfiles, EntryID: file.Name})
}
err := projectDocument(ctx, p.store, orgID, AgentProfileKind, "package:"+name+"@"+digest, "package-project:"+digest, func(current []byte) ([]byte, error) {
profiles, err := decodeProfiles(current)
if err != nil {
return nil, err
}
for profile, value := range incoming {
if _, taken := profiles[profile]; taken {
return nil, fmt.Errorf("package %q: %w: profile %q", name, storepkg.ErrContributionCollision, profile)
}
profiles[profile] = value
}
return encodeProfiles(profiles)
})
if err != nil {
return err
}
if err := p.ledger.Record(ctx, orgID, name, recorded); err != nil {
return fmt.Errorf("record contributions of %q: %w", name, err)
}
return nil
}
func (p *ProfileProjector) Withdraw(ctx context.Context, orgID, name, digest string) error {
entries, err := p.ledger.Entries(ctx, orgID, name)
if err != nil {
return fmt.Errorf("entries of package %q: %w", name, err)
}
var withdrawn []string
for _, entry := range entries {
if entry.Family == storepkg.FamilyProfiles {
withdrawn = append(withdrawn, entry.EntryID)
}
}
if len(withdrawn) == 0 {
return nil
}
err = projectDocument(ctx, p.store, orgID, AgentProfileKind, "package-withdraw:"+name+"@"+digest, "package-withdraw:"+digest, func(current []byte) ([]byte, error) {
profiles, err := decodeProfiles(current)
if err != nil {
return nil, err
}
for profile := range profiles {
if slices.Contains(withdrawn, profile) {
delete(profiles, profile)
}
}
return encodeProfiles(profiles)
})
if err != nil {
return err
}
return p.ledger.Forget(ctx, orgID, name, storepkg.FamilyProfiles)
}
func decodeProfiles(value []byte) (map[string]agentProfile, error) {
profiles := map[string]agentProfile{}
if value == nil {
return profiles, nil
}
if err := json.Unmarshal(value, &profiles); err != nil {
return nil, fmt.Errorf("decode %s: %w", AgentProfileKind, err)
}
if profiles == nil {
profiles = map[string]agentProfile{}
}
return profiles, nil
}
func encodeProfiles(profiles map[string]agentProfile) ([]byte, error) {
value, err := json.Marshal(profiles)
if err != nil {
return nil, err
}
if err := validateAgentProfiles(value); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
return value, nil
}
@@ -0,0 +1,273 @@
package controlplanestore
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
type Definition struct {
Kind string
Title string
// Document is a zero value of the resource's document type; the JSON Schema
// is derived from it. Nil means no document.
Document any
ApplyMode string
Seed func(config.Config) any
Validate func([]byte) error
Normalize func([]byte) ([]byte, error)
// Defaults is the factory value clients offer as "restore shipped". Only
// resources that ship with content set it.
Defaults func() any
// SchemaExtensions are merged into the derived schema's top level, for
// vocabulary the document type alone cannot express.
SchemaExtensions map[string]any
}
func (d Definition) Descriptor() *pb.ResourceDescriptor {
descriptor := &pb.ResourceDescriptor{Kind: d.Kind, Title: d.Title, SchemaJson: schemaJSON(d.Document, d.SchemaExtensions), Commands: []string{"replace"}, ApplyMode: d.ApplyMode}
if d.Defaults != nil {
if defaults, err := json.Marshal(d.Defaults()); err == nil {
descriptor.DefaultsJson = string(defaults)
}
}
return descriptor
}
func (d Definition) Decode(input []byte) ([]byte, error) {
if !json.Valid(input) {
return nil, fmt.Errorf("%w: invalid JSON", ErrValidation)
}
if err := d.Validate(input); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
if d.Normalize != nil {
normalized, err := d.Normalize(input)
if err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
input = normalized
}
var value any
if err := json.Unmarshal(input, &value); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
encoded, err := json.Marshal(value)
if err != nil {
return nil, fmt.Errorf("encode %s: %w", d.Kind, err)
}
return encoded, nil
}
// SeedSkip records a resource ImportConfig could not seed from the file config,
// and why. It is reported rather than returned as an error: see ImportConfig.
type SeedSkip struct {
Kind string
Err error
}
// seedActor is the audit identity seeds write under.
const (
seedActor = "system:migration"
seedSource = "legacy-config"
)
// ImportConfig seeds every resource the store does not hold and returns the
// version each kind is left at. A stored value is kept, except a shipped
// document the seed itself wrote, which is refreshed. A seed its validator
// refuses is skipped and returned in skipped.
func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[string]int64, []SeedSkip, error) {
versions := make(map[string]int64, len(s.ordered))
var skipped []SeedSkip
for _, definition := range s.ordered {
version, err := s.seedKind(ctx, storecontract.DefaultOrgID, definition, cfg)
var refusal *seedRefusal
switch {
case errors.As(err, &refusal):
skipped = append(skipped, SeedSkip{Kind: definition.Kind, Err: refusal.err})
case err != nil:
return nil, nil, err
default:
versions[definition.Kind] = version
}
}
resources, err := s.store.ListResources(ctx)
if err != nil {
return nil, nil, err
}
for _, resource := range resources {
if resource.OrgID == storecontract.DefaultOrgID || resource.Kind != WorkflowDefinitionsKind {
continue
}
if _, err := s.seedKind(ctx, resource.OrgID, s.definitions[resource.Kind], config.Config{}); err != nil {
return nil, nil, err
}
}
return versions, skipped, nil
}
// seedRefusal is the seed's own validation refusing the value this build
// derived. It is an error because it is one -- there is nothing to write -- and a
// distinct type because ImportConfig answers it by reporting the kind rather
// than failing the boot (see ImportConfig on why a bad seed is not fatal).
type seedRefusal struct{ err error }
func (r *seedRefusal) Error() string { return r.err.Error() }
func (r *seedRefusal) Unwrap() error { return r.err }
// seedKind seeds, refreshes or leaves one kind and returns its version. A
// *seedRefusal means the seed failed validation and nothing was written.
func (s *Server) seedKind(ctx context.Context, orgID string, definition Definition, cfg config.Config) (int64, error) {
stored, storedErr := s.store.Resource(ctx, orgID, definition.Kind)
absent := errors.Is(storedErr, storecontract.ErrResourceNotFound)
if storedErr != nil && !absent {
return 0, storedErr
}
value, err := definition.seededValue(cfg)
if err != nil {
// Skipped, not fatal.
return 0, &seedRefusal{err: err}
}
if !absent && bytes.Equal(stored.Value, value) {
// The store already holds what this build seeds. Comparing the values
// rather than re-writing them is what keeps a boot from adding a
// revision for a document that did not change.
return stored.Version, nil
}
if !absent {
refresh, err := s.shippedValueIsStale(ctx, orgID, definition)
if err != nil {
return 0, err
}
if !refresh {
return stored.Version, nil
}
}
write := storecontract.ResourceWrite{
OrgID: orgID, Kind: definition.Kind, Value: value,
Actor: seedActor, Source: seedSource,
RequestID: seedRequestID(definition.Kind, value),
ExpectedVersion: expectedVersion(stored, absent), At: time.Now().UTC(),
}
resource, err := s.store.PutResource(ctx, write)
if err != nil {
return 0, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
return resource.Version, nil
}
// expectedVersion is the optimistic-concurrency guard a seed writes under: the
// revision it is replacing, or nothing at all for a kind that has none.
func expectedVersion(stored storecontract.Resource, absent bool) int64 {
if absent {
return 0
}
return stored.Version
}
// shippedValueIsStale reports whether the newest stored revision of a
// shipped document was written by the seed.
func (s *Server) shippedValueIsStale(ctx context.Context, orgID string, definition Definition) (bool, error) {
if definition.Defaults == nil {
return false, nil
}
return s.seedWroteNewest(ctx, orgID, definition.Kind)
}
// seedWroteNewest reports whether the newest revision of kind was written by a
// seed. It reads the ledger rather than the current row because the ledger is
// what records who wrote a value, and the row does not.
func (s *Server) seedWroteNewest(ctx context.Context, orgID, kind string) (bool, error) {
history, err := s.store.ResourceHistory(ctx, orgID, kind, 1)
if err != nil {
return false, fmt.Errorf("read %s history: %w", kind, err)
}
if len(history) == 0 {
return false, nil
}
return history[0].Actor == seedActor && history[0].Source == seedSource, nil
}
// seedRequestID is a seed write's idempotency key, derived from the kind and
// value.
func seedRequestID(kind string, value []byte) string {
sum := sha256.Sum256(value)
return "import:" + kind + ":" + hex.EncodeToString(sum[:])
}
// seededValue is the value written for a kind the store does not hold.
func (d Definition) seededValue(cfg config.Config) ([]byte, error) {
value, err := json.Marshal(d.Seed(cfg))
if err != nil {
return nil, fmt.Errorf("seed %s: %w", d.Kind, err)
}
value, err = d.Decode(value)
if err != nil {
return nil, fmt.Errorf("seed %s: %w", d.Kind, err)
}
return value, nil
}
// seededValues is what the State Store would write for every kind, keyed by
// kind.
func (s *Server) seededValues(cfg config.Config) (map[string][]byte, error) {
values := make(map[string][]byte, len(s.ordered))
for _, definition := range s.ordered {
value, err := definition.seededValue(cfg)
if err != nil {
return nil, err
}
values[definition.Kind] = value
}
return values, nil
}
// Owns reports whether kind is a resource the control plane owns, so a caller
// acting on a stored value can refuse a kind nobody defines before it reaches
// the store.
func (s *Server) Owns(kind string) bool {
_, ok := s.definitions[kind]
return ok
}
// ValidateStored decodes every stored resource with its definition and
// returns how many it checked. Errors name the kind and revision.
func (s *Server) ValidateStored(ctx context.Context) (int, error) {
resources, err := s.store.ListResources(ctx)
if err != nil {
return 0, err
}
checked := 0
var failures []error
for _, resource := range resources {
definition, ok := s.definitions[resource.Kind]
if !ok {
continue
}
checked++
if _, err := definition.Decode(resource.Value); err != nil {
failures = append(failures, fmt.Errorf("org %s: %s at version %d: %w", resource.OrgID, definition.Kind, resource.Version, err))
}
}
return checked, errors.Join(failures...)
}
func validateAs[T any](input []byte, validate func(T) error) error {
var value T
decoder := json.NewDecoder(bytes.NewReader(input))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&value); err != nil {
return err
}
return validate(value)
}
@@ -0,0 +1,230 @@
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// resourceReader returns a resource kind's value and version; found is false
// when the store holds none.
// RuntimeConfig layers stored resources over base and returns each kind's
// version.
func (c *Client) RuntimeConfig(ctx context.Context, base config.Config) (config.Config, map[string]int64, error) {
return runtimeConfigFrom(ctx, c, base)
}
// RuntimeChatConfig layers the stored channel settings over the file document's
// chat section.
// StoredRuntimeConfig is RuntimeConfig over this server's own store. Kinds
// not stored are read as their seed.
func (s *Server) StoredRuntimeConfig(ctx context.Context, base config.Config) (config.Config, map[string]int64, error) {
seeds, err := s.seededValues(base)
if err != nil {
return config.Config{}, nil, err
}
return runtimeConfigFrom(ctx, storeReader{resources: s.store, seeds: seeds}, base)
}
// storeReader reads this server's store, returning the seed for kinds it
// does not hold.
type storeReader struct {
resources ResourceStore
seeds map[string][]byte
}
func (r storeReader) Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error) {
resource, err := r.resources.Resource(ctx, storecontract.DefaultOrgID, kind)
if errors.Is(err, storecontract.ErrResourceNotFound) {
seed, ok := r.seeds[kind]
if !ok {
return 0, false, fmt.Errorf("read %s: %w", kind, storecontract.ErrResourceNotFound)
}
if err := decode(seed); err != nil {
return 0, false, fmt.Errorf("decode %s seed: %w", kind, err)
}
// No version: nothing has been stored for this kind, so nothing has
// been applied either. It is still a value to layer in -- the seed --
// which is why this reader never reports the kind absent.
return 0, true, nil
}
if err != nil {
return 0, false, fmt.Errorf("read %s: %w", kind, err)
}
if err := decode(resource.Value); err != nil {
return 0, false, fmt.Errorf("decode %s: %w", kind, err)
}
return resource.Version, true, nil
}
func runtimeConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReader, base config.Config) (config.Config, map[string]int64, error) {
out := base.Clone()
versions := map[string]int64{}
if err := layerResource(ctx, reader, versions, ProviderSettingsKind, func(providers map[string]providerDocument) error {
out.Providers = make(map[string]config.Provider, len(providers))
for name, provider := range providers {
if err := rejectBootDerivedProviderEnv(name, provider); err != nil {
return err
}
out.Providers[name] = config.Provider{Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, APIKey: provider.APIKey, BaseURL: provider.BaseURL}
}
return nil
}); err != nil {
return config.Config{}, nil, err
}
// Stored aliases replace cfg.Models outright.
if err := layerResource(ctx, reader, versions, ModelAliasesKind, func(aliases map[string]string) error {
out.Models = aliases
return nil
}); err != nil {
return config.Config{}, nil, err
}
if err := layerResourceJSON(ctx, reader, versions, RepositoryPoliciesKind, &out.Repos); err != nil {
return config.Config{}, nil, err
}
// The instance's own forge is its root connection: the file's [forge]
// section migrated into that resource, so a connection the operator
// edits or removes is what the daemon reaches the forge with. Intake and
// the webhook secret are instance infrastructure and stay the file's.
if err := layerResource(ctx, reader, versions, ForgeConnectionsKind, func(connections []config.ForgeConnection) error {
forge := out.Forge
forge.Type, forge.Host, forge.Token = "", "", config.SecretRef{}
if connection, ok := rootConnection(connections); ok {
forge.Type, forge.Host, forge.Token = connection.Type, connection.Host, connection.Token
}
out.Forge = forge
return nil
}); err != nil {
return config.Config{}, nil, err
}
chat, chatVersion, err := controlplanerpc.RuntimeChatConfigFrom(ctx, reader, out.Chat)
if err != nil {
return config.Config{}, nil, err
}
out.Chat, versions[ChannelSettingsKind] = chat, chatVersion
if err := layerResource(ctx, reader, versions, SchedulingPolicyKind, func(policy schedulingPolicy) error {
interval, err := time.ParseDuration(policy.PollInterval)
if err != nil {
return err
}
out.PollInterval, out.MaxRetries, out.Dispatch = config.Duration(interval), policy.MaxRetries, policy.Dispatch
// A stored label replaces the file's.
if policy.Label != nil {
out.Label = *policy.Label
}
return nil
}); err != nil {
return config.Config{}, nil, err
}
return runtimeToolConfigFrom(ctx, reader, versions, out)
}
func runtimeToolConfigFrom(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, out config.Config) (config.Config, map[string]int64, error) {
policy := taskPolicyOf(out)
if err := layerResourceJSON(ctx, reader, versions, TaskPolicyKind, &policy); err != nil {
return config.Config{}, nil, err
}
out.Notify = config.Notify{Webhook: policy.NotifyWebhook, MinSeverity: policy.NotifyMinSeverity, Secret: policy.NotifySecret}
if err := layerResource(ctx, reader, versions, ToolSettingsKind, func(settings toolSettings) error {
headers := make(map[string]map[string]string, len(out.Tools.MCPServers))
fileParallelToolCalls := make(map[string]bool, len(out.Tools.MCPServers))
for _, server := range out.Tools.MCPServers {
headers[server.Name] = server.Headers
fileParallelToolCalls[server.Name] = server.ParallelToolCalls
}
servers := make([]config.MCPServer, 0, len(settings.MCPServers))
for _, server := range settings.MCPServers {
// cfg.Tools is replaced wholesale, so keep file-owned fields: headers, and
// ParallelToolCalls when not stored.
parallelToolCalls := fileParallelToolCalls[server.Name]
if server.ParallelToolCalls != nil {
parallelToolCalls = *server.ParallelToolCalls
}
servers = append(servers, config.MCPServer{
Name: server.Name,
Transport: server.Transport,
Command: server.Command,
Args: server.Args,
WorkDir: server.WorkDir,
URL: server.URL,
Headers: headers[server.Name],
SSEEndpoint: server.SSEEndpoint,
MessageEndpoint: server.MessageEndpoint,
ParallelToolCalls: parallelToolCalls,
})
}
out.Tools = config.ToolsConfig{MCPServers: servers, Policy: settings.Policy, WebFetch: settings.WebFetch, Minimax: config.MinimaxConfig{Enabled: settings.Minimax.Enabled, APIKey: settings.Minimax.APIKey, BaseURL: settings.Minimax.BaseURL}}
return nil
}); err != nil {
return config.Config{}, nil, err
}
if err := layerResource(ctx, reader, versions, PluginSettingsKind, func(settings pluginSettings) error {
out.SkillsDir = settings.SkillsDir
return nil
}); err != nil {
return config.Config{}, nil, err
}
if err := layerResource(ctx, reader, versions, ContainerRuntimePoliciesKind, func(policies containerRuntimePolicies) error {
// Keep the file-owned Profiles and RegistryAuth across the replacement.
profiles := out.Containers.Profiles
registryAuth := out.Containers.RegistryAuth
out.Containers = policies.settings()
out.Containers.Profiles = profiles
out.Containers.RegistryAuth = registryAuth
return nil
}); err != nil {
return config.Config{}, nil, err
}
// Stored profiles replace the file's outright.
if err := layerResource(ctx, reader, versions, AgentProfileKind, func(profiles map[string]agentProfile) error {
out.Containers.Profiles = agentProfilesSettings(profiles)
return nil
}); err != nil {
return config.Config{}, nil, err
}
err := layerCredentials(ctx, reader, versions, &out)
return out, versions, err
}
// layerResource decodes a stored JSON resource into a T, applies it and
// records its version. A kind with no stored value is skipped.
func layerResource[T any](ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, kind string, apply func(T) error) error {
return layerRaw(ctx, reader, versions, kind, func(value []byte) error {
var v T
if err := json.Unmarshal(value, &v); err != nil {
return err
}
return apply(v)
})
}
// layerResourceJSON decodes a stored resource over target, keeping fields
// the stored document omits.
func layerResourceJSON(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, kind string, target any) error {
return layerRaw(ctx, reader, versions, kind, func(value []byte) error { return json.Unmarshal(value, target) })
}
func layerRaw(ctx context.Context, reader controlplanerpc.ResourceReader, versions map[string]int64, kind string, decode func([]byte) error) error {
version, found, err := reader.Query(ctx, kind, decode)
if err != nil {
return err
}
if found {
versions[kind] = version
}
return nil
}
// query returns the version of the resource it decoded, so callers that layer
// a resource in can report the version they applied. A kind the store holds no
// value for is reported as not found rather than as an error: the caller leaves
// the file document's value in effect (see resourceReader).
@@ -0,0 +1,82 @@
package controlplanestore
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
)
const SchedulesKind = "schedules"
func scheduleDefinition() Definition {
return Definition{
Kind: SchedulesKind,
Title: "Schedules",
Document: []scheduling.JobSpec{},
ApplyMode: "live",
Seed: func(config.Config) any { return []scheduling.JobSpec{} },
Validate: func(input []byte) error {
return validateAs(input, validateSchedules)
},
Normalize: normalizeSchedules,
}
}
func validateSchedules(jobs []scheduling.JobSpec) error {
seen := make(map[string]struct{}, len(jobs))
for _, job := range jobs {
if err := scheduling.RefuseDangerousJob(job); err != nil {
return err
}
if strings.TrimSpace(job.ID) == "" {
return fmt.Errorf("schedule ID is required")
}
if _, exists := seen[job.ID]; exists {
return fmt.Errorf("duplicate schedule %q", job.ID)
}
seen[job.ID] = struct{}{}
switch job.Kind {
case scheduling.KindWorkflow:
case scheduling.KindChat:
if job.Target.Channel == "" || job.Target.ChatID == "" || strings.TrimSpace(job.Payload.Text) == "" {
return fmt.Errorf("chat schedule %q needs a channel, chat ID and message", job.ID)
}
default:
return fmt.Errorf("schedule %q has unsupported kind %q", job.ID, job.Kind)
}
if err := job.Schedule.Validate(); err != nil {
return err
}
if err := scheduling.Pool(job.Pool).Validate(); err != nil {
return err
}
}
return nil
}
func normalizeSchedules(input []byte) ([]byte, error) {
var jobs []scheduling.JobSpec
if err := json.Unmarshal(input, &jobs); err != nil {
return nil, err
}
now := time.Now().UTC()
for i := range jobs {
jobs[i].Schedule = jobs[i].Schedule.Resolved()
if jobs[i].NextRun.IsZero() {
next, err := jobs[i].Schedule.FirstRun(now)
if err != nil {
return nil, err
}
jobs[i].NextRun = next.UTC()
}
if jobs[i].Created.IsZero() {
jobs[i].Created = now
}
jobs[i].Updated = now
}
return json.Marshal(jobs)
}
@@ -0,0 +1,155 @@
package controlplanestore
import (
"encoding/json"
"maps"
"reflect"
"strings"
"time"
)
// bareObjectSchema is what a descriptor advertises when its definition names no
// document. It is the fallback, not the norm: a descriptor with no properties is
// what left the Web UI with nothing to label, describe or format a field with
const bareObjectSchema = `{"type":"object"}`
var timeType = reflect.TypeFor[time.Time]()
// stdDuration is the marker this tree's string-form duration types satisfy:
// config.Duration, channelDuration and scheduling.Duration each expose the
// standard duration for arithmetic.
var stdDuration = reflect.TypeOf((*interface{ Std() time.Duration })(nil)).Elem()
// durationLike reports whether t marshals as a duration string.
func durationLike(t reflect.Type) bool {
if !t.Implements(stdDuration) {
return false
}
encoded, err := json.Marshal(reflect.Zero(t).Interface())
return err == nil && len(encoded) > 0 && encoded[0] == '"'
}
// schemaJSON derives a resource's JSON Schema from its document type: keys,
// types and tag annotations. It never emits required.
func schemaJSON(document any, extensions map[string]any) string {
if document == nil {
return bareObjectSchema
}
schema := schemaOf(reflect.TypeOf(document), "json")
maps.Copy(schema, extensions)
encoded, err := json.Marshal(schema)
if err != nil {
// Unreachable: the tree below holds only strings, maps, slices and
// booleans. A boot must not fail over documentation, so degrade to the
// shape descriptors carried before this existed rather than panic.
return bareObjectSchema
}
return string(encoded)
}
// settingsSchema is the JSON Schema of a workflow step's settings type, keyed by
// its yaml tags because step settings are written in YAML. Nil means the step
// takes no settings.
func settingsSchema(settings any) map[string]any {
if settings == nil {
return nil
}
return schemaOf(reflect.TypeOf(settings), "yaml")
}
// schemaOf is the JSON Schema for one type, following the keyTag struct tags
// for keys and the Go type for everything else.
func schemaOf(t reflect.Type, keyTag string) map[string]any {
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
switch {
case durationLike(t):
// The type writes the string time.ParseDuration reads, so the schema says
// so and a client can offer a duration affordance instead of a number
// box. This rule reaches every duration field in the catalogue, not just
// the one that prompted it.
return map[string]any{"type": "string", "format": "duration"}
case t == timeType:
return map[string]any{"type": "string", "format": "date-time"}
}
switch t.Kind() {
case reflect.Struct:
return objectSchemaOf(t, keyTag)
case reflect.Slice, reflect.Array:
return map[string]any{"type": "array", "items": schemaOf(t.Elem(), keyTag)}
case reflect.Map:
return map[string]any{"type": "object", "additionalProperties": schemaOf(t.Elem(), keyTag)}
case reflect.Bool:
return map[string]any{"type": "boolean"}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return map[string]any{"type": "integer"}
case reflect.Float32, reflect.Float64:
return map[string]any{"type": "number"}
case reflect.Interface:
return map[string]any{} // any JSON value
default:
return map[string]any{"type": "string"}
}
}
func objectSchemaOf(t reflect.Type, keyTag string) map[string]any {
properties := map[string]any{}
for field := range t.Fields() {
if field.Anonymous {
// encoding/json promotes an embedded struct's fields into the
// enclosing object, so the schema lists them there too. Dropping
// them would leave document keys nothing describes.
embedded, ok := schemaOf(field.Type, keyTag)["properties"].(map[string]any)
if !ok {
continue
}
maps.Copy(properties, embedded)
continue
}
if field.PkgPath != "" {
continue // unexported: not part of any document
}
name, ok := documentKey(field, keyTag)
if !ok {
continue
}
properties[name] = documented(schemaOf(field.Type, keyTag), field)
}
return map[string]any{"type": "object", "properties": properties}
}
// documentKey is the key a field carries in its document: the json tag's name,
// or the Go field name when the tag declares none, because that fallback is what
// encoding/json uses and therefore what the document really holds. Reporting the
// tag instead of the fallback would describe a document nobody stores.
func documentKey(field reflect.StructField, keyTag string) (string, bool) {
name, _, _ := strings.Cut(field.Tag.Get(keyTag), ",")
switch name {
case "-":
return "", false
case "":
return field.Name, true
default:
return name, true
}
}
// documented layers the three annotations a field declares in its own tags over
// the derived type.
func documented(schema map[string]any, field reflect.StructField) map[string]any {
for _, annotation := range []struct{ tag, key string }{
{"title", "title"},
{"format", "format"},
{"doc", "description"},
} {
if value := field.Tag.Get(annotation.tag); value != "" {
schema[annotation.key] = value
}
}
if values := field.Tag.Get("enum"); values != "" {
schema["enum"] = strings.Split(values, ",")
}
return schema
}
@@ -0,0 +1,101 @@
package controlplanestore
import (
"encoding/json"
"errors"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/skill"
)
// SkillsKind is the control-plane resource holding the org's skills: SKILL.md
// documents under their skill name.
const SkillsKind = "skills"
// SkillCollection is the skills document.
type SkillCollection struct {
Skills []SkillEntry `json:"skills"`
}
// SkillEntry is one skill. Content is its SKILL.md.
type SkillEntry struct {
Name string `json:"name"`
Content string `json:"content"`
}
func skillsDefinition() Definition {
return Definition{
Kind: SkillsKind,
Title: "Skills",
Document: SkillCollection{},
ApplyMode: "live",
Seed: func(config.Config) any { return SkillCollection{Skills: []SkillEntry{}} },
Validate: func(input []byte) error {
return validateAs(input, validateSkills)
},
}
}
func validateSkills(c SkillCollection) error {
seen := map[string]bool{}
for _, entry := range c.Skills {
if entry.Name == "" || seen[entry.Name] {
return fmt.Errorf("%w: skill name %q is empty or repeated", ErrValidation, entry.Name)
}
seen[entry.Name] = true
fm, _, err := skill.Parse([]byte(entry.Content))
if err != nil {
return fmt.Errorf("%w: skill %q: %w", ErrValidation, entry.Name, err)
}
if fm.Name != entry.Name {
return fmt.Errorf("%w: skill %q: SKILL.md names it %q", ErrValidation, entry.Name, fm.Name)
}
}
return nil
}
// NewSkillPackageProjector builds the projector for storepkg.FamilySkills.
func NewSkillPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger) (storepkg.FamilyProjector, error) {
return newListProjector(resources, ledger, listFamily[SkillEntry]{
kind: SkillsKind,
family: storepkg.FamilySkills,
decode: func(value []byte) ([]SkillEntry, error) {
c, err := decodeSkills(value)
return c.Skills, err
},
encode: func(entries []SkillEntry) ([]byte, error) {
return encodeSkills(SkillCollection{Skills: entries})
},
id: func(e SkillEntry) string { return e.Name },
parse: func(_ string, content []byte) (SkillEntry, error) {
fm, _, err := skill.Parse(content)
if err != nil {
return SkillEntry{}, err
}
if fm.Name == "" {
return SkillEntry{}, errors.New("no frontmatter name")
}
return SkillEntry{Name: fm.Name, Content: string(content)}, nil
},
})
}
func decodeSkills(value []byte) (SkillCollection, error) {
collection := SkillCollection{Skills: []SkillEntry{}}
if value == nil {
return collection, nil
}
if err := json.Unmarshal(value, &collection); err != nil {
return SkillCollection{}, fmt.Errorf("decode %s: %w", SkillsKind, err)
}
return collection, nil
}
func encodeSkills(collection SkillCollection) ([]byte, error) {
if err := validateSkills(collection); err != nil {
return nil, err
}
return json.Marshal(collection)
}
@@ -0,0 +1,32 @@
package controlplanestore
import (
"encoding/json"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agent"
)
// SoulKind is the control-plane resource holding the agent's SOUL document.
const SoulKind = "soul"
func soulDefinition() Definition {
return Definition{
Kind: SoulKind,
Title: "Instructions",
Document: agent.Soul{},
ApplyMode: "live",
// Seeded empty. An unowned SOUL reads the identity's file and then the
// shipped default; the first dashboard save takes ownership.
Seed: func(config.Config) any { return agent.Soul{} },
Validate: func(input []byte) error {
return validateAs(input, func(s agent.Soul) error { return s.Validate() })
},
}
}
func decodeSoul(input []byte) (agent.Soul, error) {
var soul agent.Soul
err := json.Unmarshal(input, &soul)
return soul, err
}
@@ -0,0 +1,46 @@
package controlplanestore
import (
"fmt"
"net/url"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/alert"
)
const TaskPolicyKind = "task-policy"
type taskPolicy struct {
NotifyWebhook string `json:"notify_webhook"`
NotifyMinSeverity string `json:"notify_min_severity"`
NotifySecret config.SecretRef `json:"notify_secret"`
}
func taskPolicyDefinition() Definition {
return Definition{Kind: TaskPolicyKind, Title: "Task policy", ApplyMode: "live", Document: taskPolicy{}, Seed: func(cfg config.Config) any {
return taskPolicyOf(cfg)
}, Validate: func(input []byte) error {
return validateAs(input, func(doc taskPolicy) error {
if doc.NotifyWebhook != "" {
parsed, err := url.Parse(doc.NotifyWebhook)
if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
return fmt.Errorf("notify_webhook must be an HTTP or HTTPS URL")
}
}
if !alert.Severity(doc.NotifyMinSeverity).Valid() && doc.NotifyMinSeverity != "" {
return fmt.Errorf("notify_min_severity must be info, warning or action")
}
if (doc.NotifySecret.Engine == "") != (doc.NotifySecret.Key == "") {
return fmt.Errorf("notify_secret needs both an engine and a key")
}
return nil
})
}}
}
func taskPolicyOf(cfg config.Config) taskPolicy {
return taskPolicy{
NotifyWebhook: cfg.Notify.Webhook,
NotifyMinSeverity: cfg.Notify.MinSeverity, NotifySecret: cfg.Notify.Secret,
}
}
@@ -0,0 +1,228 @@
{
"description": "Shared accept/reject fixtures for the control-plane validators the dashboard hand-mirrors in ui/src/settings/validation.ts. The control plane is the authority: every case's `valid` is what internal/infrastructure/controlplanestore accepts or refuses. The Go test in this package runs the real server validators over these cases; the node test ui/test/control-plane-validator-parity.test.ts runs the real dashboard validators over the same cases. A one-sided change to either rule makes one of the two tests fail, which is the tie that stops the two implementations drifting apart (archie-core-ui-dashboard-3). Add a case here, never only to one side.",
"cases": {
"model-aliases": [
{
"why": "a plain provider/model value",
"value": {
"default": "openai/gpt-4o"
},
"valid": true
},
{
"why": "a trailing space: the server only splits on the slash, so the dashboard must not refuse it",
"value": {
"default": "openai/gpt-4o "
},
"valid": true
},
{
"why": "a model id with a colon (a real ollama tag), which a stricter shape would wrongly refuse",
"value": {
"default": "openai/gpt-4o",
"fast": "ollama/qwen2.5-coder:7b"
},
"valid": true
},
{
"why": "an empty table: nothing configured yet",
"value": {},
"valid": true
},
{
"why": "no slash at all",
"value": {
"default": "gpt-4o"
},
"valid": false
},
{
"why": "an empty model half",
"value": {
"default": "openai/"
},
"valid": false
},
{
"why": "an empty model: the server refuses it, so the dashboard must too (SystemModelsPage deletes the key rather than storing one)",
"value": {
"default": ""
},
"valid": false
},
{
"why": "aliases without the default alias: an org's own table inherits the instance default, so only the instance save requires it",
"value": {
"fast": "openai/gpt-4o"
},
"valid": true
},
{
"why": "an alias name with capitals or spaces",
"value": {
"default": "openai/gpt-4o",
"Fast model": "openai/gpt-4o"
},
"valid": false
}
],
"scheduling-policy": [
{
"why": "a positive interval, a valid trigger and the label the trigger needs",
"value": {
"poll_interval": "1m0s",
"max_retries": 0,
"label": "archie",
"dispatch": {
"trigger": "assignee"
}
},
"valid": true
},
{
"why": "assignee does not require a label",
"value": {
"poll_interval": "30s",
"max_retries": 3,
"dispatch": {
"trigger": "assignee"
}
},
"valid": true
},
{
"why": "either requires a label, and one is present",
"value": {
"poll_interval": "1h30m",
"label": "archie",
"dispatch": {
"trigger": "either"
}
},
"valid": true
},
{
"why": "a fractional duration the server's parser accepts",
"value": {
"poll_interval": "1.5h",
"dispatch": {
"trigger": "assignee"
}
},
"valid": true
},
{
"why": "a zero interval",
"value": {
"poll_interval": "0s",
"label": "archie",
"dispatch": {
"trigger": "assignee"
}
},
"valid": false
},
{
"why": "an interval the server's parser cannot read",
"value": {
"poll_interval": "nonsense",
"label": "archie",
"dispatch": {
"trigger": "assignee"
}
},
"valid": false
},
{
"why": "the label trigger with no label",
"value": {
"poll_interval": "30s",
"max_retries": 3,
"dispatch": {
"trigger": "label"
}
},
"valid": false
},
{
"why": "the either trigger with an empty label",
"value": {
"poll_interval": "30s",
"max_retries": 0,
"label": "",
"dispatch": {
"trigger": "either"
}
},
"valid": false
}
],
"schedules": [
{
"why": "a single valid workflow job",
"value": [
{
"id": "daily",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "24h0m0s"
}
}
],
"valid": true
},
{
"why": "a cron job with a pool the server recognises",
"value": [
{
"id": "nightly",
"kind": "workflow",
"pool": "parallel",
"schedule": {
"kind": "cron",
"cron": "0 3 * * *"
}
}
],
"valid": true
},
{
"why": "a job with no id",
"value": [
{
"id": "",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "24h0m0s"
}
}
],
"valid": false
},
{
"why": "two jobs sharing an id",
"value": [
{
"id": "daily",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "24h0m0s"
}
},
{
"id": "daily",
"kind": "workflow",
"schedule": {
"kind": "interval",
"interval": "1h0m0s"
}
}
],
"valid": false
}
]
}
}
@@ -0,0 +1,86 @@
package controlplanestore
import (
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
)
type toolSettings struct {
MCPServers []mcpServerSettings `json:"mcp_servers"`
Policy config.ToolPolicy `json:"policy"`
WebFetch config.WebFetchConfig `json:"web_fetch"`
Minimax minimaxSettings `json:"minimax"`
}
type mcpServerSettings struct {
Name string `json:"name"`
Transport string `json:"transport"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
WorkDir string `json:"work_dir,omitempty"`
URL string `json:"url,omitempty"`
SSEEndpoint string `json:"sse_endpoint,omitempty"`
MessageEndpoint string `json:"message_endpoint,omitempty"`
// ParallelToolCalls is nil when not stored, keeping the file's value.
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`
HeadersConfigured bool `json:"headers_configured"`
}
type minimaxSettings struct {
Enabled bool `json:"enabled"`
APIKey config.SecretRef `json:"api_key_ref"`
CredentialConfigured bool `json:"credential_configured"`
BaseURL string `json:"base_url,omitempty"`
}
func seedTools(cfg config.Config) any {
servers := make([]mcpServerSettings, 0, len(cfg.Tools.MCPServers))
for _, server := range cfg.Tools.MCPServers {
// The seed states the file's value explicitly: it is written on a fresh
// store, where there is nothing older to inherit from.
parallelToolCalls := server.ParallelToolCalls
servers = append(servers, mcpServerSettings{
Name: server.Name,
Transport: server.Transport,
Command: server.Command,
Args: server.Args,
WorkDir: server.WorkDir,
URL: server.URL,
SSEEndpoint: server.SSEEndpoint,
MessageEndpoint: server.MessageEndpoint,
ParallelToolCalls: &parallelToolCalls,
HeadersConfigured: len(server.Headers) > 0,
})
}
return toolSettings{MCPServers: servers, Policy: cfg.Tools.Policy, WebFetch: cfg.Tools.WebFetch, Minimax: minimaxSettings{Enabled: cfg.Tools.Minimax.Enabled, APIKey: cfg.Tools.Minimax.APIKey, CredentialConfigured: cfg.Tools.Minimax.APIKey != (config.SecretRef{}), BaseURL: cfg.Tools.Minimax.BaseURL}}
}
func validateTools(input []byte) error {
return validateAs(input, func(settings toolSettings) error {
for _, server := range settings.MCPServers {
transport := strings.ToLower(strings.TrimSpace(server.Transport))
if server.Name == "" {
return fmt.Errorf("MCP server name is required")
}
switch transport {
case "", "stdio":
if server.Command == "" {
return fmt.Errorf("MCP stdio server %q requires command", server.Name)
}
case "http", "streamablehttp":
if server.URL == "" {
return fmt.Errorf("MCP http server %q requires url", server.Name)
}
case "sse":
if server.SSEEndpoint == "" {
return fmt.Errorf("MCP sse server %q requires sse_endpoint", server.Name)
}
default:
return fmt.Errorf("unknown MCP transport %q", server.Transport)
}
}
return nil
})
}
@@ -0,0 +1,64 @@
package controlplanestore
import (
"encoding/json"
"errors"
"fmt"
"maps"
"slices"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
const WorkflowDefinitionsKind = "workflow-definitions"
// stepRegistry returns the step vocabulary from the injected manager.
func stepRegistry(steps *workflow.Manager) (workflow.StepRegistry, error) {
if steps == nil {
return nil, errors.New("control plane: no workflow step vocabulary: the composition root must register the provider set (infrastructure/workflowsteps.NewManager) before the first resolution")
}
return steps.Registry(), nil
}
func workflowDefinitionsDefinition(steps workflow.StepRegistry, settings map[string]any) Definition {
return Definition{
Kind: WorkflowDefinitionsKind,
Title: "Workflow definitions",
Document: workflow.WorkflowDefinitionCollection{},
ApplyMode: "live",
Seed: func(config.Config) any {
return workflow.ShippedDefinitions()
},
Defaults: func() any {
return workflow.ShippedDefinitions()
},
Validate: func(input []byte) error {
_, err := workflow.DecodeDefinitionCollection(input, steps)
return err
},
SchemaExtensions: map[string]any{"x-step-types": stepTypeVocabulary(steps, settings), "x-intake-routes": workflow.IntakeRoutes()},
}
}
// stepTypeVocabulary is the registered step types as the dashboard editor
// reads them: each name, whether it needs a repository, and the schema of its
// settings (absent for a step that takes none).
func stepTypeVocabulary(steps workflow.StepRegistry, settings map[string]any) []map[string]any {
vocabulary := make([]map[string]any, 0, len(steps))
for _, name := range slices.Sorted(maps.Keys(steps)) {
entry := map[string]any{"name": name, "needs_repository": workflow.NeedsRepository(name)}
if schema := settingsSchema(settings[name]); schema != nil {
entry["settings"] = schema
}
vocabulary = append(vocabulary, entry)
}
return vocabulary
}
func encodeWorkflowDefinitions(collection workflow.WorkflowDefinitionCollection, steps workflow.StepRegistry) ([]byte, error) {
if err := workflow.ValidateDefinitionCollection(collection, steps); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
return json.Marshal(collection)
}
@@ -0,0 +1,45 @@
package controlplanestore
import (
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/config"
)
// WorkflowDraftsKind holds unpublished edits to workflows. A draft may be
// incomplete or invalid, so only its shape is checked; publishing copies it
// into workflow-definitions, which validates it. Nothing runs from a draft
// except an explicit test run.
const WorkflowDraftsKind = "workflow-drafts"
type workflowDraft struct {
ID string `json:"id"`
YAML string `json:"yaml"`
}
type workflowDraftCollection struct {
Drafts []workflowDraft `json:"drafts"`
}
func workflowDraftsDefinition() Definition {
return Definition{
Kind: WorkflowDraftsKind,
Title: "Workflow drafts",
Document: workflowDraftCollection{},
ApplyMode: "live",
Seed: func(config.Config) any { return workflowDraftCollection{Drafts: []workflowDraft{}} },
Validate: func(input []byte) error {
return validateAs(input, func(c workflowDraftCollection) error {
seen := map[string]bool{}
for _, draft := range c.Drafts {
if strings.TrimSpace(draft.ID) == "" || seen[draft.ID] {
return fmt.Errorf("workflow draft id %q is empty or repeated", draft.ID)
}
seen[draft.ID] = true
}
return nil
})
},
}
}
@@ -0,0 +1,40 @@
package controlplanestore
import (
"context"
"encoding/json"
"github.com/samcharles93/archie-core/internal/config"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
const WorkflowEnablementKind = "workflow-enablement"
func workflowEnablementDefinition() Definition {
return Definition{
Kind: WorkflowEnablementKind,
Title: "Workflow enablement",
Document: task.WorkflowEnablement{},
ApplyMode: "live",
Seed: func(config.Config) any { return task.WorkflowEnablement{Orgs: map[org.OrgID]task.OrgWorkflows{}} },
Validate: func(input []byte) error {
return validateAs(input, func(enablement task.WorkflowEnablement) error { return enablement.Validate() })
},
}
}
// WorkflowEnablement returns which workflows each org has disabled.
func (c *Client) WorkflowEnablement(ctx context.Context) (task.WorkflowEnablement, error) {
response, err := c.rpc.Query(ctx, &controlpb.QueryRequest{Kind: WorkflowEnablementKind})
if err != nil {
c.ApplyStatus.Report(ctx, WorkflowEnablementKind, 0, err)
return task.WorkflowEnablement{}, controlplanerpc.ClientError(err)
}
var enablement task.WorkflowEnablement
err = json.Unmarshal(response.Resource.ValueJson, &enablement)
c.ApplyStatus.Report(ctx, WorkflowEnablementKind, response.Resource.Version, err)
return enablement, err
}
@@ -0,0 +1,174 @@
package controlplanestore
import (
"context"
"errors"
"fmt"
"strconv"
"time"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// projectionActor is the audit identity every package projection carries: the
// write is made by the installed package, never by a request body.
const projectionActor = "archie-state-store"
// projectWriteAttempts bounds one apply or withdrawal: each attempt re-reads
// the org's document and re-merges, so a document the operator edited during
// the projection is folded in, and only a persistently moving document
// refuses the projection.
const projectWriteAttempts = 3
// WorkflowProjector merges an installed package's workflows into the org's
// workflow-definitions resource. Ids owned by an operator or another package
// are refused.
type WorkflowProjector struct {
store ResourceStore
ledger storepkg.ProjectionLedger
steps workflow.StepRegistry
}
var _ storepkg.FamilyProjector = (*WorkflowProjector)(nil)
// NewWorkflowPackageProjector builds the projector for storepkg.FamilyWorkflows
// on the workflow step vocabulary the composition root registered: the
// vocabulary the projected definitions are compiled and validated against,
// the same one the control plane validates dashboard edits with.
func NewWorkflowPackageProjector(resources ResourceStore, ledger storepkg.ProjectionLedger, manager *workflow.Manager) (*WorkflowProjector, error) {
steps, err := stepRegistry(manager)
if err != nil {
return nil, err
}
if resources == nil || ledger == nil {
return nil, errors.New("control plane: workflow projection needs a resource store and a contributions ledger")
}
return &WorkflowProjector{store: resources, ledger: ledger, steps: steps}, nil
}
func (p *WorkflowProjector) Apply(ctx context.Context, orgID, name, digest string, contents map[string][]byte) error {
entries := make([]workflow.WorkflowDefinitionEntry, 0, len(contents))
recorded := make([]storepkg.ProjectionEntry, 0, len(contents))
for contentName, content := range contents {
id, err := workflow.DefinitionID(string(content))
if err != nil {
return fmt.Errorf("contributed workflow %q: %w", contentName, err)
}
if workflow.PackageOf(string(content)) != "" {
return fmt.Errorf("contributed workflow %q: package is set by the installer, not the workflow", contentName)
}
entries = append(entries, workflow.WorkflowDefinitionEntry{ID: id, YAML: "package: " + strconv.Quote(name) + "\n" + string(content)})
recorded = append(recorded, storepkg.ProjectionEntry{Family: storepkg.FamilyWorkflows, EntryID: id})
}
// One apply, one request: a retried PutResource reuses the same request ID
// and answers once, while a later install of the same package writes a
// revision of its own.
source := "package:" + name + "@" + digest
if err := p.write(ctx, orgID, source, "package-project:"+digest, func(collection workflow.WorkflowDefinitionCollection) (workflow.WorkflowDefinitionCollection, error) {
return mergeContribution(collection, entries, name)
}); err != nil {
return err
}
if err := p.ledger.Record(ctx, orgID, name, recorded); err != nil {
return fmt.Errorf("record contributions of %q: %w", name, err)
}
return nil
}
func (p *WorkflowProjector) Withdraw(ctx context.Context, orgID, name, digest string) error {
entries, err := p.ledger.Entries(ctx, orgID, name)
if err != nil {
return fmt.Errorf("entries of package %q: %w", name, err)
}
withdrawn := make(map[string]struct{}, len(entries))
for _, entry := range entries {
if entry.Family == storepkg.FamilyWorkflows {
withdrawn[entry.EntryID] = struct{}{}
}
}
if len(withdrawn) == 0 {
return nil
}
if err := p.write(ctx, orgID, "package-withdraw:"+name+"@"+digest, "package-withdraw:"+digest,
func(collection workflow.WorkflowDefinitionCollection) (workflow.WorkflowDefinitionCollection, error) {
merged := make([]workflow.WorkflowDefinitionEntry, 0, len(collection.Definitions))
for _, item := range collection.Definitions {
if _, gone := withdrawn[item.ID]; gone {
continue
}
merged = append(merged, item)
}
return workflow.WorkflowDefinitionCollection{Definitions: merged}, nil
}); err != nil {
return err
}
return p.ledger.Forget(ctx, orgID, name, storepkg.FamilyWorkflows)
}
// write merges an org's stored workflow-definitions document and puts it
// back, bounded by projectWriteAttempts: each attempt re-reads and re-merges,
// so a document the operator edited during the projection is folded in, and
// the write carries the ledger's replay identity of one episode.
func (p *WorkflowProjector) write(ctx context.Context, orgID, source, requestPrefix string, merge func(workflow.WorkflowDefinitionCollection) (workflow.WorkflowDefinitionCollection, error)) error {
requestID := requestPrefix + ":" + strconv.FormatInt(time.Now().UTC().UnixNano(), 36)
for attempt := 0; ; attempt++ {
collection, version := p.collection(ctx, orgID)
merged, err := merge(collection)
if err != nil {
return err
}
value, err := encodeWorkflowDefinitions(merged, p.steps)
if err != nil {
return err
}
if _, err := p.store.PutResource(ctx, storecontract.ResourceWrite{
OrgID: orgID, Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: version,
Actor: projectionActor, Source: source, RequestID: requestID,
}); errors.Is(err, storecontract.ErrResourceVersionConflict) && attempt < projectWriteAttempts-1 {
continue
} else if err != nil {
return err
}
return nil
}
}
// collection reads an org's workflow-definitions document. An org that never
// received one starts from the shipped definitions, the state a first write
// seeds, so projection leaves the org with one answer either way.
func (p *WorkflowProjector) collection(ctx context.Context, orgID string) (workflow.WorkflowDefinitionCollection, int64) {
resource, err := p.store.Resource(ctx, orgID, WorkflowDefinitionsKind)
if errors.Is(err, storecontract.ErrResourceNotFound) {
return workflow.ShippedDefinitions(), 0
}
if err != nil {
return workflow.WorkflowDefinitionCollection{}, 0
}
collection, err := workflow.DecodeDefinitionCollection(resource.Value, p.steps)
if err != nil {
return workflow.WorkflowDefinitionCollection{}, 0
}
return collection, resource.Version
}
// mergeContribution merges a package's contributed entries into an org's
// collection. An operator's entry with the same workflow id is a refusal, not
// a silent replacement; the package's own entries reach here only after its
// ledger rows were cleared, so colliding is always foreign work.
func mergeContribution(base workflow.WorkflowDefinitionCollection, contributed []workflow.WorkflowDefinitionEntry, name string) (workflow.WorkflowDefinitionCollection, error) {
replacing := make(map[string]struct{}, len(contributed))
for _, entry := range contributed {
replacing[entry.ID] = struct{}{}
}
merged := make([]workflow.WorkflowDefinitionEntry, 0, len(base.Definitions)+len(contributed))
for _, entry := range base.Definitions {
if _, incoming := replacing[entry.ID]; incoming {
return workflow.WorkflowDefinitionCollection{}, fmt.Errorf("package %q: %w: workflow %q", name, storepkg.ErrContributionCollision, entry.ID)
}
merged = append(merged, entry)
}
merged = append(merged, contributed...)
return workflow.WorkflowDefinitionCollection{Definitions: merged}, nil
}
@@ -0,0 +1,84 @@
package controlplanestore
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
const WorkflowExecutionSettingsKind = "workflow-execution-settings"
// defaultTaskRuntime bounds a task run when the stored settings predate the
// limit.
const defaultTaskRuntime = 4 * time.Hour
type executionSettingsDocument struct {
MaxModelToolSteps int `json:"max_model_tool_steps"`
MaxRuntimeSeconds int64 `json:"max_runtime_seconds" title:"Max seconds per agent call" doc:"Limit for one agent call inside a stage. 0 disables it."`
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
// MaxTaskRuntimeSeconds is a pointer so a document stored before the
// field existed reads as the default, while an explicit 0 disables it.
MaxTaskRuntimeSeconds *int64 `json:"max_task_runtime_seconds" title:"Max task runtime seconds" doc:"Limit for a whole task run; the task is parked when it passes. 0 disables it."`
}
// ImportWorkflowExecutionSettings seeds the workflow execution settings when
// the store does not hold them.
func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings workflow.ExecutionSettings) (int64, error) {
resource, err := s.store.Resource(ctx, storecontract.DefaultOrgID, WorkflowExecutionSettingsKind)
if err == nil {
return resource.Version, nil
}
if !errors.Is(err, storecontract.ErrResourceNotFound) {
return 0, err
}
value, err := encodeSettings(settings)
if err != nil {
return 0, err
}
value, err = workflowDefinition().Decode(value)
if err != nil {
return 0, err
}
resource, err = s.store.PutResource(ctx, storecontract.ResourceWrite{OrgID: storecontract.DefaultOrgID, Kind: WorkflowExecutionSettingsKind, Value: value, Actor: seedActor, Source: seedSource, RequestID: seedRequestID(WorkflowExecutionSettingsKind, value), ExpectedVersion: 0, At: time.Now().UTC()})
return resource.Version, err
}
func workflowDefinition() Definition {
return Definition{
Kind: WorkflowExecutionSettingsKind, Title: "Workflow execution settings", ApplyMode: "live", Document: executionSettingsDocument{},
Seed: func(cfg config.Config) any {
taskRuntime := time.Duration(cfg.Budgets.TaskWallClock)
if taskRuntime == 0 {
taskRuntime = defaultTaskRuntime
}
return executionSettingsDocument{cfg.Budgets.MaxSteps, int64(time.Duration(cfg.Budgets.WallClock) / time.Second), cfg.Budgets.GateMaxFailures, new(int64(taskRuntime / time.Second))}
},
Validate: func(input []byte) error { _, err := decodeSettings(input); return err },
}
}
func encodeSettings(s workflow.ExecutionSettings) ([]byte, error) {
return json.Marshal(executionSettingsDocument{s.MaxModelToolSteps, int64(s.MaxRuntime / time.Second), s.MaxConsecutiveGateFailures, new(int64(s.MaxTaskRuntime / time.Second))})
}
func decodeSettings(value []byte) (workflow.ExecutionSettings, error) {
var document executionSettingsDocument
if err := json.Unmarshal(value, &document); err != nil {
return workflow.ExecutionSettings{}, fmt.Errorf("%w: invalid JSON: %w", ErrValidation, err)
}
taskRuntime := defaultTaskRuntime
if document.MaxTaskRuntimeSeconds != nil {
taskRuntime = time.Duration(*document.MaxTaskRuntimeSeconds) * time.Second
}
settings := workflow.ExecutionSettings{MaxModelToolSteps: document.MaxModelToolSteps, MaxRuntime: time.Duration(document.MaxRuntimeSeconds) * time.Second, MaxConsecutiveGateFailures: document.MaxConsecutiveGateFailures, MaxTaskRuntime: taskRuntime}
if err := settings.Validate(); err != nil {
return workflow.ExecutionSettings{}, fmt.Errorf("%w: %w", ErrValidation, err)
}
return settings, nil
}