feat(controlplane): runtime administration over the State Store's gRPC server

The Web UI and messaging channels now read and write Archie's runtime
settings through one versioned, audited control-plane API hosted on the
State Store's existing gRPC server: catalog, query, command, watch. Each
feature owns its resource, validation and commands; storage only writes
versions and audit records.

Workflows move with it. Definitions become portable YAML compiled through
a closed, typed step registry and stored as a control-plane resource, so
the yaegi interpretation paths (internal/gate, wfeval, wfextract,
gateeval, gateextract, skillbuild) are deleted rather than carried.

The UI process reads definitions as data: the JSON projection lives in
internal/domain/workflow/task so a dashboard decodes the stored
collection without linking the workflow engine, which cmd/archie-ui's
deletion gate forbids. Shipped definitions ride the catalog descriptor
rather than a bespoke REST route, keeping the API to its four operations.

archie-messaging gains -state-store-target/-state-store-token and reads
channel settings from the database, failing closed when the State Store
is unreachable: the database is authoritative for those settings.
This commit is contained in:
sam committed 2026-09-21 08:17:42 +10:00
1 parent 28e2c01018
commit 3944f544e8
131 files changed
+8510 -3371

No files matched your search

+2
View File
@@ -50,6 +50,8 @@ domain migration.
planning/refactor tracking issues. planning/refactor tracking issues.
- **Solo Project Context:** Prefer the smallest workable change over extensive - **Solo Project Context:** Prefer the smallest workable change over extensive
defensive scaffolding. defensive scaffolding.
- **PRD writing:** Read and follow `docs/prds/RULES.md` before creating or
editing a PRD.
## Deployment Model ## Deployment Model
+2
View File
@@ -27,6 +27,8 @@ func run() int {
flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target, else 127.0.0.1:8585)") flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target, else 127.0.0.1:8585)")
flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway") flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway")
flag.StringVar(&options.StateStore.Target, "state-store-target", "", "archie-state-store gRPC address (defaults to [services.state].target)")
flag.StringVar(&options.StateStore.Token, "state-store-token", "", "bearer token presented to archie-state-store")
flag.DurationVar(&options.DependencyTimeout, "dependency-timeout", 0, "readiness probe timeout (default 5s)") flag.DurationVar(&options.DependencyTimeout, "dependency-timeout", 0, "readiness probe timeout (default 5s)")
flag.DurationVar(&options.ShutdownTimeout, "shutdown-timeout", 0, "shutdown timeout (default 5s)") flag.DurationVar(&options.ShutdownTimeout, "shutdown-timeout", 0, "shutdown timeout (default 5s)")
flag.Parse() flag.Parse()
+36 -1
View File
@@ -14,6 +14,7 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
) )
@@ -73,6 +74,38 @@ func startTestGateway(t *testing.T) (target string, cleanup func()) {
} }
} }
// fakeControlPlane serves the empty channel-settings resource the Messaging
// Service reads at startup. The database is authoritative for channel
// settings, so the process refuses to start without a State Store to read.
type fakeControlPlane struct {
controlpb.UnimplementedControlPlaneServiceServer
}
func (f *fakeControlPlane) Catalog(context.Context, *controlpb.CatalogRequest) (*controlpb.CatalogResponse, error) {
return &controlpb.CatalogResponse{}, nil
}
func (f *fakeControlPlane) Query(_ context.Context, request *controlpb.QueryRequest) (*controlpb.QueryResponse, error) {
return &controlpb.QueryResponse{Resource: &controlpb.Resource{Kind: request.GetKind(), Version: 1, ValueJson: []byte("{}")}}, nil
}
func startTestStateStore(t *testing.T) (target string, cleanup func()) {
t.Helper()
lis, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("net.Listen: %v", err)
}
srv := grpc.NewServer()
controlpb.RegisterControlPlaneServiceServer(srv, &fakeControlPlane{})
go func() {
_ = srv.Serve(lis)
}()
return lis.Addr().String(), func() {
srv.GracefulStop()
_ = lis.Close()
}
}
func TestBinaryHelp(t *testing.T) { func TestBinaryHelp(t *testing.T) {
bin := buildBinary(t) bin := buildBinary(t)
cmd := exec.CommandContext(t.Context(), bin, "-help") cmd := exec.CommandContext(t.Context(), bin, "-help")
@@ -87,8 +120,10 @@ func TestBinaryStartsAndShutsDownCleanly(t *testing.T) {
bin := buildBinary(t) bin := buildBinary(t)
gatewayTarget, cleanup := startTestGateway(t) gatewayTarget, cleanup := startTestGateway(t)
defer cleanup() defer cleanup()
stateStoreTarget, stopStateStore := startTestStateStore(t)
defer stopStateStore()
cmd := exec.CommandContext(t.Context(), bin, "-gateway-target", gatewayTarget) cmd := exec.CommandContext(t.Context(), bin, "-gateway-target", gatewayTarget, "-state-store-target", stateStoreTarget)
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
t.Fatalf("cmd.Start: %v", err) t.Fatalf("cmd.Start: %v", err)
} }
+29
View File
@@ -0,0 +1,29 @@
# PRD writing rules
These rules apply to every file in `docs/prds/`.
- Search existing PRDs, issues, architecture records, and code first. Do not ask
the maintainer to repeat recorded requirements.
- A newer maintainer decision overrides an older design. Mark the old design as
superseded instead of preserving or defending it.
- Write plain English. Use a technical term only when the reader needs that
exact contract or concept.
- Use the shortest direct sentence. Write “When upgraded, existing instances
are migrated to the database,” not a description of an importer seeding
absent resources.
- State each fact once. Do not repeat a heading, summarize a list before showing
it, or restate a decision afterward.
- Every sentence must add a decision, requirement, constraint, evidence, or
verification step. Delete narration and explanations of obvious text.
- Do not turn a requested outcome into extra product features. Keep inferences
open until the maintainer or repository evidence settles them.
- Do not create a process for a logical boundary. Add one only when it must
deploy, scale, start, secure, or fail separately.
- Describe working behavior, not explanatory UI around missing behavior. State
what users can do and how success is proved.
- Before approval, use independent read-only reviewers to check a cross-cutting
PRD for missing behavior and exaggerated claims. Verify and synthesize their
findings; do not copy their prose.
- Before requesting approval, review every sentence for complexity, repetition,
and unsupported scope.
- Mark a draft as unapproved until the maintainer explicitly approves it.
+125
View File
@@ -0,0 +1,125 @@
# Runtime control plane
**Status:** Draft — not approved
**Date:** 2026-09-20
**Tracking:** `archie-core-j28m`, `archie-core-1786637498420-327-bacadaae`
## Outcome
Archie can be managed from the Web UI or a messaging channel. Both use the same
API.
## Model
Each feature owns its settings and commands. The database stores them. There is
no global configuration document.
This includes:
- workflows;
- identities and bindings;
- providers and models;
- repository policies;
- channels and schedules;
- capture mappings and bindings;
- tool settings;
- prompts and personas;
- plugin settings.
Plugin code remains installed code. Only its settings are stored in the
database.
Each feature defines its data, validation, permissions, editor fields, and how
changes take effect. Each feature also defines its allowed actions. For example,
identities can be created, suspended, and retired.
Repository and identity settings remain separate. They are not stored as large
records that unrelated features must share.
The State Store process hosts the control-plane API on its existing gRPC server.
No new process is added. Feature code validates changes. Storage code only
writes versions and audit records.
Every write records who made it, where it came from, a request ID, and the
version being edited. The API layer sets the actor; the request body cannot.
The server validates the change, then writes it with its audit record. It rejects
edits to an old version.
## API
The API has four operations:
1. **Catalog** tells clients what can be viewed or changed and how to edit it.
2. **Query** reads data and versions without exposing secrets.
3. **Command** asks the owning feature to make a change.
4. **Watch** streams changes and errors to clients.
Complex features can use custom screens. They still use the same commands.
A dashboard session or channel sender must map to an Archie identity before it
can run a command. Messaging syntax maps to the same commands as the Web UI.
`archie-ui` receives only an API client. It does not receive a database handle,
daemon pointer, global configuration object, or secret value.
The database stores the requested settings. Each process reports the version it
is using or why it failed. The UI shows both.
Some changes require a restart. The UI shows them as pending. When a live change
replaces a running component, Archie starts and checks the new one before
switching. If the check fails, the old one keeps running.
## Bootstrap, migration, and recovery
Bootstrap contains only the database path, listen addresses, credentials, TLS,
and encryption-key references. State Store and control-plane RPCs use the same
endpoint.
When upgraded, existing instances are migrated to the database. Existing
database values are not overwritten. After migration, settings in TOML are
ignored and cannot block State Store startup.
The Web UI remains available when `archied` or Gateway is down. It shows failed
changes and can correct or roll them back.
Offline commands can back up, restore, validate, and roll back the database.
Recovery does not require `archied` or the Web UI. The database stores secret
references, not secret values.
## Workflows
Users create and edit workflows in the Web UI. Workflows are stored as versioned
YAML. Built-in workflows can be overridden and restored.
A workflow is a list of steps. Each step has a known type and its own settings.
Plugins can add step types. Each run keeps the workflow version it started with.
Yaegi, `.archie/stages/*.go`, and `.archie/gate.go` will be removed. Their useful
behavior must first be available as normal workflow steps.
## First implementation
The first implementation makes task limits editable: maximum model steps,
maximum runtime, and maximum consecutive gate failures.
It includes:
- validated task-limit fields;
- version history and audit records;
- the four API operations;
- authenticated Web UI and messaging access;
- live updates and apply status;
- a Pinia-backed editor in the Web UI;
- a messaging command using the same API;
- migration of existing `[budgets]` values;
- an end-to-end restart test.
Running tasks keep the limits they started with. New tasks use the latest applied
version. This replaces the old settings overlay instead of extending it.
## Not included in the first implementation
- Moving bootstrap or secret values into normal settings.
- A generic JSON editor.
- Rebuilding every settings screen at once.
- Changing the limits of a running task.
+47 -23
View File
@@ -13,9 +13,7 @@ import (
"github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfeval"
"github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/installtype" "github.com/samcharles93/archie-core/internal/installtype"
"github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/storage"
@@ -202,27 +200,23 @@ func applyToolLimits(agent agentexec.Runner, policy config.ToolPolicy) {
} }
} }
// routeTask applies the request-carried routing bindings and selects the // routeTask remains available for routing-only callers. Production execution
// workflow for a task. The daemon's package-level SetKindWorkflows state // compiles the request's pinned YAML directly.
// never crosses the process boundary, so runTask installs the resolved
// bindings here -- this worker process is where workflow.Route actually runs.
func routeTask(req taskrun.Request, registry workflow.Registry) workflow.Workflow { func routeTask(req taskrun.Request, registry workflow.Registry) workflow.Workflow {
workflow.SetKindWorkflows(req.KindWorkflows) workflow.SetKindWorkflows(req.KindWorkflows)
workflow.SetLabelWorkflows(req.LabelWorkflows) workflow.SetLabelWorkflows(req.LabelWorkflows)
return workflow.Route(req.Task, registry) return workflow.Route(req.Task, registry)
} }
// runTask builds a workflow.Registry from the container's mounted worktree, // runTask compiles the immutable database definition carried by the request,
// routes and runs the entire workflow, and reports its terminal outcome. // runs it, and reports its terminal outcome.
// Store remains archied's authority; Response.Task is a logging snapshot. // Store remains archied's authority; Response.Task is a logging snapshot.
func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependencies, newRunner runnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) { func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependencies, newRunner runnerFactory, workDir string, log *slog.Logger) (*taskrun.Response, error) {
registry, err := skillbuild.BuildRegistry(workDir) wf, err := resolvePinnedWorkflow(&req)
if err != nil { if err != nil {
return nil, fmt.Errorf("build registry: %w", err) return nil, err
} }
wf := routeTask(req, registry)
trees := &hybridTrees{ trees := &hybridTrees{
push: dependencies.trees, push: dependencies.trees,
local: &worktree.Manager{ local: &worktree.Manager{
@@ -286,17 +280,16 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
} }
tc := &workflow.TaskContext{ tc := &workflow.TaskContext{
Task: req.Task, Task: req.Task,
Repo: req.Repo, Repo: req.Repo,
Cfg: req.Cfg.ToConfig(), Cfg: req.Cfg.ToConfig(),
Forge: dependencies.forge, Forge: dependencies.forge,
Store: dependencies.store, Store: dependencies.store,
Trees: trees, Trees: trees,
Agent: agent, Agent: agent,
Reviewer: newReviewerFor(req), Reviewer: newReviewerFor(req),
Bus: bus, Bus: bus,
Log: log, Log: log,
CustomStages: wfeval.Discover,
} }
if req.Repo.PersistentStorage { if req.Repo.PersistentStorage {
memory, readErr := readProjectMemory(storage.MemoryPath) memory, readErr := readProjectMemory(storage.MemoryPath)
@@ -317,3 +310,34 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
AgentInstallType: installtype.Type(), AgentInstallType: installtype.Type(),
}, nil }, nil
} }
func resolvePinnedWorkflow(req *taskrun.Request) (workflow.Workflow, error) {
if req.WorkflowDefinition == "" {
shipped := workflow.ShippedDefinitions()
registry := make(workflow.Registry, len(shipped.Definitions))
for _, definition := range shipped.Definitions {
compiled, compileErr := workflow.ParseAndCompile(definition.YAML, workflow.BuiltinStepRegistry())
if compileErr != nil {
return workflow.Workflow{}, fmt.Errorf("compile shipped workflow definition: %w", compileErr)
}
registry[definition.ID] = compiled
}
selected := routeTask(*req, registry)
req.Task.Workflow = selected.Name
entry, ok := shipped.DefinitionByID(selected.Name)
if !ok {
return workflow.Workflow{}, fmt.Errorf("task has no pinned workflow definition")
}
req.WorkflowDefinition = entry.YAML
req.Task.WorkflowDefinitionYAML = entry.YAML
req.Task.WorkflowDefinitionDigest = workflow.DigestDefinition(entry.YAML)
}
wf, err := workflow.ParseAndCompile(req.WorkflowDefinition, workflow.BuiltinStepRegistry())
if err != nil {
return workflow.Workflow{}, fmt.Errorf("compile pinned workflow definition: %w", err)
}
if wf.Name != req.Task.Workflow || workflow.DigestDefinition(req.WorkflowDefinition) != req.Task.WorkflowDefinitionDigest {
return workflow.Workflow{}, fmt.Errorf("pinned workflow definition does not match task identity")
}
return wf, nil
}
+17 -17
View File
@@ -24,6 +24,7 @@ import (
natsio "github.com/nats-io/nats.go" natsio "github.com/nats-io/nats.go"
"github.com/samcharles93/ai-sdk/runtime" "github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/daemon" "github.com/samcharles93/archie-core/internal/daemon"
@@ -32,11 +33,11 @@ import (
"github.com/samcharles93/archie-core/internal/domain/eda/playbook" "github.com/samcharles93/archie-core/internal/domain/eda/playbook"
domainembedding "github.com/samcharles93/archie-core/internal/domain/embedding" domainembedding "github.com/samcharles93/archie-core/internal/domain/embedding"
"github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
domainmemory "github.com/samcharles93/archie-core/internal/domain/memory" domainmemory "github.com/samcharles93/archie-core/internal/domain/memory"
"github.com/samcharles93/archie-core/internal/domain/scheduling" "github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild"
"github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/domain/workintake"
"github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/forge" "github.com/samcharles93/archie-core/internal/forge"
@@ -116,6 +117,7 @@ type boot struct {
// standalone-only compose leaves no other case). // standalone-only compose leaves no other case).
stateStoreGrants *staterpc.GrantIssuer stateStoreGrants *staterpc.GrantIssuer
stateStoreToken string stateStoreToken string
controlPlane *controlplane.Client
chatSessionStore gateway.SessionStore chatSessionStore gateway.SessionStore
catalog modelcatalog.Snapshot catalog modelcatalog.Snapshot
@@ -282,6 +284,7 @@ func (b *boot) loadConfig(ctx context.Context, cfgPath, overlayPath string, noCo
} }
} }
b.cfg = b.doc.Config b.cfg = b.doc.Config
b.cfgHolder = config.NewHolder(b.cfg)
b.currentProvenance.Store(&b.doc.Provenance) b.currentProvenance.Store(&b.doc.Provenance)
return b.setupLogging() return b.setupLogging()
} }
@@ -363,6 +366,7 @@ func (b *boot) openStateStoreAdapter() error {
return err return err
} }
b.stateStore = client b.stateStore = client
b.controlPlane = controlplane.NewRPCClient(client.ControlPlane())
b.stateStoreGrants = &staterpc.GrantIssuer{Client: client} b.stateStoreGrants = &staterpc.GrantIssuer{Client: client}
b.stateStoreToken = b.cfg.Services.ResolvedToken(config.ServiceNameState, b.secrets.Getenv) b.stateStoreToken = b.cfg.Services.ResolvedToken(config.ServiceNameState, b.secrets.Getenv)
b.addCleanup(cleanup) b.addCleanup(cleanup)
@@ -419,7 +423,6 @@ func (b *boot) setupObservability(ctx context.Context) {
bus := events.NewBus() bus := events.NewBus()
b.bus = bus b.bus = bus
b.addCleanup(func() { bus.Close() }) b.addCleanup(func() { bus.Close() })
b.cfgHolder = config.NewHolder(cfg)
// The watchdog leaves its verdict in a file on this host, so the daemon // The watchdog leaves its verdict in a file on this host, so the daemon
// reads it and publishes the outcome as an event; the dashboard renders // reads it and publishes the outcome as an event; the dashboard renders
// what it receives, wherever it runs (archie-core-8cda.5.4). // what it receives, wherever it runs (archie-core-8cda.5.4).
@@ -584,13 +587,15 @@ func (b *boot) setupEmbeddings(cfg config.Config, log *slog.Logger) {
// setupLLMAndChat wires the runtime, tool registry, model management, // setupLLMAndChat wires the runtime, tool registry, model management,
// personas and the dashboard's chat service. // personas and the dashboard's chat service.
func (b *boot) setupLLMAndChat() error { func (b *boot) setupLLMAndChat(ctx context.Context) error {
cfg, log := b.cfg, b.log cfg, log := b.cfg, b.log
// Telegram/email keep their own in-process routers rather than going // Telegram/email keep their own in-process routers rather than going
// through ChatContract: their streaming responder is a callback, and // through ChatContract: their streaming responder is a callback, and
// ChatContract's wire-safe interface can't carry one. // ChatContract's wire-safe interface can't carry one.
b.setupChatRuntime(cfg) if err := b.setupChatRuntime(ctx, cfg); err != nil {
return err
}
b.setupEmbeddings(cfg, log) b.setupEmbeddings(cfg, log)
contract, cleanup, err := composeChatContract(cfg.Services, b.secrets) contract, cleanup, err := composeChatContract(cfg.Services, b.secrets)
@@ -635,9 +640,8 @@ func (b *boot) startRateLimiter(ctx context.Context, cfg config.RateLimitConfig)
}() }()
} }
// loadWorkflows builds the workflow registry from the skill catalog. // loadWorkflows loads routing inputs. Executable definitions are supplied by
// Plugin-defined workflows override built-ins of the same name; // the State Store control plane and pinned before each dispatch.
// built-ins fill gaps.
func (b *boot) loadWorkflows(ctx context.Context) error { func (b *boot) loadWorkflows(ctx context.Context) error {
cfg, log := b.cfg, b.log cfg, log := b.cfg, b.log
if err := b.loadWorkflowRouting(cfg, log); err != nil { if err := b.loadWorkflowRouting(cfg, log); err != nil {
@@ -650,16 +654,7 @@ func (b *boot) loadWorkflows(ctx context.Context) error {
return err return err
} }
skillsBase := cfg.SkillsDir log.Info("workflow step registry built", "shipped_workflows", len(workflow.ShippedDefinitions().Definitions))
if skillsBase == "" {
skillsBase = cfg.WorkDir
}
workflowCatalog, err := skillbuild.BuildCatalog(skillsBase)
if err != nil {
log.Error("skill registry build failed", "err", err)
return err
}
log.Info("workflow registry built", "workflows", len(workflowCatalog.Registry))
// The dashboard is served by the archie-ui process from the cutover // The dashboard is served by the archie-ui process from the cutover
// change (archie-core-8cda.5.4, PRD gate 7): the daemon runs no webui // change (archie-core-8cda.5.4, PRD gate 7): the daemon runs no webui
// listener, and [web].listen is the archie-ui process's bind address. // listener, and [web].listen is the archie-ui process's bind address.
@@ -1250,10 +1245,15 @@ func (b *boot) buildDaemon() {
Guardrails: b.guardrails, Guardrails: b.guardrails,
ToolRegistry: b.toolReg, ToolRegistry: b.toolReg,
Identities: b.identityRunners, Identities: b.identityRunners,
RootIdentityID: identity.StableID(configuredIdentityNames(b.cfg)[0]),
TaskLogs: b.taskLogs, TaskLogs: b.taskLogs,
AgentStatus: b.agentStatus, AgentStatus: b.agentStatus,
KindWorkflows: b.kindWorkflows, KindWorkflows: b.kindWorkflows,
LabelWorkflows: b.labelWorkflows, LabelWorkflows: b.labelWorkflows,
WorkflowDefinitions: b.controlPlane,
}
if identities, ok := b.stateStore.(identity.Repository); ok {
b.d.IdentityRepository = identities
} }
// Consumer mapping/binding surfaces resolve from b.stateStore (the State // Consumer mapping/binding surfaces resolve from b.stateStore (the State
// Store contract adapter): local by default, remote *staterpc.Client when // Store contract adapter): local by default, remote *staterpc.Client when
@@ -20,7 +20,7 @@ func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() { _ = st.Close() }) t.Cleanup(func() { _ = st.Close() })
b := &boot{cfg: cfg, log: slog.Default(), cfgHolder: config.NewHolder(cfg), stateStore: st} b := &boot{cfg: cfg, log: slog.Default(), cfgHolder: config.NewHolder(cfg), stateStore: st, personas: gateway.NewPersonaRegistry(gateway.DefaultPersonas())}
t.Cleanup(b.cleanup) t.Cleanup(b.cleanup)
if err := b.openStores(t.Context()); err != nil { if err := b.openStores(t.Context()); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -29,7 +29,7 @@ func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) {
t.Fatal("startup did not open the channel conversation store") t.Fatal("startup did not open the channel conversation store")
} }
sessions := b.chatSessionStore sessions := b.chatSessionStore
if err := b.setupLLMAndChat(); err != nil { if err := b.setupLLMAndChat(t.Context()); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if b.chatSessionStore != sessions { if b.chatSessionStore != sessions {
+61
View File
@@ -0,0 +1,61 @@
package archied
import (
"context"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
func (b *boot) loadRuntimeConfig(ctx context.Context) error {
cfg, err := b.controlPlane.RuntimeConfig(ctx, b.cfg)
if err != nil {
return err
}
if err := configuration.Validate(&cfg); err != nil {
return fmt.Errorf("validate database settings: %w", err)
}
b.cfg = cfg
b.cfgHolder.Set(cfg)
return nil
}
func (b *boot) startWorkflowExecutionSettings(ctx context.Context) error {
settings, version, err := b.controlPlane.WorkflowExecutionSettings(ctx)
if err != nil {
return err
}
b.applyWorkflowExecutionSettings(settings, version)
updates, err := b.controlPlane.WatchWorkflowExecutionSettings(ctx, version)
if err != nil {
return err
}
go func() {
for update := range updates {
if update.Err != nil {
b.log.Error("workflow execution settings watch failed", "err", update.Err)
return
}
b.applyWorkflowExecutionSettings(update.Settings, update.Version)
}
}()
return nil
}
func (b *boot) applyWorkflowExecutionSettings(settings workflow.ExecutionSettings, version int64) {
cfg := b.cfgHolder.Get().Clone()
cfg.Budgets = executionBudgets(settings)
for i := range cfg.Identities {
cfg.Identities[i].Budgets = cfg.Budgets
}
b.cfgHolder.Set(cfg)
b.log.Info("workflow execution settings applied", "version", version)
}
func executionBudgets(settings workflow.ExecutionSettings) config.Budgets {
return config.Budgets{
MaxSteps: settings.MaxModelToolSteps, WallClock: config.Duration(settings.MaxRuntime), GateMaxFailures: settings.MaxConsecutiveGateFailures,
}
}
+15 -2
View File
@@ -67,7 +67,7 @@ func RunGateway(ctx context.Context, options GatewayOptions) error {
// same remote State Store contract the daemon does via // same remote State Store contract the daemon does via
// [services.state].target (docs/prds/state-store-contract.md §12 step 7). // [services.state].target (docs/prds/state-store-contract.md §12 step 7).
// Its own session SQLite is untouched and stays Gateway-owned. // Its own session SQLite is untouched and stays Gateway-owned.
if err := b.openStateStoreAdapter(); err != nil { if err := b.openGatewayState(ctx); err != nil {
return err return err
} }
b.loadCatalog(ctx, options.Config) b.loadCatalog(ctx, options.Config)
@@ -125,6 +125,16 @@ func RunGateway(ctx context.Context, options GatewayOptions) error {
return serveGateway(ctx, listener, contract, b.chatSessionStore, opts) return serveGateway(ctx, listener, contract, b.chatSessionStore, opts)
} }
func (b *boot) openGatewayState(ctx context.Context) error {
if err := b.openStateStoreAdapter(); err != nil {
return err
}
if err := b.loadRuntimeConfig(ctx); err != nil {
return fmt.Errorf("load runtime settings: %w", err)
}
return nil
}
func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) { func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
b.bus = events.NewBus() b.bus = events.NewBus()
b.addCleanup(b.bus.Close) b.addCleanup(b.bus.Close)
@@ -136,7 +146,10 @@ func (b *boot) startGatewayRuntime(ctx context.Context, actor gateway.ChatTaskAc
if err := b.setupMemoryEngine(); err != nil { //nolint:contextcheck // setupMemoryEngine owns its own lifecycle context, matching the daemon's setupMemoryEngine if err := b.setupMemoryEngine(); err != nil { //nolint:contextcheck // setupMemoryEngine owns its own lifecycle context, matching the daemon's setupMemoryEngine
return nil, err return nil, err
} }
contract := b.setupGatewayChat(ctx, actor) contract, err := b.setupGatewayChat(ctx, actor)
if err != nil {
return nil, err
}
if err := b.registerTools(ctx); err != nil { if err := b.registerTools(ctx); err != nil {
return nil, err return nil, err
} }
+38 -5
View File
@@ -6,6 +6,7 @@ import (
"github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/agentexec"
"github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/tools" "github.com/samcharles93/archie-core/internal/tools"
) )
@@ -14,7 +15,7 @@ import (
// chat task creator/controller, default chat identity and the release-update // chat task creator/controller, default chat identity and the release-update
// service. The daemon and the standalone Gateway build through this one // service. The daemon and the standalone Gateway build through this one
// constructor so the two processes cannot diverge. // constructor so the two processes cannot diverge.
func (b *boot) setupChatRuntime(cfg config.Config) { func (b *boot) setupChatRuntime(ctx context.Context, cfg config.Config) error {
// ── LLM runtime ────────────────────────────────────────────────── // ── LLM runtime ──────────────────────────────────────────────────
// Created before the router so the LLMResponder can be wired in for // Created before the router so the LLMResponder can be wired in for
// non-command message processing. // non-command message processing.
@@ -26,7 +27,27 @@ func (b *boot) setupChatRuntime(cfg config.Config) {
b.chatModels = chatModels b.chatModels = chatModels
// ── Persona registry ───────────────────────────────────────────── // ── Persona registry ─────────────────────────────────────────────
b.personas = gateway.NewPersonaRegistry(gateway.DefaultPersonas()) if b.personas == nil {
personas, version, err := b.controlPlane.Personas(ctx)
if err != nil {
return fmt.Errorf("load personas: %w", err)
}
b.personas = gateway.NewPersonaRegistry(nil)
b.applyPersonas(personas, version)
updates, err := b.controlPlane.WatchPersonas(ctx, version)
if err != nil {
return fmt.Errorf("watch personas: %w", err)
}
go func() {
for update := range updates {
if update.Err != nil {
b.log.Error("persona watch failed", "err", update.Err)
return
}
b.applyPersonas(update.Collection, update.Version)
}
}()
}
// ── Operator health surface ────────────────────────────────────── // ── Operator health surface ──────────────────────────────────────
// Built before the gateways because every turn runner and router built // Built before the gateways because every turn runner and router built
@@ -52,12 +73,24 @@ func (b *boot) setupChatRuntime(cfg config.Config) {
transition: b.stateStore.Transition, transition: b.stateStore.Transition,
}) })
b.updateService = makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)}) b.updateService = makeUpdateService(chatSetup{Cfg: config.NewHolder(cfg)})
return nil
}
func (b *boot) applyPersonas(collection agent.PersonaCollection, version int64) {
personas := make([]gateway.Persona, 0, len(collection.Personas))
for _, persona := range collection.Personas {
personas = append(personas, gateway.Persona{Name: persona.Name, Prompt: persona.Prompt})
}
b.personas.Replace(personas, collection.Default)
b.log.Info("personas applied", "version", version)
} }
// setupGatewayChat is the sole production constructor of the local contract. // setupGatewayChat is the sole production constructor of the local contract.
// Frontends use its gRPC representation; only this service owns the router. // Frontends use its gRPC representation; only this service owns the router.
func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor) gateway.ChatContract { func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
b.setupChatRuntime(b.cfg) if err := b.setupChatRuntime(ctx, b.cfg); err != nil {
return nil, err
}
cfg := b.cfg cfg := b.cfg
router := gateway.NewRouter(b.stateStore, nil, "web") router := gateway.NewRouter(b.stateStore, nil, "web")
router.Limiter = b.rateLimiter router.Limiter = b.rateLimiter
@@ -88,5 +121,5 @@ func (b *boot) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor
return &gateway.LocalChatAdapter{ return &gateway.LocalChatAdapter{
Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log), Router: router, Sessions: b.chatSessionStore, Turns: gateway.NewTurns(b.log),
Models: b.chatModels, Personas: b.personas, TaskActor: actor, Models: b.chatModels, Personas: b.personas, TaskActor: actor,
} }, nil
} }
+10 -2
View File
@@ -347,7 +347,7 @@ func parseArgs() (runArgs, bool) {
return args, false return args, false
} }
func Run() int { //nolint:cyclop // the composition root's setup sequence is deliberately flat and sequential func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence is deliberately flat and sequential
args, exit := parseArgs() args, exit := parseArgs()
if exit { if exit {
return 0 return 0
@@ -390,6 +390,14 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
if err := b.openStateStoreAdapter(); err != nil { if err := b.openStateStoreAdapter(); err != nil {
return 1 return 1
} }
if err := b.loadRuntimeConfig(ctx); err != nil {
b.log.Error("runtime settings unavailable", "err", err)
return 1
}
if err := b.startWorkflowExecutionSettings(ctx); err != nil {
b.log.Error("workflow execution settings unavailable", "err", err)
return 1
}
if exit, err := b.handleRequeue(ctx, args.requeue, args.once); err != nil { if exit, err := b.handleRequeue(ctx, args.requeue, args.once); err != nil {
return 1 return 1
} else if exit { } else if exit {
@@ -402,7 +410,7 @@ func Run() int { //nolint:cyclop // the composition root's setup sequence is del
return 1 return 1
} }
if err := b.setupLLMAndChat(); err != nil { if err := b.setupLLMAndChat(ctx); err != nil {
return 1 return 1
} }
if err := b.buildTreesAndIdentities(ctx); err != nil { if err := b.buildTreesAndIdentities(ctx); err != nil {
+19 -3
View File
@@ -29,6 +29,10 @@ type prReviewer struct {
models map[string]string models map[string]string
providers map[string]agentexec.Provider providers map[string]agentexec.Provider
maxSteps int maxSteps int
// currentMaxSteps lets the composition root apply live control-plane
// versions to reviews that have not started yet. Tests and direct
// constructions retain maxSteps as the fallback.
currentMaxSteps func() int
// allowed maps a chat identity to the "owner/name" repos it may review. // allowed maps a chat identity to the "owner/name" repos it may review.
// A nil identity is an authenticated dashboard operator, who may review // A nil identity is an authenticated dashboard operator, who may review
// any configured repository. // any configured repository.
@@ -100,11 +104,15 @@ func (r *prReviewer) ReviewPR(ctx context.Context, identity *string, repo string
return gateway.PRReviewResult{}, fmt.Errorf("snapshot PR head: %w", err) return gateway.PRReviewResult{}, fmt.Errorf("snapshot PR head: %w", err)
} }
maxSteps := r.maxSteps
if r.currentMaxSteps != nil {
maxSteps = r.currentMaxSteps()
}
report := reviewer.Review(ctx, workflow.ReviewRequest{ report := reviewer.Review(ctx, workflow.ReviewRequest{
SnapshotDir: snapshotDir, SnapshotDir: snapshotDir,
Diff: diff, Diff: diff,
IssueText: prIssueText(pr), IssueText: prIssueText(pr),
MaxSteps: r.maxSteps, MaxSteps: maxSteps,
}) })
r.logReview(key, model, report) r.logReview(key, model, report)
return mapReviewResult(repo, number, model, report), nil return mapReviewResult(repo, number, model, report), nil
@@ -246,14 +254,22 @@ func (b *boot) prReviewer() gateway.ChatPRReviewer {
if forgeReader == nil { if forgeReader == nil {
return nil return nil
} }
b.chatPRReviewer = &prReviewer{ maxSteps := b.cfg.Budgets.MaxSteps
if b.cfgHolder != nil {
maxSteps = b.cfgHolder.Get().Budgets.MaxSteps
}
review := &prReviewer{
forge: forgeReader, forge: forgeReader,
trees: b.trees, trees: b.trees,
models: b.cfg.Models, models: b.cfg.Models,
providers: executionProviders(b.cfg), providers: executionProviders(b.cfg),
maxSteps: b.cfg.Budgets.MaxSteps, maxSteps: maxSteps,
allowed: buildReviewAllowlist(b.cfg), allowed: buildReviewAllowlist(b.cfg),
log: b.log, log: b.log,
} }
if b.cfgHolder != nil {
review.currentMaxSteps = func() int { return b.cfgHolder.Get().Budgets.MaxSteps }
}
b.chatPRReviewer = review
return b.chatPRReviewer return b.chatPRReviewer
} }
+73 -11
View File
@@ -2,11 +2,12 @@ package archied
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"log/slog" "log/slog"
"path/filepath"
"time" "time"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/domain/scheduling" "github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/gateway"
@@ -68,16 +69,7 @@ func (b *boot) setupScheduling() error {
return nil return nil
} }
storePath := filepath.Join(filepath.Dir(b.cfg.DBPath), "cron", "jobs.json") store := scheduleResourceStore{client: b.controlPlane}
store, err := cronstore.Open(storePath)
if err != nil {
return fmt.Errorf("scheduling: open job store: %w", err)
}
b.addCleanup(func() {
if err := store.Close(); err != nil {
b.log.Error("scheduling store close", "err", err)
}
})
workflowRunner, err := crondelivery.NewWorkflowTask(store, spawnTaskSubmitter{creator: b.chatTasks, identity: b.defaultChatIdentity}) workflowRunner, err := crondelivery.NewWorkflowTask(store, spawnTaskSubmitter{creator: b.chatTasks, identity: b.defaultChatIdentity})
if err != nil { if err != nil {
@@ -97,6 +89,76 @@ func (b *boot) setupScheduling() error {
return nil return nil
} }
type scheduleResourceStore struct {
client *controlplane.Client
}
func (s scheduleResourceStore) Get(ctx context.Context, id string) (cronstore.JobSpec, bool, error) {
jobs, _, err := s.client.Schedules(ctx)
if err != nil {
return cronstore.JobSpec{}, false, err
}
for _, job := range jobs {
if job.ID == id {
return job, true, nil
}
}
return cronstore.JobSpec{}, false, nil
}
func (s scheduleResourceStore) Due(ctx context.Context, now time.Time) ([]scheduling.Job, error) {
jobs, _, err := s.client.Schedules(ctx)
if err != nil {
return nil, err
}
due := make([]scheduling.Job, 0, len(jobs))
for _, job := range jobs {
if !job.NextRun.After(now) {
due = append(due, scheduling.Job{ID: job.ID, Pool: scheduling.Pool(job.Pool), Detail: job.Detail})
}
}
return due, nil
}
func (s scheduleResourceStore) MarkRun(ctx context.Context, id string, runAt time.Time) error {
for range 4 {
jobs, version, err := s.client.Schedules(ctx)
if err != nil {
return err
}
found := false
for index := range jobs {
if jobs[index].ID != id {
continue
}
found = true
if jobs[index].Schedule.Resolved().Kind == cronstore.ScheduleOnce {
jobs = append(jobs[:index], jobs[index+1:]...)
break
}
next, nextErr := jobs[index].Schedule.NextRun(runAt)
if nextErr != nil {
return nextErr
}
at := runAt.UTC()
jobs[index].LastRun = &at
jobs[index].NextRun = next.UTC()
break
}
if !found {
return fmt.Errorf("%w: id %q", cronstore.ErrJobNotFound, id)
}
_, err = s.client.ReplaceSchedules(ctx, jobs, version, "system:scheduler", "scheduler", fmt.Sprintf("schedule-run:%s:%d", id, runAt.UnixNano()))
if err == nil {
return nil
}
if !errors.Is(err, controlplane.ErrVersionConflict) {
return err
}
}
return controlplane.ErrVersionConflict
}
// shutdownSchedulingEngine returns a cleanup that stops the ticker engine. // shutdownSchedulingEngine returns a cleanup that stops the ticker engine.
// The stop path derives its own timeout budget from Background rather than // The stop path derives its own timeout budget from Background rather than
// the boot context, which is already cancelled by the time shutdown runs -- // the boot context, which is already cancelled by the time shutdown runs --
+85 -1
View File
@@ -15,18 +15,39 @@ import (
"fmt" "fmt"
"net" "net"
"net/http" "net/http"
"os"
"path/filepath"
"time" "time"
"google.golang.org/grpc" "google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/config"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
"github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/readiness"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/store"
) )
func configuredIdentityNames(cfg config.Config) []string {
if len(cfg.Identities) == 0 {
name := cfg.BotUser
if name == "" {
name = "archie"
}
return []string{name}
}
names := make([]string, 0, len(cfg.Identities))
for _, value := range cfg.Identities {
names = append(names, value.Name)
}
return names
}
// StateStoreOptions contains process inputs for the standalone State Store. // StateStoreOptions contains process inputs for the standalone State Store.
type StateStoreOptions struct { type StateStoreOptions struct {
Config string Config string
@@ -65,6 +86,31 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error {
if err := b.openStateStore(ctx); err != nil { if err := b.openStateStore(ctx); err != nil {
return err return err
} }
identityStore, ok := b.st.(interface {
BootstrapIdentities(context.Context, []string) error
})
if !ok {
return fmt.Errorf("state store does not support identity bootstrap")
}
legacyNames := configuredIdentityNames(b.cfg)
if err := identityStore.BootstrapIdentities(ctx, legacyNames); err != nil {
return fmt.Errorf("bootstrap identities: %w", err)
}
resources, ok := b.st.(interface {
Resource(context.Context, string) (store.Resource, error)
PutResource(context.Context, store.ResourceWrite) (store.Resource, error)
})
if !ok {
return fmt.Errorf("state store does not support control-plane resources")
}
control := controlplane.NewServer(resources)
versions, err := control.ImportConfig(ctx, b.cfg)
if err != nil {
return fmt.Errorf("import control-plane resources: %w", err)
}
if err := migrateLegacySchedules(ctx, control, b.cfg.DBPath, versions[controlplane.SchedulesKind]); err != nil {
return fmt.Errorf("migrate schedules: %w", err)
}
token := options.Token token := options.Token
if token == "" { if token == "" {
@@ -89,7 +135,42 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error {
} }
} }
return serveStateStore(ctx, listener, b.stateStoreDeps(grants), opts) deps := b.stateStoreDeps(grants)
deps.ControlPlane = control
return serveStateStore(ctx, listener, deps, opts)
}
func migrateLegacySchedules(ctx context.Context, control *controlplane.Server, dbPath string, version int64) error {
if version != 1 {
return nil
}
path := filepath.Join(filepath.Dir(dbPath), "cron", "jobs.json")
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
legacy, err := cronstore.Open(path)
if err != nil {
return err
}
jobs, listErr := legacy.List(ctx)
closeErr := legacy.Close()
if listErr != nil {
return listErr
}
if closeErr != nil {
return closeErr
}
value, err := json.Marshal(jobs)
if err != nil {
return err
}
if _, err := control.Command(ctx, &controlpb.CommandRequest{Kind: controlplane.SchedulesKind, Command: "replace", ValueJson: value, ExpectedVersion: 1, Actor: "system:migration", Source: "legacy-cronstore", RequestId: "import:legacy-schedules"}); err != nil {
return err
}
return os.Rename(path, path+".migrated")
} }
// openStateStore opens the single task-store SQLite file exactly once for // openStateStore opens the single task-store SQLite file exactly once for
@@ -130,6 +211,9 @@ func (b *boot) openStateStore(ctx context.Context) error {
// degrades that group rather than aborting boot. // degrades that group rather than aborting boot.
func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants} deps := staterpc.Deps{Tasks: b.st, Log: b.log, Grants: grants}
if identities, ok := b.st.(identity.Repository); ok {
deps.Identities = identities
}
// Task logs live in the state directory, which this process owns, and the // Task logs live in the state directory, which this process owns, and the
// dashboard process owns no such directory -- so this is where a task-log // dashboard process owns no such directory -- so this is where a task-log
// read is served from (docs/prds/ui-service-boundary.md). The reader is // read is served from (docs/prds/ui-service-boundary.md). The reader is
@@ -50,3 +50,16 @@ func TestLoadConfigDoesNotWarnOnAKnownConfig(t *testing.T) {
t.Errorf("unexpected warning for a config with no unknown keys: %s", out) t.Errorf("unexpected warning for a config with no unknown keys: %s", out)
} }
} }
func TestLoadConfigMakesRuntimeSettingsAvailableBeforeSubsystemSetup(t *testing.T) {
path := filepath.Join(t.TempDir(), "config.toml")
writeConfig(t, path, minimalConfigTOML("widget"))
b := &boot{log: slog.Default()}
if err := b.loadConfig(t.Context(), path, "", true); err != nil {
t.Fatalf("loadConfig: %v", err)
}
if b.cfgHolder == nil {
t.Fatal("runtime config holder is nil before control-plane settings load")
}
}
+6 -4
View File
@@ -19,10 +19,11 @@ import (
) )
type deps struct { type deps struct {
Config ResolvedConfig Config ResolvedConfig
Log *slog.Logger Log *slog.Logger
Chat messaging.ChatContract Chat messaging.ChatContract
Health *health.Registry Health *health.Registry
Settings *messaging.SettingsCommand
} }
type channelInstance struct { type channelInstance struct {
@@ -63,6 +64,7 @@ func compose(ctx context.Context, d deps) (*Service, error) {
"Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.") "Add your Telegram user id to chat.telegram.allowed_user_ids to enable the bot.")
} }
tg := telegram.New(d.Config.TelegramToken, d.Config.Telegram.AllowedUserIDs, d.Log) tg := telegram.New(d.Config.TelegramToken, d.Config.Telegram.AllowedUserIDs, d.Log)
tg.Settings = d.Settings
configureTelegram(ctx, tg, d.Config, d.Chat, d.Log) configureTelegram(ctx, tg, d.Config, d.Chat, d.Log)
if err := srv.add("telegram", tg, telegramValidateConfigMap(d.Config.Telegram)); err != nil { if err := srv.add("telegram", tg, telegramValidateConfigMap(d.Config.Telegram)); err != nil {
return nil, err return nil, err
+11
View File
@@ -34,6 +34,7 @@ type ResolvedConfig struct {
type projection struct { type projection struct {
gateway ServiceTarget gateway ServiceTarget
stateStore ServiceTarget
telegram config.TelegramConfig telegram config.TelegramConfig
email config.EmailConfig email config.EmailConfig
webhook config.WebhookRoute webhook config.WebhookRoute
@@ -111,6 +112,7 @@ func project(cfg config.Config) projection {
Target: cfg.Services.Get(config.ServiceNameGateway).Target, Target: cfg.Services.Get(config.ServiceNameGateway).Target,
Token: cfg.Services.Get(config.ServiceNameGateway).TargetToken, Token: cfg.Services.Get(config.ServiceNameGateway).TargetToken,
}, },
stateStore: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameState).Target, Token: cfg.Services.Get(config.ServiceNameState).TargetToken},
telegram: cfg.Chat.Telegram, telegram: cfg.Chat.Telegram,
email: cfg.Chat.Email, email: cfg.Chat.Email,
webhook: cfg.Chat.Webhook, webhook: cfg.Chat.Webhook,
@@ -126,6 +128,9 @@ func withEnvTokens(o Options) Options {
if o.Gateway.Token == "" { if o.Gateway.Token == "" {
o.Gateway.Token = os.Getenv("GATEWAY_TOKEN") o.Gateway.Token = os.Getenv("GATEWAY_TOKEN")
} }
if o.StateStore.Token == "" {
o.StateStore.Token = os.Getenv("STATE_STORE_TOKEN")
}
return o return o
} }
@@ -136,6 +141,12 @@ func merge(o Options, p projection) Options {
if o.Gateway.Token == "" { if o.Gateway.Token == "" {
o.Gateway.Token = p.gateway.Token o.Gateway.Token = p.gateway.Token
} }
if o.StateStore.Target == "" {
o.StateStore.Target = p.stateStore.Target
}
if o.StateStore.Token == "" {
o.StateStore.Token = p.stateStore.Token
}
return o return o
} }
+6
View File
@@ -35,6 +35,7 @@ type Options struct {
Overlay string Overlay string
Gateway ServiceTarget Gateway ServiceTarget
StateStore ServiceTarget
DependencyTimeout time.Duration DependencyTimeout time.Duration
ShutdownTimeout time.Duration ShutdownTimeout time.Duration
} }
@@ -59,6 +60,11 @@ func (o Options) validate() error {
if err := validateServiceTarget("gateway", o.Gateway); err != nil { if err := validateServiceTarget("gateway", o.Gateway); err != nil {
return err return err
} }
if o.StateStore.Target != "" {
if err := validateServiceTarget("state store", o.StateStore); err != nil {
return err
}
}
return nil return nil
} }
+37 -4
View File
@@ -5,7 +5,12 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/secret"
) )
// Run runs the standalone Messaging Service process until ctx is cancelled. // Run runs the standalone Messaging Service process until ctx is cancelled.
@@ -24,12 +29,40 @@ func Run(ctx context.Context, o Options) error {
defer closeGateway() defer closeGateway()
health := newReadinessRegistry(cfg.Options, chat) health := newReadinessRegistry(cfg.Options, chat)
var settings *messaging.SettingsCommand
var closeStateStore func()
if cfg.Options.StateStore.Target != "" {
stateStore, closeClient, dialErr := staterpc.Dial(cfg.Options.StateStore.Target, cfg.Options.StateStore.Token)
if dialErr != nil {
return fmt.Errorf("dial state store control plane (%s): %w", cfg.Options.StateStore.Target, dialErr)
}
closeStateStore = closeClient
defer closeStateStore()
chatSettings, settingsErr := controlplane.NewRPCClient(stateStore.ControlPlane()).RuntimeChatConfig(ctx, config.ChatConfig{
Telegram: cfg.Telegram, Email: cfg.Email, Webhook: cfg.Webhook, WebhookAddr: cfg.WebhookAddr, ShowToolCalls: cfg.ShowToolCalls,
})
if settingsErr != nil {
return fmt.Errorf("load channel settings: %w", settingsErr)
}
secrets := secret.NewRegistry()
cfg.Telegram, cfg.Email, cfg.Webhook, cfg.WebhookAddr, cfg.ShowToolCalls = chatSettings.Telegram, chatSettings.Email, chatSettings.Webhook, chatSettings.WebhookAddr, chatSettings.ShowToolCalls
cfg.TelegramToken, settingsErr = resolveTelegramToken(chatSettings.Telegram, secrets)
if settingsErr != nil {
return fmt.Errorf("resolve database telegram token: %w", settingsErr)
}
cfg.WebhookSecret, settingsErr = resolveWebhookSecret(chatSettings.Webhook, secrets)
if settingsErr != nil {
return fmt.Errorf("resolve database webhook secret: %w", settingsErr)
}
settings = messaging.NewSettingsCommand(messagingControlPlane{client: stateStore.ControlPlane()}).WithIdentities(stateStore)
}
srv, err := compose(ctx, deps{ srv, err := compose(ctx, deps{
Config: cfg, Config: cfg,
Log: log, Log: log,
Chat: chat, Chat: chat,
Health: health, Health: health,
Settings: settings,
}) })
if err != nil { if err != nil {
return err return err
+100
View File
@@ -0,0 +1,100 @@
package archiemessaging
import (
"context"
"encoding/json"
"errors"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/messaging"
)
type messagingControlPlane struct{ client pb.ControlPlaneServiceClient }
func (c messagingControlPlane) Catalog(ctx context.Context) ([]messaging.SettingDescriptor, error) {
response, err := c.client.Catalog(ctx, &pb.CatalogRequest{})
if err != nil {
return nil, settingsRPCError(err)
}
descriptors := make([]messaging.SettingDescriptor, 0, len(response.Resources))
for _, resource := range response.Resources {
var schema struct {
Properties map[string]struct {
Type string `json:"type"`
Format string `json:"format"`
WriteOnly bool `json:"writeOnly"`
} `json:"properties"`
}
if err := json.Unmarshal([]byte(resource.SchemaJson), &schema); err != nil {
return nil, errors.Join(messaging.ErrSettingsValidation, err)
}
fields := make(map[string]messaging.SettingField, len(schema.Properties))
for name, property := range schema.Properties {
fieldType := property.Type
if property.Format == "duration" || strings.HasSuffix(name, "_seconds") {
fieldType = "duration"
}
fields[name] = messaging.SettingField{Type: fieldType, Secret: property.WriteOnly || secretFieldName(name)}
}
descriptors = append(descriptors, messaging.SettingDescriptor{Kind: resource.Kind, Title: resource.Title, Fields: fields})
}
return descriptors, nil
}
func (c messagingControlPlane) Query(ctx context.Context, kind string) (messaging.SettingResource, error) {
response, err := c.client.Query(ctx, &pb.QueryRequest{Kind: kind})
if err != nil {
return messaging.SettingResource{}, settingsRPCError(err)
}
return settingResource(response.Resource)
}
func (c messagingControlPlane) Command(ctx context.Context, command messaging.SettingCommand) (messaging.SettingResource, error) {
input := any(command.Value)
if command.RawValue != nil {
input = command.RawValue
}
value, err := json.Marshal(input)
if err != nil {
return messaging.SettingResource{}, errors.Join(messaging.ErrSettingsValidation, err)
}
response, err := c.client.Command(ctx, &pb.CommandRequest{Kind: command.Kind, Command: "replace", ValueJson: value, ExpectedVersion: command.ExpectedVersion, RequestId: command.RequestID, Actor: command.Actor, Source: command.Source})
if err != nil {
return messaging.SettingResource{}, settingsRPCError(err)
}
return settingResource(response.Resource)
}
func settingResource(resource *pb.Resource) (messaging.SettingResource, error) {
if resource == nil {
return messaging.SettingResource{}, messaging.ErrSettingsUnavailable
}
var raw any
if err := json.Unmarshal(resource.ValueJson, &raw); err != nil {
return messaging.SettingResource{}, errors.Join(messaging.ErrSettingsValidation, err)
}
value, _ := raw.(map[string]any)
return messaging.SettingResource{Kind: resource.Kind, Version: resource.Version, Value: value, Raw: raw}, nil
}
func settingsRPCError(err error) error {
switch status.Code(err) {
case codes.InvalidArgument:
return errors.Join(messaging.ErrSettingsValidation, err)
case codes.NotFound:
return errors.Join(messaging.ErrSettingsNotFound, err)
case codes.Aborted:
return errors.Join(messaging.ErrSettingsConflict, err)
default:
return errors.Join(messaging.ErrSettingsUnavailable, err)
}
}
func secretFieldName(name string) bool {
name = strings.ToLower(name)
return strings.Contains(name, "secret") || strings.Contains(name, "password") || strings.Contains(name, "token") || strings.Contains(name, "credential") || strings.Contains(name, "key")
}
+11 -5
View File
@@ -5,7 +5,9 @@ import (
"log/slog" "log/slog"
"time" "time"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/events"
@@ -18,11 +20,13 @@ import (
// contracts, the process's own logger and options, and the readiness registry // contracts, the process's own logger and options, and the readiness registry
// assembled over those same contracts. // assembled over those same contracts.
type deps struct { type deps struct {
Options Options Options Options
Log *slog.Logger Log *slog.Logger
Store storecontract.TaskStore Store storecontract.TaskStore
Chat messaging.ChatContract Chat messaging.ChatContract
Health *health.Registry Health *health.Registry
ControlPlane controlpb.ControlPlaneServiceClient
Identities identity.Repository
} }
// compose builds the dashboard server for the UI process. It sets exactly the // compose builds the dashboard server for the UI process. It sets exactly the
@@ -65,6 +69,8 @@ func compose(d deps) *webui.Server {
Token: d.Options.Token, Token: d.Options.Token,
TrustForwardedHeaders: d.Options.trustForwardedHeaders(), TrustForwardedHeaders: d.Options.trustForwardedHeaders(),
Health: d.Health, Health: d.Health,
ControlPlane: d.ControlPlane,
Identities: d.Identities,
} }
if snapshots, ok := d.Store.(storecontract.ConfigSnapshotStore); ok { if snapshots, ok := d.Store.(storecontract.ConfigSnapshotStore); ok {
srv.ConfigSource = webui.RemoteConfigView(snapshots) srv.ConfigSource = webui.RemoteConfigView(snapshots)
-3
View File
@@ -94,9 +94,6 @@ func TestComposeUIServerHoldsNoDaemonState(t *testing.T) {
t.Errorf("%s is wired; it is a daemon-owned callback or runtime handle with no contract behind it yet", name) t.Errorf("%s is wired; it is a daemon-owned callback or runtime handle with no contract behind it yet", name)
} }
} }
if srv.Workflows != nil {
t.Error("Workflows is wired; the definition catalog is a filesystem scan on the daemon host")
}
// Mappings and bindings are the other way round: ratified State Store // Mappings and bindings are the other way round: ratified State Store
// contracts, carried by the client this process already holds, so // contracts, carried by the client this process already holds, so
// leaving them nil would degrade two pages that have an owner. // leaving them nil would degrade two pages that have an owner.
+7 -5
View File
@@ -45,11 +45,13 @@ func Run(ctx context.Context, options Options) error {
cleanups = append(cleanups, closeGateway) cleanups = append(cleanups, closeGateway)
srv := compose(deps{ srv := compose(deps{
Options: opts, Options: opts,
Log: log, Log: log,
Store: tasks, Store: tasks,
Chat: chat, Chat: chat,
Health: newReadinessRegistry(opts, tasks, chat), Health: newReadinessRegistry(opts, tasks, chat),
ControlPlane: tasks.ControlPlane(),
Identities: tasks,
}) })
// Live activity has no in-process bus in this process: the pump reads // Live activity has no in-process bus in this process: the pump reads
@@ -0,0 +1,57 @@
package controlplane
import (
"fmt"
"github.com/samcharles93/archie-core/internal/config"
)
type channelSettings struct {
Operator string `json:"operator"`
ShowToolCalls bool `json:"show_tool_calls"`
MaxSteps int `json:"max_steps"`
Models []string `json:"models"`
Email config.EmailConfig `json:"email"`
WebhookAddr string `json:"webhook_addr"`
Webhook webhookChannelSettings `json:"webhook"`
Telegram telegramSettings `json:"telegram"`
RateLimit config.RateLimitConfig `json:"rate_limit"`
UnrestrictedFilesystem bool `json:"unrestricted_filesystem"`
Workspace string `json:"workspace"`
}
type telegramSettings struct {
AllowedUserIDs []int64 `json:"allowed_user_ids"`
Token config.SecretRef `json:"token_ref"`
TokenEnv string `json:"token_env,omitempty"`
CredentialConfigured bool `json:"credential_configured"`
}
type webhookChannelSettings struct {
Path string `json:"path"`
Secret config.SecretRef `json:"secret_ref"`
CredentialConfigured bool `json:"credential_configured"`
Template string `json:"template"`
DeliverTo string `json:"deliver_to"`
}
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, Models: chat.Models, Email: chat.Email, WebhookAddr: chat.WebhookAddr,
Telegram: telegramSettings{AllowedUserIDs: chat.Telegram.AllowedUserIDs, Token: chat.Telegram.Token, TokenEnv: chat.Telegram.TokenEnv, CredentialConfigured: chat.Telegram.TokenEnv != "" || chat.Telegram.Token != (config.SecretRef{})},
Webhook: webhookChannelSettings{Path: chat.Webhook.Path, Secret: chat.Webhook.Secret, CredentialConfigured: chat.Webhook.Secret != (config.SecretRef{}), Template: chat.Webhook.Template, DeliverTo: chat.Webhook.DeliverTo}, RateLimit: chat.RateLimit,
}
}
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")
}
if settings.Webhook.DeliverTo != "" && settings.Webhook.DeliverTo != "origin" {
return fmt.Errorf("webhook deliver_to must be empty or origin")
}
return nil
})
}
+188
View File
@@ -0,0 +1,188 @@
package controlplane
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
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/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
)
type Client struct{ rpc pb.ControlPlaneServiceClient }
func NewClient(conn grpc.ClientConnInterface) *Client {
return &Client{rpc: pb.NewControlPlaneServiceClient(conn)}
}
func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { return &Client{rpc: client} }
func (c *Client) Catalog(ctx context.Context) ([]*pb.ResourceDescriptor, error) {
response, err := c.rpc.Catalog(ctx, &pb.CatalogRequest{})
if err != nil {
return nil, clientError(err)
}
return response.Resources, nil
}
func (c *Client) WorkflowDefinitions(ctx context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: WorkflowDefinitionsKind})
if err != nil {
return workflow.WorkflowDefinitionCollection{}, 0, clientError(err)
}
definitions, err := workflow.DecodeDefinitionCollection(response.Resource.ValueJson, workflow.BuiltinStepRegistry())
return definitions, response.Resource.Version, err
}
// ReplaceWorkflowDefinitions replaces the collection. Passing
// workflow.ShippedDefinitions() restores all shipped definitions while keeping
// the previous override in resource history.
func (c *Client) ReplaceWorkflowDefinitions(ctx context.Context, definitions workflow.WorkflowDefinitionCollection, expectedVersion int64, actor, source, requestID string) (int64, error) {
value, err := encodeWorkflowDefinitions(definitions)
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, 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, 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, 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, clientError(err)
}
out := make(chan AppliedSettings)
go func() {
defer close(out)
for {
response, err := stream.Recv()
if err != nil {
if !errors.Is(err, io.EOF) && ctx.Err() == nil {
out <- AppliedSettings{Err: clientError(err)}
}
return
}
settings, err := decodeSettings(response.Resource.ValueJson)
out <- AppliedSettings{Settings: settings, Version: response.Resource.Version, Err: err}
}
}()
return out, nil
}
type AppliedSettings struct {
Settings workflow.ExecutionSettings
Version int64
Err error
}
func (c *Client) Personas(ctx context.Context) (agent.PersonaCollection, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: PersonasKind})
if err != nil {
return agent.PersonaCollection{}, 0, clientError(err)
}
collection, err := decodePersonas(response.Resource.ValueJson)
return collection, response.Resource.Version, err
}
type AppliedPersonas struct {
Collection agent.PersonaCollection
Version int64
Err error
}
func (c *Client) WatchPersonas(ctx context.Context, afterVersion int64) (<-chan AppliedPersonas, error) {
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: PersonasKind, AfterVersion: afterVersion})
if err != nil {
return nil, clientError(err)
}
out := make(chan AppliedPersonas)
go func() {
defer close(out)
for {
response, err := stream.Recv()
if err != nil {
if !errors.Is(err, io.EOF) && ctx.Err() == nil {
out <- AppliedPersonas{Err: clientError(err)}
}
return
}
collection, err := decodePersonas(response.Resource.ValueJson)
out <- AppliedPersonas{Collection: collection, Version: response.Resource.Version, Err: err}
}
}()
return out, nil
}
func (c *Client) Schedules(ctx context.Context) ([]cronstore.JobSpec, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SchedulesKind})
if err != nil {
return nil, 0, clientError(err)
}
var jobs []cronstore.JobSpec
if err := json.Unmarshal(response.Resource.ValueJson, &jobs); err != nil {
return nil, 0, err
}
return jobs, response.Resource.Version, nil
}
func (c *Client) ReplaceSchedules(ctx context.Context, jobs []cronstore.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, clientError(err)
}
return response.Resource.Version, nil
}
func clientError(err error) error {
switch status.Code(err) {
case codes.InvalidArgument:
return fmt.Errorf("%w: %w", ErrValidation, err)
case codes.NotFound:
return fmt.Errorf("%w: %w", ErrNotFound, err)
case codes.Aborted:
return fmt.Errorf("%w: %w", ErrVersionConflict, err)
case codes.Unavailable:
return fmt.Errorf("%w: %w", ErrUnavailable, err)
default:
return err
}
}
+131
View File
@@ -0,0 +1,131 @@
// Package controlplane owns control-plane resource registration, dispatch, and validation.
package controlplane
import (
"context"
"errors"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/store"
)
var (
ErrValidation = errors.New("control-plane validation")
ErrNotFound = errors.New("control-plane resource not found")
ErrVersionConflict = errors.New("control-plane version conflict")
ErrUnavailable = errors.New("control-plane unavailable")
)
type resourceStore interface {
Resource(context.Context, string) (store.Resource, error)
PutResource(context.Context, store.ResourceWrite) (store.Resource, error)
}
type Server struct {
pb.UnimplementedControlPlaneServiceServer
store resourceStore
definitions map[string]Definition
ordered []Definition
}
func NewServer(resources resourceStore) *Server {
definitions := builtinDefinitions()
byKind := make(map[string]Definition, len(definitions))
for _, definition := range definitions {
byKind[definition.Kind] = definition
}
return &Server{store: resources, definitions: byKind, ordered: definitions}
}
func (s *Server) Catalog(context.Context, *pb.CatalogRequest) (*pb.CatalogResponse, error) {
descriptors := make([]*pb.ResourceDescriptor, 0, len(s.ordered)+len(domainManagedDescriptors()))
for _, definition := range s.ordered {
descriptors = append(descriptors, definition.Descriptor())
}
descriptors = append(descriptors, domainManagedDescriptors()...)
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.store.Resource(ctx, request.Kind)
if err != nil {
return nil, mapError(err)
}
return &pb.QueryResponse{Resource: resourceProto(resource)}, nil
}
func (s *Server) Command(ctx context.Context, request *pb.CommandRequest) (*pb.CommandResponse, error) {
definition, ok := s.definitions[request.GetKind()]
if !ok || request.GetCommand() != "replace" {
return nil, status.Error(codes.NotFound, "resource or command not found")
}
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)
}
resource, err := s.store.PutResource(ctx, store.ResourceWrite{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.store.Resource(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, store.ErrResourceNotFound) {
return mapError(err)
}
select {
case <-stream.Context().Done():
return stream.Context().Err()
case <-ticker.C:
}
}
}
func resourceProto(resource store.Resource) *pb.Resource {
return &pb.Resource{Kind: resource.Kind, Version: resource.Version, ValueJson: resource.Value, UpdatedAt: timestamp(resource.At)}
}
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, store.ErrResourceNotFound):
return status.Error(codes.NotFound, err.Error())
case errors.Is(err, store.ErrResourceVersionConflict):
return status.Error(codes.Aborted, err.Error())
default:
return status.Error(codes.Unavailable, err.Error())
}
}
@@ -0,0 +1,202 @@
package controlplane
import (
"context"
"encoding/json"
"testing"
"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/agent"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/store"
)
func TestCatalogCarriesShippedWorkflowDefinitionsForRestore(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
catalog, err := NewServer(resources).Catalog(t.Context(), &pb.CatalogRequest{})
if err != nil {
t.Fatal(err)
}
var defaults string
for _, resource := range catalog.Resources {
if resource.Kind == WorkflowDefinitionsKind {
defaults = resource.DefaultsJson
}
}
if defaults == "" {
t.Fatal("workflow-definitions descriptor carries no defaults")
}
collection, err := workflow.DecodeDefinitionCollection([]byte(defaults), workflow.BuiltinStepRegistry())
if err != nil {
t.Fatal(err)
}
if _, ok := collection.DefinitionByID("remediate"); !ok {
t.Fatalf("shipped defaults = %#v", collection.Definitions)
}
}
func TestImportConfigSeedsWorkflowDefinitionsWithoutOverwritingOverride(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
resource, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
if err != nil {
t.Fatal(err)
}
definitions, err := workflow.DecodeDefinitionCollection(resource.Value, workflow.BuiltinStepRegistry())
if err != nil {
t.Fatal(err)
}
if _, ok := definitions.DefinitionByID("remediate"); !ok {
t.Fatal("seeded definitions omit remediate")
}
custom := workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: "id: custom\nsteps:\n - type: bootstrap.apply\n"}}}
value, err := encodeWorkflowDefinitions(custom)
if err != nil {
t.Fatal(err)
}
if _, err := resources.PutResource(t.Context(), store.ResourceWrite{Kind: WorkflowDefinitionsKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "override"}); err != nil {
t.Fatal(err)
}
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
got, err := resources.Resource(t.Context(), WorkflowDefinitionsKind)
if err != nil {
t.Fatal(err)
}
if got.Version != 2 {
t.Fatalf("version after reimport = %d, want 2", got.Version)
}
}
func TestImportConfigSeedsPersonasWithoutOverwritingEdits(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
resource, err := resources.Resource(t.Context(), PersonasKind)
if err != nil {
t.Fatal(err)
}
collection, err := decodePersonas(resource.Value)
if err != nil || len(collection.Personas) != len(agent.ShippedPersonas().Personas) {
t.Fatalf("seeded personas = %+v, %v", collection, err)
}
collection.Personas[0].Prompt = "edited"
value, err := json.Marshal(collection)
if err != nil {
t.Fatal(err)
}
if _, err := resources.PutResource(t.Context(), store.ResourceWrite{Kind: PersonasKind, Value: value, ExpectedVersion: resource.Version, Actor: "test", Source: "test", RequestID: "persona-edit"}); err != nil {
t.Fatal(err)
}
if _, err := server.ImportConfig(t.Context(), config.Config{}); err != nil {
t.Fatal(err)
}
got, err := resources.Resource(t.Context(), PersonasKind)
if err != nil {
t.Fatal(err)
}
updated, err := decodePersonas(got.Value)
if err != nil || updated.Personas[0].Prompt != "edited" || got.Version != 2 {
t.Fatalf("personas after reimport = %+v (version %d), %v", updated, got.Version, err)
}
}
func TestImportWorkflowExecutionSettingsDoesNotOverwriteExistingValue(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
first := workflow.ExecutionSettings{MaxModelToolSteps: 10, MaxRuntime: time.Minute, MaxConsecutiveGateFailures: 2}
if _, err := server.ImportWorkflowExecutionSettings(t.Context(), first); err != nil {
t.Fatal(err)
}
if _, err := server.ImportWorkflowExecutionSettings(t.Context(), workflow.ExecutionSettings{MaxModelToolSteps: 99, MaxRuntime: time.Hour, MaxConsecutiveGateFailures: 9}); err != nil {
t.Fatal(err)
}
resource, err := resources.Resource(t.Context(), WorkflowExecutionSettingsKind)
if err != nil {
t.Fatal(err)
}
got, err := decodeSettings(resource.Value)
if err != nil {
t.Fatal(err)
}
if got != first || resource.Version != 1 {
t.Fatalf("imported settings = (%+v, version %d), want (%+v, version 1)", got, resource.Version, first)
}
}
func TestRegistryRoutesAndValidatesDefinitions(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
if _, err := server.ImportConfig(t.Context(), config.Config{Containers: config.ContainerConfig{PullPolicy: "missing"}}); err != nil {
t.Fatal(err)
}
catalog, err := server.Catalog(t.Context(), &pb.CatalogRequest{})
if err != nil {
t.Fatal(err)
}
found := false
for _, descriptor := range catalog.Resources {
if descriptor.Kind == ContainerRuntimePoliciesKind {
found = descriptor.ApplyMode == "restart-required"
}
}
if !found {
t.Fatal("container runtime policies missing restart-required descriptor")
}
_, err = server.Command(t.Context(), &pb.CommandRequest{Kind: ContainerRuntimePoliciesKind, Command: "replace", ValueJson: []byte(`{"pull_policy":"sometimes"}`), Actor: "test", Source: "test", RequestId: "bad", ExpectedVersion: 1})
if err == nil {
t.Fatal("invalid pull policy accepted")
}
}
func TestProviderSeedKeepsReferencesAndNeverResolvedSecrets(t *testing.T) {
t.Parallel()
resources := store.OpenTest(t)
defer resources.Close()
server := NewServer(resources)
cfg := config.Config{Providers: map[string]config.Provider{"openai": {Class: "openai", APIKeyEnv: "OPENAI_API_KEY", APIKey: config.SecretRef{Engine: "env", Key: "OPENAI_API_KEY"}}}}
if _, err := server.ImportConfig(context.Background(), cfg); err != nil {
t.Fatal(err)
}
resource, err := resources.Resource(t.Context(), ProviderSettingsKind)
if err != nil {
t.Fatal(err)
}
var value map[string]any
if err := json.Unmarshal(resource.Value, &value); err != nil {
t.Fatal(err)
}
encoded := string(resource.Value)
if encoded == "" || !json.Valid(resource.Value) {
t.Fatalf("provider resource = %q", encoded)
}
if _, ok := value["openai"]; !ok {
t.Fatalf("provider resource = %s", encoded)
}
}
+25
View File
@@ -0,0 +1,25 @@
package controlplane
import pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
const (
objectSchema = `{"type":"object"}`
arraySchema = `{"type":"array"}`
)
func builtinDefinitions() []Definition {
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(), personaDefinition(), scheduleDefinition()}
definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...)
return definitions
}
func domainManagedDescriptors() []*pb.ResourceDescriptor {
const stateService = "state.v1.StateStoreService"
return []*pb.ResourceDescriptor{
{Kind: "identities", Title: "Identities", ApplyMode: "domain-managed", QueryService: stateService + "/ListIdentities,GetIdentity", CommandService: stateService + "/CreateIdentity,RenameIdentity,SuspendIdentity,ReactivateIdentity,RetireIdentity"},
{Kind: "capture-events", Title: "Captured events", ApplyMode: "domain-managed", QueryService: stateService + "/StreamCaptures", CommandService: stateService + "/InsertCapture"},
{Kind: "capture-mappings", Title: "Capture mappings", ApplyMode: "domain-managed", QueryService: stateService + "/ListMappings", CommandService: stateService + "/InsertMapping,UpdateMapping,DeleteMapping"},
{Kind: "capture-bindings", Title: "Capture bindings", ApplyMode: "domain-managed", QueryService: stateService + "/ListBindings", CommandService: stateService + "/InsertBinding,UpdateBinding,DeleteBinding"},
}
}
@@ -0,0 +1,65 @@
package controlplane
import (
"fmt"
"net/url"
"strings"
"github.com/samcharles93/archie-core/internal/config"
)
const (
ProviderSettingsKind = "provider-settings"
ModelRoleAssignmentsKind = "model-role-assignments"
)
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: "restart-required", Schema: objectSchema, Seed: seedProviders, Validate: validateProviders},
{Kind: ModelRoleAssignmentsKind, Title: "Model role assignments", ApplyMode: "restart-required", Schema: objectSchema, Seed: func(cfg config.Config) any { return cfg.Models }, Validate: validateModelRoles},
}
}
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 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 validateModelRoles(input []byte) error {
return validateAs(input, func(models map[string]string) error {
for role, model := range models {
if strings.TrimSpace(role) == "" || !strings.Contains(model, "/") {
return fmt.Errorf("model role %q must reference provider/model", role)
}
}
return nil
})
}
@@ -0,0 +1,89 @@
package controlplane
import (
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
)
const (
RepositoryPoliciesKind = "repository-policies"
ChannelSettingsKind = "channel-settings"
SchedulingPolicyKind = "scheduling-policy"
ToolSettingsKind = "tool-settings"
PluginSettingsKind = "plugin-settings"
ContainerRuntimePoliciesKind = "container-runtime-policies"
)
type schedulingPolicy struct {
PollInterval string `json:"poll_interval"`
MaxRetries int `json:"max_retries"`
Dispatch config.Dispatch `json:"dispatch"`
}
type pluginSettings struct {
PluginDir string `json:"plugin_dir"`
ModuleDir string `json:"module_dir"`
SecretEngineDir string `json:"secret_engine_dir"`
SkillsDir string `json:"skills_dir"`
}
func operationalDefinitions() []Definition {
return []Definition{
{Kind: RepositoryPoliciesKind, Title: "Repository policies", ApplyMode: "restart-required", Schema: arraySchema, Seed: func(cfg config.Config) any { return cfg.Repos }, Validate: validateRepositories},
{Kind: ChannelSettingsKind, Title: "Channel settings", ApplyMode: "restart-required", Schema: objectSchema, Seed: seedChannels, Validate: validateChannels},
{Kind: SchedulingPolicyKind, Title: "Scheduling policy", ApplyMode: "restart-required", Schema: objectSchema, Seed: func(cfg config.Config) any {
return schedulingPolicy{cfg.PollInterval.Std().String(), cfg.MaxRetries, cfg.Dispatch}
}, Validate: validateScheduling},
{Kind: ToolSettingsKind, Title: "Tool and MCP settings", ApplyMode: "restart-required", Schema: objectSchema, Seed: seedTools, Validate: validateTools},
{Kind: PluginSettingsKind, Title: "Plugin settings", ApplyMode: "restart-required", Schema: objectSchema, Seed: func(cfg config.Config) any {
return pluginSettings{cfg.PluginDir, cfg.ModuleDir, cfg.SecretEngineDir, cfg.SkillsDir}
}, Validate: func(input []byte) error { return validateAs(input, func(pluginSettings) error { return nil }) }},
{Kind: ContainerRuntimePoliciesKind, Title: "Container runtime policies", ApplyMode: "restart-required", Schema: objectSchema, Seed: func(cfg config.Config) any { return cfg.Containers }, Validate: validateContainers},
}
}
func validateRepositories(input []byte) error {
return validateAs(input, func(repos []config.Repo) error {
seen := make(map[string]struct{}, len(repos))
for _, repo := range repos {
if strings.TrimSpace(repo.Owner) == "" || strings.TrimSpace(repo.Name) == "" {
return fmt.Errorf("repository owner and name are required")
}
if _, exists := seen[repo.FullName()]; exists {
return fmt.Errorf("duplicate repository %q", repo.FullName())
}
seen[repo.FullName()] = struct{}{}
}
return nil
})
}
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")
}
if policy.PollInterval != "0s" {
interval, err := time.ParseDuration(policy.PollInterval)
if err != nil || interval < 0 {
return fmt.Errorf("poll_interval must be a non-negative duration")
}
}
return nil
})
}
func validateContainers(input []byte) error {
return validateAs(input, func(settings config.ContainerConfig) error {
if settings.MaxConcurrency < 0 || time.Duration(settings.MaxUptime) < 0 || time.Duration(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")
}
return nil
})
}
+29
View File
@@ -0,0 +1,29 @@
package controlplane
import (
"encoding/json"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agent"
)
const PersonasKind = "personas"
func personaDefinition() Definition {
return Definition{
Kind: PersonasKind,
Title: "Personas",
Schema: objectSchema,
ApplyMode: "live",
Seed: func(config.Config) any { return agent.ShippedPersonas() },
Validate: func(input []byte) error {
return validateAs(input, func(collection agent.PersonaCollection) error { return collection.Validate() })
},
}
}
func decodePersonas(input []byte) (agent.PersonaCollection, error) {
var collection agent.PersonaCollection
err := json.Unmarshal(input, &collection)
return collection, err
}
+100
View File
@@ -0,0 +1,100 @@
package controlplane
import (
"bytes"
"context"
"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/store"
)
type Definition struct {
Kind string
Title string
Schema string
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
}
func (d Definition) Descriptor() *pb.ResourceDescriptor {
descriptor := &pb.ResourceDescriptor{Kind: d.Kind, Title: d.Title, SchemaJson: d.Schema, 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
}
func (s *Server) ImportConfig(ctx context.Context, cfg config.Config) (map[string]int64, error) {
versions := make(map[string]int64, len(s.ordered))
for _, definition := range s.ordered {
resource, err := s.store.Resource(ctx, definition.Kind)
if err == nil {
versions[definition.Kind] = resource.Version
continue
}
if !errors.Is(err, store.ErrResourceNotFound) {
return nil, err
}
value, err := json.Marshal(definition.Seed(cfg))
if err != nil {
return nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
value, err = definition.Decode(value)
if err != nil {
return nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
resource, err = s.store.PutResource(ctx, store.ResourceWrite{Kind: definition.Kind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + definition.Kind, ExpectedVersion: 0, At: time.Now().UTC()})
if err != nil {
return nil, fmt.Errorf("seed %s: %w", definition.Kind, err)
}
versions[definition.Kind] = resource.Version
}
return versions, nil
}
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)
}
+131
View File
@@ -0,0 +1,131 @@
package controlplane
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
)
// RuntimeConfig applies restart-scoped database resources over bootstrap
// configuration. Values intentionally absent from a control-plane projection,
// such as secret-bearing MCP headers and channel update commands, remain
// bootstrap-owned.
func (c *Client) RuntimeConfig(ctx context.Context, base config.Config) (config.Config, error) {
out := base.Clone()
if err := c.query(ctx, ProviderSettingsKind, func(value []byte) error {
var providers map[string]providerDocument
if err := json.Unmarshal(value, &providers); err != nil {
return err
}
out.Providers = make(map[string]config.Provider, len(providers))
for name, provider := range providers {
out.Providers[name] = config.Provider{Class: provider.Class, APIKeyEnv: provider.APIKeyEnv, APIKey: provider.APIKey, BaseURL: provider.BaseURL}
}
return nil
}); err != nil {
return config.Config{}, err
}
if err := c.queryJSON(ctx, ModelRoleAssignmentsKind, &out.Models); err != nil {
return config.Config{}, err
}
if err := c.queryJSON(ctx, RepositoryPoliciesKind, &out.Repos); err != nil {
return config.Config{}, err
}
chat, err := c.RuntimeChatConfig(ctx, out.Chat)
if err != nil {
return config.Config{}, err
}
out.Chat = chat
if err := c.query(ctx, SchedulingPolicyKind, func(value []byte) error {
var policy schedulingPolicy
if err := json.Unmarshal(value, &policy); err != nil {
return err
}
interval, err := time.ParseDuration(policy.PollInterval)
if err != nil {
return err
}
out.PollInterval, out.MaxRetries, out.Dispatch = config.Duration(interval), policy.MaxRetries, policy.Dispatch
return nil
}); err != nil {
return config.Config{}, err
}
return c.runtimeToolConfig(ctx, out)
}
func (c *Client) runtimeToolConfig(ctx context.Context, out config.Config) (config.Config, error) {
if err := c.query(ctx, ToolSettingsKind, func(value []byte) error {
var settings toolSettings
if err := json.Unmarshal(value, &settings); err != nil {
return err
}
headers := make(map[string]map[string]string, len(out.Tools.MCPServers))
for _, server := range out.Tools.MCPServers {
headers[server.Name] = server.Headers
}
servers := make([]config.MCPServer, 0, len(settings.MCPServers))
for _, server := range settings.MCPServers {
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})
}
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{}, err
}
if err := c.query(ctx, PluginSettingsKind, func(value []byte) error {
var settings pluginSettings
if err := json.Unmarshal(value, &settings); err != nil {
return err
}
out.PluginDir, out.ModuleDir, out.SecretEngineDir, out.SkillsDir = settings.PluginDir, settings.ModuleDir, settings.SecretEngineDir, settings.SkillsDir
return nil
}); err != nil {
return config.Config{}, err
}
if err := c.queryJSON(ctx, ContainerRuntimePoliciesKind, &out.Containers); err != nil {
return config.Config{}, err
}
return out, nil
}
func (c *Client) RuntimeChatConfig(ctx context.Context, base config.ChatConfig) (config.ChatConfig, error) {
out := base
err := c.query(ctx, ChannelSettingsKind, func(value []byte) error {
var settings channelSettings
if err := json.Unmarshal(value, &settings); err != nil {
return err
}
check, install := base.Telegram.UpdateCheckCommand, base.Telegram.UpdateInstallCommand
out = config.ChatConfig{
Operator: settings.Operator, ShowToolCalls: settings.ShowToolCalls, MaxSteps: settings.MaxSteps,
Models: settings.Models, Email: settings.Email, WebhookAddr: settings.WebhookAddr,
Webhook: config.WebhookRoute{Path: settings.Webhook.Path, Secret: settings.Webhook.Secret, Template: settings.Webhook.Template, DeliverTo: settings.Webhook.DeliverTo},
Telegram: config.TelegramConfig{AllowedUserIDs: settings.Telegram.AllowedUserIDs, Token: settings.Telegram.Token, TokenEnv: settings.Telegram.TokenEnv, UpdateCheckCommand: check, UpdateInstallCommand: install},
RateLimit: settings.RateLimit, UnrestrictedFilesystem: settings.UnrestrictedFilesystem, Workspace: settings.Workspace,
}
return nil
})
return out, err
}
func (c *Client) queryJSON(ctx context.Context, kind string, target any) error {
return c.query(ctx, kind, func(value []byte) error { return json.Unmarshal(value, target) })
}
func (c *Client) query(ctx context.Context, kind string, decode func([]byte) error) error {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: kind})
if err != nil {
return clientError(err)
}
if response.Resource == nil {
return fmt.Errorf("%s resource missing", kind)
}
if err := decode(response.Resource.ValueJson); err != nil {
return fmt.Errorf("decode %s: %w", kind, err)
}
return nil
}
@@ -0,0 +1,67 @@
package controlplane
import (
"context"
"encoding/json"
"testing"
"google.golang.org/grpc"
"github.com/samcharles93/archie-core/internal/config"
pb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
)
type runtimeConfigClient struct{ values map[string]any }
func (*runtimeConfigClient) Catalog(context.Context, *pb.CatalogRequest, ...grpc.CallOption) (*pb.CatalogResponse, error) {
return &pb.CatalogResponse{}, nil
}
func (c *runtimeConfigClient) Query(_ context.Context, request *pb.QueryRequest, _ ...grpc.CallOption) (*pb.QueryResponse, error) {
value, err := json.Marshal(c.values[request.Kind])
return &pb.QueryResponse{Resource: &pb.Resource{Kind: request.Kind, Version: 2, ValueJson: value}}, err
}
func (*runtimeConfigClient) Command(context.Context, *pb.CommandRequest, ...grpc.CallOption) (*pb.CommandResponse, error) {
panic("unexpected Command")
}
func (*runtimeConfigClient) Watch(context.Context, *pb.WatchRequest, ...grpc.CallOption) (grpc.ServerStreamingClient[pb.WatchResponse], error) {
panic("unexpected Watch")
}
func TestRuntimeConfigUsesDatabaseResourcesAndPreservesBootstrapOnlySecrets(t *testing.T) {
base := config.Config{
Providers: map[string]config.Provider{"old": {Class: "openai"}},
Models: map[string]string{"builder": "old/model"},
Repos: []config.Repo{{Owner: "old", Name: "repo"}},
Chat: config.ChatConfig{Telegram: config.TelegramConfig{
UpdateCheckCommand: []string{"check"}, UpdateInstallCommand: []string{"install"},
}},
Tools: config.ToolsConfig{MCPServers: []config.MCPServer{{Name: "docs", Headers: map[string]string{"Authorization": "secret"}}}},
}
client := NewRPCClient(&runtimeConfigClient{values: map[string]any{
ProviderSettingsKind: map[string]any{"main": map[string]any{"class": "openai", "base_url": "https://api.example.com", "api_key_ref": map[string]any{"engine": "env", "key": "API_KEY"}, "has_credential": true}},
ModelRoleAssignmentsKind: map[string]string{"builder": "main/model"},
RepositoryPoliciesKind: []config.Repo{{Owner: "acme", Name: "widget"}},
ChannelSettingsKind: map[string]any{"operator": "Sam", "show_tool_calls": true, "max_steps": 20, "models": []string{"main/model"}, "email": map[string]any{}, "webhook_addr": "", "webhook": map[string]any{}, "telegram": map[string]any{"allowed_user_ids": []int64{42}, "credential_configured": false}, "rate_limit": map[string]any{}, "unrestricted_filesystem": false, "workspace": "/workspace"},
SchedulingPolicyKind: map[string]any{"poll_interval": "2m", "max_retries": 7, "dispatch": map[string]any{"trigger": "assignee"}},
ToolSettingsKind: map[string]any{"mcp_servers": []map[string]any{{"name": "docs", "transport": "http", "url": "https://mcp.example.com", "headers_configured": true}}, "policy": map[string]any{}, "web_fetch": map[string]any{}, "minimax": map[string]any{"enabled": false, "credential_configured": false}},
PluginSettingsKind: map[string]any{"plugin_dir": "/plugins", "module_dir": "/modules", "secret_engine_dir": "/secrets", "skills_dir": "/skills"},
ContainerRuntimePoliciesKind: config.ContainerConfig{LegacyEnabled: true, Image: "archie:next", PullPolicy: "missing"},
}})
got, err := client.RuntimeConfig(t.Context(), base)
if err != nil {
t.Fatalf("RuntimeConfig: %v", err)
}
if got.Models["builder"] != "main/model" || got.Repos[0].FullName() != "acme/widget" || got.MaxRetries != 7 || got.PluginDir != "/plugins" || got.Containers.Image != "archie:next" {
t.Fatalf("database settings not applied: %+v", got)
}
if got.Chat.Operator != "Sam" || got.Chat.Telegram.AllowedUserIDs[0] != 42 {
t.Fatalf("channel settings not applied: %+v", got.Chat)
}
if got.Chat.Telegram.UpdateCheckCommand[0] != "check" || got.Tools.MCPServers[0].Headers["Authorization"] != "secret" {
t.Fatalf("bootstrap-only secret-backed settings were dropped: chat=%+v tools=%+v", got.Chat, got.Tools)
}
}
+74
View File
@@ -0,0 +1,74 @@
package controlplane
import (
"encoding/json"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/scheduling"
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
)
const SchedulesKind = "schedules"
func scheduleDefinition() Definition {
return Definition{
Kind: SchedulesKind,
Title: "Schedules",
Schema: arraySchema,
ApplyMode: "live",
Seed: func(config.Config) any { return []cronstore.JobSpec{} },
Validate: func(input []byte) error {
return validateAs(input, validateSchedules)
},
Normalize: normalizeSchedules,
}
}
func validateSchedules(jobs []cronstore.JobSpec) error {
seen := make(map[string]struct{}, len(jobs))
for _, job := range jobs {
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{}{}
if job.Kind != cronstore.KindWorkflow {
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 []cronstore.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,38 @@
package controlplane
import (
"encoding/json"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/infrastructure/cronstore"
)
func TestScheduleDefinitionComputesFirstRunAndRejectsDuplicateIDs(t *testing.T) {
t.Parallel()
definition := scheduleDefinition()
jobs := []cronstore.JobSpec{{ID: "daily", Kind: cronstore.KindWorkflow, Schedule: cronstore.Schedule{Kind: cronstore.ScheduleInterval, Interval: time.Hour}}}
input, err := json.Marshal(jobs)
if err != nil {
t.Fatal(err)
}
got, err := definition.Decode(input)
if err != nil {
t.Fatal(err)
}
var normalized []cronstore.JobSpec
if err := json.Unmarshal(got, &normalized); err != nil {
t.Fatal(err)
}
if len(normalized) != 1 || normalized[0].NextRun.IsZero() || normalized[0].Created.IsZero() || normalized[0].Updated.IsZero() {
t.Fatalf("normalized schedules = %+v", normalized)
}
duplicate, err := json.Marshal(append(jobs, jobs[0]))
if err != nil {
t.Fatal(err)
}
if _, err := definition.Decode(duplicate); err == nil {
t.Fatal("duplicate schedule IDs accepted")
}
}
@@ -0,0 +1,70 @@
package controlplane
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"`
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 {
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, 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,37 @@
package controlplane
import (
"encoding/json"
"fmt"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
const WorkflowDefinitionsKind = "workflow-definitions"
func workflowDefinitionsDefinition() Definition {
return Definition{
Kind: WorkflowDefinitionsKind,
Title: "Workflow definitions",
Schema: objectSchema,
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, workflow.BuiltinStepRegistry())
return err
},
}
}
func encodeWorkflowDefinitions(collection workflow.WorkflowDefinitionCollection) ([]byte, error) {
if err := workflow.ValidateDefinitionCollection(collection, workflow.BuiltinStepRegistry()); err != nil {
return nil, fmt.Errorf("%w: %w", ErrValidation, err)
}
return json.Marshal(collection)
}
@@ -0,0 +1,69 @@
package controlplane
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/store"
)
const WorkflowExecutionSettingsKind = "workflow-execution-settings"
type executionSettingsDocument struct {
MaxModelToolSteps int `json:"max_model_tool_steps"`
MaxRuntimeSeconds int64 `json:"max_runtime_seconds"`
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
}
// ImportWorkflowExecutionSettings preserves the focused bootstrap API for callers
// that do not own the complete legacy configuration document.
func (s *Server) ImportWorkflowExecutionSettings(ctx context.Context, settings workflow.ExecutionSettings) (int64, error) {
resource, err := s.store.Resource(ctx, WorkflowExecutionSettingsKind)
if err == nil {
return resource.Version, nil
}
if !errors.Is(err, store.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, store.ResourceWrite{Kind: WorkflowExecutionSettingsKind, Value: value, Actor: "system:migration", Source: "legacy-config", RequestID: "import:" + WorkflowExecutionSettingsKind, ExpectedVersion: 0, At: time.Now().UTC()})
return resource.Version, err
}
func workflowDefinition() Definition {
return Definition{
Kind: WorkflowExecutionSettingsKind, Title: "Workflow execution settings", ApplyMode: "live", Schema: objectSchema,
Seed: func(cfg config.Config) any {
return executionSettingsDocument{cfg.Budgets.MaxSteps, int64(time.Duration(cfg.Budgets.WallClock) / time.Second), cfg.Budgets.GateMaxFailures}
},
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})
}
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)
}
settings := workflow.ExecutionSettings{MaxModelToolSteps: document.MaxModelToolSteps, MaxRuntime: time.Duration(document.MaxRuntimeSeconds) * time.Second, MaxConsecutiveGateFailures: document.MaxConsecutiveGateFailures}
if err := settings.Validate(); err != nil {
return workflow.ExecutionSettings{}, fmt.Errorf("%w: %w", ErrValidation, err)
}
return settings, nil
}
+1
View File
@@ -26,6 +26,7 @@ var gatewayCommandSpecs = []commandSpec{
{Command: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"}, {Command: "model", Description: "Choose a provider and model or switch directly", Usage: "/model [provider/model]"},
{Command: "personality", Description: "Choose a communication style", Usage: "/personality [name]"}, {Command: "personality", Description: "Choose a communication style", Usage: "/personality [name]"},
{Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"}, {Command: "spawn", Description: "Create a tracked task", Usage: "/spawn [identity=name] [repo=owner/name] [workflow=name] <title>"},
{Command: "settings", Description: "Inspect or change runtime settings", Usage: "/settings [list|get <kind>|set <kind> <field>=<value> ...]"},
{Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"}, {Command: "cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel [identity=name] <task-id>"},
{Command: "start", Description: "Confirm that Archie is running", Usage: "/start"}, {Command: "start", Description: "Confirm that Archie is running", Usage: "/start"},
{Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"}, {Command: "new", Description: "Start a fresh session, clearing conversation history", Usage: "/new [title]"},
+22
View File
@@ -48,6 +48,11 @@ type Gateway struct {
// Updates is injected by the composition root. It owns release discovery, // Updates is injected by the composition root. It owns release discovery,
// deferral persistence, and installation; Telegram only presents it. // deferral persistence, and installation; Telegram only presents it.
Updates UpdateService Updates UpdateService
// Settings executes control-plane commands in this authenticated adapter.
Settings *messaging.SettingsCommand
// ResolveActor maps a channel-native sender to an authenticated Archie
// identity. Nil deliberately permits reads but makes writes fail closed.
ResolveActor func(int64) (string, bool)
// UpdateReportPath is where the update watchdog (see // UpdateReportPath is where the update watchdog (see
// scripts/archie-update-watchdog) leaves the phase-2 outcome of an // scripts/archie-update-watchdog) leaves the phase-2 outcome of an
@@ -254,6 +259,7 @@ func (g *Gateway) registerCommandHandlers(b *bot.Bot, client messaging.ChatContr
b.RegisterHandler(bot.HandlerTypeMessageText, "/agents", bot.MatchTypeExact, g.agentsHandler(client)) b.RegisterHandler(bot.HandlerTypeMessageText, "/agents", bot.MatchTypeExact, g.agentsHandler(client))
b.RegisterHandler(bot.HandlerTypeMessageText, "/version", bot.MatchTypeExact, g.versionHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/version", bot.MatchTypeExact, g.versionHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/update", bot.MatchTypeExact, g.updateHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/update", bot.MatchTypeExact, g.updateHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/settings", bot.MatchTypePrefix, g.settingsHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/start", bot.MatchTypeExact, g.startHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/help", bot.MatchTypeExact, g.helpHandler())
b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler()) b.RegisterHandler(bot.HandlerTypeMessageText, "/restart", bot.MatchTypeExact, g.restartHandler())
@@ -442,6 +448,22 @@ func (g *Gateway) routeCmdHandler(client messaging.ChatContract, cmd string) bot
} }
} }
func (g *Gateway) settingsHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update)
if !ok {
return
}
actor := ""
if g.ResolveActor != nil {
actor, _ = g.ResolveActor(msg.From.ID)
}
input := strings.TrimSpace(strings.TrimPrefix(msg.Text, "/settings"))
reply := g.Settings.Execute(ctx, actor, input)
g.sendMessage(ctx, b, msg.Chat.ID, msg.MessageThreadID, reply)
}
}
func (g *Gateway) versionHandler() bot.HandlerFunc { func (g *Gateway) versionHandler() bot.HandlerFunc {
return func(ctx context.Context, b *bot.Bot, update *models.Update) { return func(ctx context.Context, b *bot.Bot, update *models.Update) {
msg, ok := g.authorizedMessage(ctx, b, update) msg, ok := g.authorizedMessage(ctx, b, update)
@@ -0,0 +1,732 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc (unknown)
// source: controlplane/v1/controlplane.proto
package controlplanev1
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type ResourceDescriptor struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"`
SchemaJson string `protobuf:"bytes,3,opt,name=schema_json,json=schemaJson,proto3" json:"schema_json,omitempty"`
Commands []string `protobuf:"bytes,4,rep,name=commands,proto3" json:"commands,omitempty"`
// ApplyMode is "live", "restart-required", or "domain-managed".
ApplyMode string `protobuf:"bytes,5,opt,name=apply_mode,json=applyMode,proto3" json:"apply_mode,omitempty"`
// QueryService and command_service identify an existing domain API when
// the resource is not stored as a generic JSON document.
QueryService string `protobuf:"bytes,6,opt,name=query_service,json=queryService,proto3" json:"query_service,omitempty"`
CommandService string `protobuf:"bytes,7,opt,name=command_service,json=commandService,proto3" json:"command_service,omitempty"`
// DefaultsJson is the factory value a client can restore this resource to.
// Empty when the resource has no shipped default.
DefaultsJson string `protobuf:"bytes,8,opt,name=defaults_json,json=defaultsJson,proto3" json:"defaults_json,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *ResourceDescriptor) Reset() {
*x = ResourceDescriptor{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *ResourceDescriptor) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ResourceDescriptor) ProtoMessage() {}
func (x *ResourceDescriptor) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ResourceDescriptor.ProtoReflect.Descriptor instead.
func (*ResourceDescriptor) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{0}
}
func (x *ResourceDescriptor) GetKind() string {
if x != nil {
return x.Kind
}
return ""
}
func (x *ResourceDescriptor) GetTitle() string {
if x != nil {
return x.Title
}
return ""
}
func (x *ResourceDescriptor) GetSchemaJson() string {
if x != nil {
return x.SchemaJson
}
return ""
}
func (x *ResourceDescriptor) GetCommands() []string {
if x != nil {
return x.Commands
}
return nil
}
func (x *ResourceDescriptor) GetApplyMode() string {
if x != nil {
return x.ApplyMode
}
return ""
}
func (x *ResourceDescriptor) GetQueryService() string {
if x != nil {
return x.QueryService
}
return ""
}
func (x *ResourceDescriptor) GetCommandService() string {
if x != nil {
return x.CommandService
}
return ""
}
func (x *ResourceDescriptor) GetDefaultsJson() string {
if x != nil {
return x.DefaultsJson
}
return ""
}
type CatalogRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CatalogRequest) Reset() {
*x = CatalogRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CatalogRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CatalogRequest) ProtoMessage() {}
func (x *CatalogRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CatalogRequest.ProtoReflect.Descriptor instead.
func (*CatalogRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{1}
}
type CatalogResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Resources []*ResourceDescriptor `protobuf:"bytes,1,rep,name=resources,proto3" json:"resources,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CatalogResponse) Reset() {
*x = CatalogResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CatalogResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CatalogResponse) ProtoMessage() {}
func (x *CatalogResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CatalogResponse.ProtoReflect.Descriptor instead.
func (*CatalogResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{2}
}
func (x *CatalogResponse) GetResources() []*ResourceDescriptor {
if x != nil {
return x.Resources
}
return nil
}
type Resource struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"`
ValueJson []byte `protobuf:"bytes,3,opt,name=value_json,json=valueJson,proto3" json:"value_json,omitempty"`
UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Resource) Reset() {
*x = Resource{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Resource) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Resource) ProtoMessage() {}
func (x *Resource) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Resource.ProtoReflect.Descriptor instead.
func (*Resource) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{3}
}
func (x *Resource) GetKind() string {
if x != nil {
return x.Kind
}
return ""
}
func (x *Resource) GetVersion() int64 {
if x != nil {
return x.Version
}
return 0
}
func (x *Resource) GetValueJson() []byte {
if x != nil {
return x.ValueJson
}
return nil
}
func (x *Resource) GetUpdatedAt() *timestamppb.Timestamp {
if x != nil {
return x.UpdatedAt
}
return nil
}
type QueryRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *QueryRequest) Reset() {
*x = QueryRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *QueryRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*QueryRequest) ProtoMessage() {}
func (x *QueryRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use QueryRequest.ProtoReflect.Descriptor instead.
func (*QueryRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{4}
}
func (x *QueryRequest) GetKind() string {
if x != nil {
return x.Kind
}
return ""
}
type QueryResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *QueryResponse) Reset() {
*x = QueryResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *QueryResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*QueryResponse) ProtoMessage() {}
func (x *QueryResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use QueryResponse.ProtoReflect.Descriptor instead.
func (*QueryResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{5}
}
func (x *QueryResponse) GetResource() *Resource {
if x != nil {
return x.Resource
}
return nil
}
type CommandRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
Command string `protobuf:"bytes,2,opt,name=command,proto3" json:"command,omitempty"`
ValueJson []byte `protobuf:"bytes,3,opt,name=value_json,json=valueJson,proto3" json:"value_json,omitempty"`
ExpectedVersion int64 `protobuf:"varint,4,opt,name=expected_version,json=expectedVersion,proto3" json:"expected_version,omitempty"`
RequestId string `protobuf:"bytes,5,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"`
// Actor and source are supplied by a trusted service adapter, never copied
// from browser/request JSON.
Actor string `protobuf:"bytes,6,opt,name=actor,proto3" json:"actor,omitempty"`
Source string `protobuf:"bytes,7,opt,name=source,proto3" json:"source,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CommandRequest) Reset() {
*x = CommandRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CommandRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CommandRequest) ProtoMessage() {}
func (x *CommandRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CommandRequest.ProtoReflect.Descriptor instead.
func (*CommandRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{6}
}
func (x *CommandRequest) GetKind() string {
if x != nil {
return x.Kind
}
return ""
}
func (x *CommandRequest) GetCommand() string {
if x != nil {
return x.Command
}
return ""
}
func (x *CommandRequest) GetValueJson() []byte {
if x != nil {
return x.ValueJson
}
return nil
}
func (x *CommandRequest) GetExpectedVersion() int64 {
if x != nil {
return x.ExpectedVersion
}
return 0
}
func (x *CommandRequest) GetRequestId() string {
if x != nil {
return x.RequestId
}
return ""
}
func (x *CommandRequest) GetActor() string {
if x != nil {
return x.Actor
}
return ""
}
func (x *CommandRequest) GetSource() string {
if x != nil {
return x.Source
}
return ""
}
type CommandResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CommandResponse) Reset() {
*x = CommandResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CommandResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CommandResponse) ProtoMessage() {}
func (x *CommandResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CommandResponse.ProtoReflect.Descriptor instead.
func (*CommandResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{7}
}
func (x *CommandResponse) GetResource() *Resource {
if x != nil {
return x.Resource
}
return nil
}
type WatchRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Kind string `protobuf:"bytes,1,opt,name=kind,proto3" json:"kind,omitempty"`
AfterVersion int64 `protobuf:"varint,2,opt,name=after_version,json=afterVersion,proto3" json:"after_version,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *WatchRequest) Reset() {
*x = WatchRequest{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *WatchRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WatchRequest) ProtoMessage() {}
func (x *WatchRequest) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use WatchRequest.ProtoReflect.Descriptor instead.
func (*WatchRequest) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{8}
}
func (x *WatchRequest) GetKind() string {
if x != nil {
return x.Kind
}
return ""
}
func (x *WatchRequest) GetAfterVersion() int64 {
if x != nil {
return x.AfterVersion
}
return 0
}
type WatchResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
Resource *Resource `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"`
Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *WatchResponse) Reset() {
*x = WatchResponse{}
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *WatchResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*WatchResponse) ProtoMessage() {}
func (x *WatchResponse) ProtoReflect() protoreflect.Message {
mi := &file_controlplane_v1_controlplane_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use WatchResponse.ProtoReflect.Descriptor instead.
func (*WatchResponse) Descriptor() ([]byte, []int) {
return file_controlplane_v1_controlplane_proto_rawDescGZIP(), []int{9}
}
func (x *WatchResponse) GetResource() *Resource {
if x != nil {
return x.Resource
}
return nil
}
func (x *WatchResponse) GetError() string {
if x != nil {
return x.Error
}
return ""
}
var File_controlplane_v1_controlplane_proto protoreflect.FileDescriptor
const file_controlplane_v1_controlplane_proto_rawDesc = "" +
"\n" +
"\"controlplane/v1/controlplane.proto\x12\x0fcontrolplane.v1\x1a\x1fgoogle/protobuf/timestamp.proto\"\x8d\x02\n" +
"\x12ResourceDescriptor\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x14\n" +
"\x05title\x18\x02 \x01(\tR\x05title\x12\x1f\n" +
"\vschema_json\x18\x03 \x01(\tR\n" +
"schemaJson\x12\x1a\n" +
"\bcommands\x18\x04 \x03(\tR\bcommands\x12\x1d\n" +
"\n" +
"apply_mode\x18\x05 \x01(\tR\tapplyMode\x12#\n" +
"\rquery_service\x18\x06 \x01(\tR\fqueryService\x12'\n" +
"\x0fcommand_service\x18\a \x01(\tR\x0ecommandService\x12#\n" +
"\rdefaults_json\x18\b \x01(\tR\fdefaultsJson\"\x10\n" +
"\x0eCatalogRequest\"T\n" +
"\x0fCatalogResponse\x12A\n" +
"\tresources\x18\x01 \x03(\v2#.controlplane.v1.ResourceDescriptorR\tresources\"\x92\x01\n" +
"\bResource\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x18\n" +
"\aversion\x18\x02 \x01(\x03R\aversion\x12\x1d\n" +
"\n" +
"value_json\x18\x03 \x01(\fR\tvalueJson\x129\n" +
"\n" +
"updated_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\"\n" +
"\fQueryRequest\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\"F\n" +
"\rQueryResponse\x125\n" +
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\"\xd5\x01\n" +
"\x0eCommandRequest\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12\x18\n" +
"\acommand\x18\x02 \x01(\tR\acommand\x12\x1d\n" +
"\n" +
"value_json\x18\x03 \x01(\fR\tvalueJson\x12)\n" +
"\x10expected_version\x18\x04 \x01(\x03R\x0fexpectedVersion\x12\x1d\n" +
"\n" +
"request_id\x18\x05 \x01(\tR\trequestId\x12\x14\n" +
"\x05actor\x18\x06 \x01(\tR\x05actor\x12\x16\n" +
"\x06source\x18\a \x01(\tR\x06source\"H\n" +
"\x0fCommandResponse\x125\n" +
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\"G\n" +
"\fWatchRequest\x12\x12\n" +
"\x04kind\x18\x01 \x01(\tR\x04kind\x12#\n" +
"\rafter_version\x18\x02 \x01(\x03R\fafterVersion\"\\\n" +
"\rWatchResponse\x125\n" +
"\bresource\x18\x01 \x01(\v2\x19.controlplane.v1.ResourceR\bresource\x12\x14\n" +
"\x05error\x18\x02 \x01(\tR\x05error2\xc3\x02\n" +
"\x13ControlPlaneService\x12L\n" +
"\aCatalog\x12\x1f.controlplane.v1.CatalogRequest\x1a .controlplane.v1.CatalogResponse\x12F\n" +
"\x05Query\x12\x1d.controlplane.v1.QueryRequest\x1a\x1e.controlplane.v1.QueryResponse\x12L\n" +
"\aCommand\x12\x1f.controlplane.v1.CommandRequest\x1a .controlplane.v1.CommandResponse\x12H\n" +
"\x05Watch\x12\x1d.controlplane.v1.WatchRequest\x1a\x1e.controlplane.v1.WatchResponse0\x01B\xdc\x01\n" +
"\x13com.controlplane.v1B\x11ControlplaneProtoP\x01ZUgithub.com/samcharles93/archie-core/internal/contracts/controlplane/v1;controlplanev1\xa2\x02\x03CXX\xaa\x02\x0fControlplane.V1\xca\x02\x0fControlplane\\V1\xe2\x02\x1bControlplane\\V1\\GPBMetadata\xea\x02\x10Controlplane::V1b\x06proto3"
var (
file_controlplane_v1_controlplane_proto_rawDescOnce sync.Once
file_controlplane_v1_controlplane_proto_rawDescData []byte
)
func file_controlplane_v1_controlplane_proto_rawDescGZIP() []byte {
file_controlplane_v1_controlplane_proto_rawDescOnce.Do(func() {
file_controlplane_v1_controlplane_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_controlplane_v1_controlplane_proto_rawDesc), len(file_controlplane_v1_controlplane_proto_rawDesc)))
})
return file_controlplane_v1_controlplane_proto_rawDescData
}
var file_controlplane_v1_controlplane_proto_msgTypes = make([]protoimpl.MessageInfo, 10)
var file_controlplane_v1_controlplane_proto_goTypes = []any{
(*ResourceDescriptor)(nil), // 0: controlplane.v1.ResourceDescriptor
(*CatalogRequest)(nil), // 1: controlplane.v1.CatalogRequest
(*CatalogResponse)(nil), // 2: controlplane.v1.CatalogResponse
(*Resource)(nil), // 3: controlplane.v1.Resource
(*QueryRequest)(nil), // 4: controlplane.v1.QueryRequest
(*QueryResponse)(nil), // 5: controlplane.v1.QueryResponse
(*CommandRequest)(nil), // 6: controlplane.v1.CommandRequest
(*CommandResponse)(nil), // 7: controlplane.v1.CommandResponse
(*WatchRequest)(nil), // 8: controlplane.v1.WatchRequest
(*WatchResponse)(nil), // 9: controlplane.v1.WatchResponse
(*timestamppb.Timestamp)(nil), // 10: google.protobuf.Timestamp
}
var file_controlplane_v1_controlplane_proto_depIdxs = []int32{
0, // 0: controlplane.v1.CatalogResponse.resources:type_name -> controlplane.v1.ResourceDescriptor
10, // 1: controlplane.v1.Resource.updated_at:type_name -> google.protobuf.Timestamp
3, // 2: controlplane.v1.QueryResponse.resource:type_name -> controlplane.v1.Resource
3, // 3: controlplane.v1.CommandResponse.resource:type_name -> controlplane.v1.Resource
3, // 4: controlplane.v1.WatchResponse.resource:type_name -> controlplane.v1.Resource
1, // 5: controlplane.v1.ControlPlaneService.Catalog:input_type -> controlplane.v1.CatalogRequest
4, // 6: controlplane.v1.ControlPlaneService.Query:input_type -> controlplane.v1.QueryRequest
6, // 7: controlplane.v1.ControlPlaneService.Command:input_type -> controlplane.v1.CommandRequest
8, // 8: controlplane.v1.ControlPlaneService.Watch:input_type -> controlplane.v1.WatchRequest
2, // 9: controlplane.v1.ControlPlaneService.Catalog:output_type -> controlplane.v1.CatalogResponse
5, // 10: controlplane.v1.ControlPlaneService.Query:output_type -> controlplane.v1.QueryResponse
7, // 11: controlplane.v1.ControlPlaneService.Command:output_type -> controlplane.v1.CommandResponse
9, // 12: controlplane.v1.ControlPlaneService.Watch:output_type -> controlplane.v1.WatchResponse
9, // [9:13] is the sub-list for method output_type
5, // [5:9] is the sub-list for method input_type
5, // [5:5] is the sub-list for extension type_name
5, // [5:5] is the sub-list for extension extendee
0, // [0:5] is the sub-list for field type_name
}
func init() { file_controlplane_v1_controlplane_proto_init() }
func file_controlplane_v1_controlplane_proto_init() {
if File_controlplane_v1_controlplane_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_controlplane_v1_controlplane_proto_rawDesc), len(file_controlplane_v1_controlplane_proto_rawDesc)),
NumEnums: 0,
NumMessages: 10,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_controlplane_v1_controlplane_proto_goTypes,
DependencyIndexes: file_controlplane_v1_controlplane_proto_depIdxs,
MessageInfos: file_controlplane_v1_controlplane_proto_msgTypes,
}.Build()
File_controlplane_v1_controlplane_proto = out.File
file_controlplane_v1_controlplane_proto_goTypes = nil
file_controlplane_v1_controlplane_proto_depIdxs = nil
}
@@ -0,0 +1,239 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
// - protoc (unknown)
// source: controlplane/v1/controlplane.proto
package controlplanev1
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
ControlPlaneService_Catalog_FullMethodName = "/controlplane.v1.ControlPlaneService/Catalog"
ControlPlaneService_Query_FullMethodName = "/controlplane.v1.ControlPlaneService/Query"
ControlPlaneService_Command_FullMethodName = "/controlplane.v1.ControlPlaneService/Command"
ControlPlaneService_Watch_FullMethodName = "/controlplane.v1.ControlPlaneService/Watch"
)
// ControlPlaneServiceClient is the client API for ControlPlaneService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type ControlPlaneServiceClient interface {
Catalog(ctx context.Context, in *CatalogRequest, opts ...grpc.CallOption) (*CatalogResponse, error)
Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error)
Command(ctx context.Context, in *CommandRequest, opts ...grpc.CallOption) (*CommandResponse, error)
Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[WatchResponse], error)
}
type controlPlaneServiceClient struct {
cc grpc.ClientConnInterface
}
func NewControlPlaneServiceClient(cc grpc.ClientConnInterface) ControlPlaneServiceClient {
return &controlPlaneServiceClient{cc}
}
func (c *controlPlaneServiceClient) Catalog(ctx context.Context, in *CatalogRequest, opts ...grpc.CallOption) (*CatalogResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CatalogResponse)
err := c.cc.Invoke(ctx, ControlPlaneService_Catalog_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *controlPlaneServiceClient) Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(QueryResponse)
err := c.cc.Invoke(ctx, ControlPlaneService_Query_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *controlPlaneServiceClient) Command(ctx context.Context, in *CommandRequest, opts ...grpc.CallOption) (*CommandResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CommandResponse)
err := c.cc.Invoke(ctx, ControlPlaneService_Command_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *controlPlaneServiceClient) Watch(ctx context.Context, in *WatchRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[WatchResponse], error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
stream, err := c.cc.NewStream(ctx, &ControlPlaneService_ServiceDesc.Streams[0], ControlPlaneService_Watch_FullMethodName, cOpts...)
if err != nil {
return nil, err
}
x := &grpc.GenericClientStream[WatchRequest, WatchResponse]{ClientStream: stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ControlPlaneService_WatchClient = grpc.ServerStreamingClient[WatchResponse]
// ControlPlaneServiceServer is the server API for ControlPlaneService service.
// All implementations must embed UnimplementedControlPlaneServiceServer
// for forward compatibility.
type ControlPlaneServiceServer interface {
Catalog(context.Context, *CatalogRequest) (*CatalogResponse, error)
Query(context.Context, *QueryRequest) (*QueryResponse, error)
Command(context.Context, *CommandRequest) (*CommandResponse, error)
Watch(*WatchRequest, grpc.ServerStreamingServer[WatchResponse]) error
mustEmbedUnimplementedControlPlaneServiceServer()
}
// UnimplementedControlPlaneServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedControlPlaneServiceServer struct{}
func (UnimplementedControlPlaneServiceServer) Catalog(context.Context, *CatalogRequest) (*CatalogResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Catalog not implemented")
}
func (UnimplementedControlPlaneServiceServer) Query(context.Context, *QueryRequest) (*QueryResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Query not implemented")
}
func (UnimplementedControlPlaneServiceServer) Command(context.Context, *CommandRequest) (*CommandResponse, error) {
return nil, status.Error(codes.Unimplemented, "method Command not implemented")
}
func (UnimplementedControlPlaneServiceServer) Watch(*WatchRequest, grpc.ServerStreamingServer[WatchResponse]) error {
return status.Error(codes.Unimplemented, "method Watch not implemented")
}
func (UnimplementedControlPlaneServiceServer) mustEmbedUnimplementedControlPlaneServiceServer() {}
func (UnimplementedControlPlaneServiceServer) testEmbeddedByValue() {}
// UnsafeControlPlaneServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to ControlPlaneServiceServer will
// result in compilation errors.
type UnsafeControlPlaneServiceServer interface {
mustEmbedUnimplementedControlPlaneServiceServer()
}
func RegisterControlPlaneServiceServer(s grpc.ServiceRegistrar, srv ControlPlaneServiceServer) {
// If the following call panics, it indicates UnimplementedControlPlaneServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&ControlPlaneService_ServiceDesc, srv)
}
func _ControlPlaneService_Catalog_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CatalogRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ControlPlaneServiceServer).Catalog(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ControlPlaneService_Catalog_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ControlPlaneServiceServer).Catalog(ctx, req.(*CatalogRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ControlPlaneService_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(QueryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ControlPlaneServiceServer).Query(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ControlPlaneService_Query_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ControlPlaneServiceServer).Query(ctx, req.(*QueryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ControlPlaneService_Command_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CommandRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ControlPlaneServiceServer).Command(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: ControlPlaneService_Command_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ControlPlaneServiceServer).Command(ctx, req.(*CommandRequest))
}
return interceptor(ctx, in, info, handler)
}
func _ControlPlaneService_Watch_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(WatchRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(ControlPlaneServiceServer).Watch(m, &grpc.GenericServerStream[WatchRequest, WatchResponse]{ServerStream: stream})
}
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type ControlPlaneService_WatchServer = grpc.ServerStreamingServer[WatchResponse]
// ControlPlaneService_ServiceDesc is the grpc.ServiceDesc for ControlPlaneService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var ControlPlaneService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "controlplane.v1.ControlPlaneService",
HandlerType: (*ControlPlaneServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Catalog",
Handler: _ControlPlaneService_Catalog_Handler,
},
{
MethodName: "Query",
Handler: _ControlPlaneService_Query_Handler,
},
{
MethodName: "Command",
Handler: _ControlPlaneService_Command_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "Watch",
Handler: _ControlPlaneService_Watch_Handler,
ServerStreams: true,
},
},
Metadata: "controlplane/v1/controlplane.proto",
}
File diff suppressed because it is too large. Load diff
@@ -21,6 +21,13 @@ const _ = grpc.SupportPackageIsVersion9
const ( const (
StateStoreService_RegisterTaskGrant_FullMethodName = "/state.v1.StateStoreService/RegisterTaskGrant" StateStoreService_RegisterTaskGrant_FullMethodName = "/state.v1.StateStoreService/RegisterTaskGrant"
StateStoreService_RevokeTaskGrant_FullMethodName = "/state.v1.StateStoreService/RevokeTaskGrant" StateStoreService_RevokeTaskGrant_FullMethodName = "/state.v1.StateStoreService/RevokeTaskGrant"
StateStoreService_ListIdentities_FullMethodName = "/state.v1.StateStoreService/ListIdentities"
StateStoreService_GetIdentity_FullMethodName = "/state.v1.StateStoreService/GetIdentity"
StateStoreService_CreateIdentity_FullMethodName = "/state.v1.StateStoreService/CreateIdentity"
StateStoreService_RenameIdentity_FullMethodName = "/state.v1.StateStoreService/RenameIdentity"
StateStoreService_SuspendIdentity_FullMethodName = "/state.v1.StateStoreService/SuspendIdentity"
StateStoreService_ReactivateIdentity_FullMethodName = "/state.v1.StateStoreService/ReactivateIdentity"
StateStoreService_RetireIdentity_FullMethodName = "/state.v1.StateStoreService/RetireIdentity"
StateStoreService_EnqueueIssue_FullMethodName = "/state.v1.StateStoreService/EnqueueIssue" StateStoreService_EnqueueIssue_FullMethodName = "/state.v1.StateStoreService/EnqueueIssue"
StateStoreService_EnqueueChatTask_FullMethodName = "/state.v1.StateStoreService/EnqueueChatTask" StateStoreService_EnqueueChatTask_FullMethodName = "/state.v1.StateStoreService/EnqueueChatTask"
StateStoreService_ClaimNext_FullMethodName = "/state.v1.StateStoreService/ClaimNext" StateStoreService_ClaimNext_FullMethodName = "/state.v1.StateStoreService/ClaimNext"
@@ -84,6 +91,14 @@ type StateStoreServiceClient interface {
// Administrative task credential lifecycle. Worker credentials cannot call these. // Administrative task credential lifecycle. Worker credentials cannot call these.
RegisterTaskGrant(ctx context.Context, in *RegisterTaskGrantRequest, opts ...grpc.CallOption) (*RegisterTaskGrantResponse, error) RegisterTaskGrant(ctx context.Context, in *RegisterTaskGrantRequest, opts ...grpc.CallOption) (*RegisterTaskGrantResponse, error)
RevokeTaskGrant(ctx context.Context, in *RevokeTaskGrantRequest, opts ...grpc.CallOption) (*RevokeTaskGrantResponse, error) RevokeTaskGrant(ctx context.Context, in *RevokeTaskGrantRequest, opts ...grpc.CallOption) (*RevokeTaskGrantResponse, error)
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
ListIdentities(ctx context.Context, in *ListIdentitiesRequest, opts ...grpc.CallOption) (*ListIdentitiesResponse, error)
GetIdentity(ctx context.Context, in *GetIdentityRequest, opts ...grpc.CallOption) (*GetIdentityResponse, error)
CreateIdentity(ctx context.Context, in *CreateIdentityRequest, opts ...grpc.CallOption) (*CreateIdentityResponse, error)
RenameIdentity(ctx context.Context, in *RenameIdentityRequest, opts ...grpc.CallOption) (*RenameIdentityResponse, error)
SuspendIdentity(ctx context.Context, in *SuspendIdentityRequest, opts ...grpc.CallOption) (*SuspendIdentityResponse, error)
ReactivateIdentity(ctx context.Context, in *ReactivateIdentityRequest, opts ...grpc.CallOption) (*ReactivateIdentityResponse, error)
RetireIdentity(ctx context.Context, in *RetireIdentityRequest, opts ...grpc.CallOption) (*RetireIdentityResponse, error)
// Lifecycle // Lifecycle
EnqueueIssue(ctx context.Context, in *EnqueueIssueRequest, opts ...grpc.CallOption) (*EnqueueIssueResponse, error) EnqueueIssue(ctx context.Context, in *EnqueueIssueRequest, opts ...grpc.CallOption) (*EnqueueIssueResponse, error)
EnqueueChatTask(ctx context.Context, in *EnqueueChatTaskRequest, opts ...grpc.CallOption) (*EnqueueChatTaskResponse, error) EnqueueChatTask(ctx context.Context, in *EnqueueChatTaskRequest, opts ...grpc.CallOption) (*EnqueueChatTaskResponse, error)
@@ -194,6 +209,76 @@ func (c *stateStoreServiceClient) RevokeTaskGrant(ctx context.Context, in *Revok
return out, nil return out, nil
} }
func (c *stateStoreServiceClient) ListIdentities(ctx context.Context, in *ListIdentitiesRequest, opts ...grpc.CallOption) (*ListIdentitiesResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ListIdentitiesResponse)
err := c.cc.Invoke(ctx, StateStoreService_ListIdentities_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) GetIdentity(ctx context.Context, in *GetIdentityRequest, opts ...grpc.CallOption) (*GetIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetIdentityResponse)
err := c.cc.Invoke(ctx, StateStoreService_GetIdentity_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) CreateIdentity(ctx context.Context, in *CreateIdentityRequest, opts ...grpc.CallOption) (*CreateIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CreateIdentityResponse)
err := c.cc.Invoke(ctx, StateStoreService_CreateIdentity_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RenameIdentity(ctx context.Context, in *RenameIdentityRequest, opts ...grpc.CallOption) (*RenameIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RenameIdentityResponse)
err := c.cc.Invoke(ctx, StateStoreService_RenameIdentity_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) SuspendIdentity(ctx context.Context, in *SuspendIdentityRequest, opts ...grpc.CallOption) (*SuspendIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SuspendIdentityResponse)
err := c.cc.Invoke(ctx, StateStoreService_SuspendIdentity_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) ReactivateIdentity(ctx context.Context, in *ReactivateIdentityRequest, opts ...grpc.CallOption) (*ReactivateIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ReactivateIdentityResponse)
err := c.cc.Invoke(ctx, StateStoreService_ReactivateIdentity_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) RetireIdentity(ctx context.Context, in *RetireIdentityRequest, opts ...grpc.CallOption) (*RetireIdentityResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RetireIdentityResponse)
err := c.cc.Invoke(ctx, StateStoreService_RetireIdentity_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) EnqueueIssue(ctx context.Context, in *EnqueueIssueRequest, opts ...grpc.CallOption) (*EnqueueIssueResponse, error) { func (c *stateStoreServiceClient) EnqueueIssue(ctx context.Context, in *EnqueueIssueRequest, opts ...grpc.CallOption) (*EnqueueIssueResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(EnqueueIssueResponse) out := new(EnqueueIssueResponse)
@@ -698,6 +783,14 @@ type StateStoreServiceServer interface {
// Administrative task credential lifecycle. Worker credentials cannot call these. // Administrative task credential lifecycle. Worker credentials cannot call these.
RegisterTaskGrant(context.Context, *RegisterTaskGrantRequest) (*RegisterTaskGrantResponse, error) RegisterTaskGrant(context.Context, *RegisterTaskGrantRequest) (*RegisterTaskGrantResponse, error)
RevokeTaskGrant(context.Context, *RevokeTaskGrantRequest) (*RevokeTaskGrantResponse, error) RevokeTaskGrant(context.Context, *RevokeTaskGrantRequest) (*RevokeTaskGrantResponse, error)
// Identity domain. Task-scoped grants cannot call these administrative RPCs.
ListIdentities(context.Context, *ListIdentitiesRequest) (*ListIdentitiesResponse, error)
GetIdentity(context.Context, *GetIdentityRequest) (*GetIdentityResponse, error)
CreateIdentity(context.Context, *CreateIdentityRequest) (*CreateIdentityResponse, error)
RenameIdentity(context.Context, *RenameIdentityRequest) (*RenameIdentityResponse, error)
SuspendIdentity(context.Context, *SuspendIdentityRequest) (*SuspendIdentityResponse, error)
ReactivateIdentity(context.Context, *ReactivateIdentityRequest) (*ReactivateIdentityResponse, error)
RetireIdentity(context.Context, *RetireIdentityRequest) (*RetireIdentityResponse, error)
// Lifecycle // Lifecycle
EnqueueIssue(context.Context, *EnqueueIssueRequest) (*EnqueueIssueResponse, error) EnqueueIssue(context.Context, *EnqueueIssueRequest) (*EnqueueIssueResponse, error)
EnqueueChatTask(context.Context, *EnqueueChatTaskRequest) (*EnqueueChatTaskResponse, error) EnqueueChatTask(context.Context, *EnqueueChatTaskRequest) (*EnqueueChatTaskResponse, error)
@@ -794,6 +887,27 @@ func (UnimplementedStateStoreServiceServer) RegisterTaskGrant(context.Context, *
func (UnimplementedStateStoreServiceServer) RevokeTaskGrant(context.Context, *RevokeTaskGrantRequest) (*RevokeTaskGrantResponse, error) { func (UnimplementedStateStoreServiceServer) RevokeTaskGrant(context.Context, *RevokeTaskGrantRequest) (*RevokeTaskGrantResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RevokeTaskGrant not implemented") return nil, status.Error(codes.Unimplemented, "method RevokeTaskGrant not implemented")
} }
func (UnimplementedStateStoreServiceServer) ListIdentities(context.Context, *ListIdentitiesRequest) (*ListIdentitiesResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ListIdentities not implemented")
}
func (UnimplementedStateStoreServiceServer) GetIdentity(context.Context, *GetIdentityRequest) (*GetIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method GetIdentity not implemented")
}
func (UnimplementedStateStoreServiceServer) CreateIdentity(context.Context, *CreateIdentityRequest) (*CreateIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CreateIdentity not implemented")
}
func (UnimplementedStateStoreServiceServer) RenameIdentity(context.Context, *RenameIdentityRequest) (*RenameIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RenameIdentity not implemented")
}
func (UnimplementedStateStoreServiceServer) SuspendIdentity(context.Context, *SuspendIdentityRequest) (*SuspendIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method SuspendIdentity not implemented")
}
func (UnimplementedStateStoreServiceServer) ReactivateIdentity(context.Context, *ReactivateIdentityRequest) (*ReactivateIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method ReactivateIdentity not implemented")
}
func (UnimplementedStateStoreServiceServer) RetireIdentity(context.Context, *RetireIdentityRequest) (*RetireIdentityResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RetireIdentity not implemented")
}
func (UnimplementedStateStoreServiceServer) EnqueueIssue(context.Context, *EnqueueIssueRequest) (*EnqueueIssueResponse, error) { func (UnimplementedStateStoreServiceServer) EnqueueIssue(context.Context, *EnqueueIssueRequest) (*EnqueueIssueResponse, error) {
return nil, status.Error(codes.Unimplemented, "method EnqueueIssue not implemented") return nil, status.Error(codes.Unimplemented, "method EnqueueIssue not implemented")
} }
@@ -989,6 +1103,132 @@ func _StateStoreService_RevokeTaskGrant_Handler(srv interface{}, ctx context.Con
return interceptor(ctx, in, info, handler) return interceptor(ctx, in, info, handler)
} }
func _StateStoreService_ListIdentities_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListIdentitiesRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ListIdentities(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ListIdentities_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ListIdentities(ctx, req.(*ListIdentitiesRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_GetIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetIdentityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).GetIdentity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_GetIdentity_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).GetIdentity(ctx, req.(*GetIdentityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_CreateIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateIdentityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).CreateIdentity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_CreateIdentity_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).CreateIdentity(ctx, req.(*CreateIdentityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RenameIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RenameIdentityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RenameIdentity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RenameIdentity_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RenameIdentity(ctx, req.(*RenameIdentityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_SuspendIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SuspendIdentityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).SuspendIdentity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_SuspendIdentity_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).SuspendIdentity(ctx, req.(*SuspendIdentityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_ReactivateIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ReactivateIdentityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).ReactivateIdentity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_ReactivateIdentity_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).ReactivateIdentity(ctx, req.(*ReactivateIdentityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_RetireIdentity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RetireIdentityRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).RetireIdentity(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_RetireIdentity_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).RetireIdentity(ctx, req.(*RetireIdentityRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_EnqueueIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { func _StateStoreService_EnqueueIssue_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(EnqueueIssueRequest) in := new(EnqueueIssueRequest)
if err := dec(in); err != nil { if err := dec(in); err != nil {
@@ -1811,6 +2051,34 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "RevokeTaskGrant", MethodName: "RevokeTaskGrant",
Handler: _StateStoreService_RevokeTaskGrant_Handler, Handler: _StateStoreService_RevokeTaskGrant_Handler,
}, },
{
MethodName: "ListIdentities",
Handler: _StateStoreService_ListIdentities_Handler,
},
{
MethodName: "GetIdentity",
Handler: _StateStoreService_GetIdentity_Handler,
},
{
MethodName: "CreateIdentity",
Handler: _StateStoreService_CreateIdentity_Handler,
},
{
MethodName: "RenameIdentity",
Handler: _StateStoreService_RenameIdentity_Handler,
},
{
MethodName: "SuspendIdentity",
Handler: _StateStoreService_SuspendIdentity_Handler,
},
{
MethodName: "ReactivateIdentity",
Handler: _StateStoreService_ReactivateIdentity_Handler,
},
{
MethodName: "RetireIdentity",
Handler: _StateStoreService_RetireIdentity_Handler,
},
{ {
MethodName: "EnqueueIssue", MethodName: "EnqueueIssue",
Handler: _StateStoreService_EnqueueIssue_Handler, Handler: _StateStoreService_EnqueueIssue_Handler,
+90 -10
View File
@@ -20,6 +20,7 @@ import (
"github.com/samcharles93/archie-core/internal/container" "github.com/samcharles93/archie-core/internal/container"
"github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow"
@@ -177,6 +178,10 @@ type Daemon struct {
// When non-empty, Run() starts one goroutine per identity instead of // When non-empty, Run() starts one goroutine per identity instead of
// using the single-identity Forge/Trees/Cfg.Repos path. // using the single-identity Forge/Trees/Cfg.Repos path.
Identities []*IdentityRunner Identities []*IdentityRunner
// IdentityRepository is the durable lifecycle authority. Polling checks it
// every cycle so suspend/reactivate commands do not require a restart.
IdentityRepository identity.Repository
RootIdentityID identity.IdentityID
// Guardrails is the tool-call guardrail engine, wired by the composition // Guardrails is the tool-call guardrail engine, wired by the composition
// root. When non-nil, tool successes and failures are recorded and // root. When non-nil, tool successes and failures are recorded and
@@ -191,6 +196,11 @@ type Daemon struct {
// bindings the daemon loaded; nil means built-in defaults. // bindings the daemon loaded; nil means built-in defaults.
KindWorkflows workflow.KindWorkflows KindWorkflows workflow.KindWorkflows
LabelWorkflows workflow.LabelWorkflows LabelWorkflows workflow.LabelWorkflows
// WorkflowDefinitions supplies the active database definitions. A task is
// pinned once before dispatch; retries reuse the task's stored YAML.
WorkflowDefinitions interface {
WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error)
}
// ToolRegistry is the central tool registry, wired by the composition // ToolRegistry is the central tool registry, wired by the composition
// root. MCP-discovered tools and built-in tools are registered here // root. MCP-discovered tools and built-in tools are registered here
@@ -222,6 +232,7 @@ type Daemon struct {
// own forge client, worktree manager, repo list, and config -- but shares // own forge client, worktree manager, repo list, and config -- but shares
// the store, NATS connection, container pool, and event bus with siblings. // the store, NATS connection, container pool, and event bus with siblings.
type IdentityRunner struct { type IdentityRunner struct {
ID identity.IdentityID
Name string Name string
Forge forge.Forge Forge forge.Forge
Trees *worktree.Manager Trees *worktree.Manager
@@ -240,6 +251,7 @@ func NewIdentityRunner(ctx context.Context, idCfg config.IdentityConfig, fg forg
return nil, fmt.Errorf("identity name is required") return nil, fmt.Errorf("identity name is required")
} }
return &IdentityRunner{ return &IdentityRunner{
ID: identity.StableID(idCfg.Name),
Name: idCfg.Name, Name: idCfg.Name,
Forge: fg, Forge: fg,
Trees: trees, Trees: trees,
@@ -440,6 +452,9 @@ func (d *Daemon) runIdentities(ctx context.Context) error {
// drains or reconciles -- those are store-wide and run in the shared // drains or reconciles -- those are store-wide and run in the shared
// maintainAndDrain loop. // maintainAndDrain loop.
func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) { func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) {
if !d.identityActive(ctx, id.ID) {
return
}
d.markPoll() d.markPoll()
cfg := configForIdentity(d.Cfg.Get(), id.Cfg) cfg := configForIdentity(d.Cfg.Get(), id.Cfg)
for _, repo := range id.Repos { for _, repo := range id.Repos {
@@ -447,7 +462,7 @@ func (d *Daemon) pollForIdentity(ctx context.Context, id *IdentityRunner) {
for _, is := range issues { for _, is := range issues {
labels := strings.Join(is.Labels, ",") labels := strings.Join(is.Labels, ",")
if d.Tasks != nil { if d.Tasks != nil {
d.pollNATS(ctx, id.Forge, cfg, repo, is, labels, id.Name) d.pollNATS(ctx, id.Forge, cfg, repo, is, labels, string(id.ID))
} }
} }
} }
@@ -873,6 +888,9 @@ func (d *taskDispatcher) Wait() {
} }
func (d *Daemon) poll(ctx context.Context) { func (d *Daemon) poll(ctx context.Context) {
if !d.identityActive(ctx, d.RootIdentityID) {
return
}
d.markPoll() d.markPoll()
for _, repo := range d.Cfg.Get().Repos { for _, repo := range d.Cfg.Get().Repos {
issues := d.pollIssues(ctx, repo) issues := d.pollIssues(ctx, repo)
@@ -1394,15 +1412,21 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
cfg := d.configFor(task) cfg := d.configFor(task)
taskCfg := cfg.ForTask() taskCfg := cfg.ForTask()
d.captureAttemptConfig(ctx, task, taskCfg) d.captureAttemptConfig(ctx, task, taskCfg)
if err := d.pinWorkflowDefinition(ctx, task); err != nil {
d.Log.Error("pin workflow definition failed", "task", task.ID, "err", err)
d.parkRunningTask(ctx, task.ID, "pin workflow definition: "+err.Error())
return
}
req := taskrun.Request{ req := taskrun.Request{
Task: task, Task: task,
Repo: repo, Repo: repo,
Cfg: taskCfg, Cfg: taskCfg,
Providers: agentexec.ProvidersFromConfig(cfg.Providers), Providers: agentexec.ProvidersFromConfig(cfg.Providers),
MCPServers: cfg.Tools.MCPServers, MCPServers: cfg.Tools.MCPServers,
WorktreeGrant: grant, WorktreeGrant: grant,
KindWorkflows: d.KindWorkflows, KindWorkflows: d.KindWorkflows,
LabelWorkflows: d.LabelWorkflows, LabelWorkflows: d.LabelWorkflows,
WorkflowDefinition: task.WorkflowDefinitionYAML,
} }
data, err := json.Marshal(req) data, err := json.Marshal(req)
if err != nil { if err != nil {
@@ -1441,6 +1465,46 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
d.Log.Info("taskrun complete", "task", task.ID, "status", resp.Status) d.Log.Info("taskrun complete", "task", task.ID, "status", resp.Status)
} }
func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task) error {
if task.WorkflowDefinitionYAML != "" {
if workflow.DigestDefinition(task.WorkflowDefinitionYAML) != task.WorkflowDefinitionDigest {
return fmt.Errorf("stored workflow definition digest mismatch")
}
return nil
}
if d.WorkflowDefinitions == nil {
return d.pinWorkflowFromCollection(ctx, task, workflow.ShippedDefinitions(), 0)
}
collection, version, err := d.WorkflowDefinitions.WorkflowDefinitions(ctx)
if err != nil {
return err
}
return d.pinWorkflowFromCollection(ctx, task, collection, version)
}
func (d *Daemon) pinWorkflowFromCollection(ctx context.Context, task *workflow.Task, collection workflow.WorkflowDefinitionCollection, version int64) error {
available := make(map[string]struct{}, len(collection.Definitions))
for _, definition := range collection.Definitions {
available[definition.ID] = struct{}{}
}
id, err := workflow.ResolveWorkflowID(task, available, d.KindWorkflows, d.LabelWorkflows)
if err != nil {
return err
}
definition, ok := collection.DefinitionByID(id)
if !ok {
return fmt.Errorf("workflow definition %q disappeared", id)
}
task.Workflow = id
task.WorkflowDefinitionVersion = version
task.WorkflowDefinitionYAML = definition.YAML
task.WorkflowDefinitionDigest = workflow.DigestDefinition(definition.YAML)
if err := d.Store.Update(ctx, task); err != nil {
return fmt.Errorf("persist workflow definition pin: %w", err)
}
return nil
}
const ( const (
// defaultTaskRunReadyTimeout is how long requestTaskRun retries a // defaultTaskRunReadyTimeout is how long requestTaskRun retries a
// nats.ErrNoResponders before giving up, when Daemon.TaskRunReadyTimeout // nats.ErrNoResponders before giving up, when Daemon.TaskRunReadyTimeout
@@ -1636,13 +1700,29 @@ func (d *Daemon) identityFor(task *workflow.Task) *IdentityRunner {
return nil return nil
} }
for _, id := range d.Identities { for _, id := range d.Identities {
if id.Name == task.Identity { if id.Name == task.Identity || string(id.ID) == task.Identity {
return id return id
} }
} }
return nil return nil
} }
func (d *Daemon) identityActive(ctx context.Context, id identity.IdentityID) bool {
if d.IdentityRepository == nil {
return true
}
if id == "" {
d.Log.Error("identity lifecycle check failed", "err", "identity ID is empty")
return false
}
value, err := d.IdentityRepository.Get(ctx, id)
if err != nil {
d.Log.Error("identity lifecycle check failed", "identity", id, "err", err)
return false
}
return value.Lifecycle == identity.LifecycleActive
}
// forgeFor returns the forge client that owns task: the identity's own // forgeFor returns the forge client that owns task: the identity's own
// client when task.Identity names a configured identity, else the root // client when task.Identity names a configured identity, else the root
// d.Forge. This is the safety boundary that keeps one identity's forge // d.Forge. This is the safety boundary that keeps one identity's forge
@@ -0,0 +1,48 @@
package daemon
import (
"context"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/store"
)
type workflowDefinitionsStub struct {
collection workflow.WorkflowDefinitionCollection
version int64
}
func (s *workflowDefinitionsStub) WorkflowDefinitions(context.Context) (workflow.WorkflowDefinitionCollection, int64, error) {
return s.collection, s.version, nil
}
func TestWorkflowDefinitionPinSurvivesActiveOverride(t *testing.T) {
resources := store.OpenTest(t)
defer resources.Close()
task, err := resources.EnqueueChatTask(t.Context(), "acme", "widget", "custom", "", "custom", "operator")
if err != nil {
t.Fatal(err)
}
first := "id: custom\nsteps:\n - type: bootstrap.apply\n"
provider := &workflowDefinitionsStub{collection: workflow.WorkflowDefinitionCollection{Definitions: []workflow.WorkflowDefinitionEntry{{ID: "custom", YAML: first}}}, version: 4}
d := &Daemon{Store: resources, WorkflowDefinitions: provider}
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
provider.collection.Definitions[0].YAML = "id: custom\nsteps:\n - type: bootstrap.prepare\n"
provider.version = 5
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
t.Fatal(err)
}
if task.WorkflowDefinitionYAML != first || task.WorkflowDefinitionVersion != 4 {
t.Fatalf("pin changed after override: version=%d yaml=%q", task.WorkflowDefinitionVersion, task.WorkflowDefinitionYAML)
}
stored, err := resources.TaskByID(t.Context(), task.ID)
if err != nil {
t.Fatal(err)
}
if stored.WorkflowDefinitionDigest != workflow.DigestDefinition(first) {
t.Fatal("persisted workflow digest does not identify the pinned YAML")
}
}
+53
View File
@@ -0,0 +1,53 @@
package agent
import (
"fmt"
"strings"
)
type Persona struct {
Name string `json:"name"`
Prompt string `json:"prompt"`
}
type PersonaCollection struct {
Default string `json:"default"`
Personas []Persona `json:"personas"`
}
func (c PersonaCollection) Validate() error {
if len(c.Personas) == 0 {
return fmt.Errorf("at least one persona is required")
}
defaultName := normalizePersonaName(c.Default)
seen := make(map[string]struct{}, len(c.Personas))
for _, persona := range c.Personas {
name := normalizePersonaName(persona.Name)
if name == "" || strings.TrimSpace(persona.Prompt) == "" {
return fmt.Errorf("persona name and prompt are required")
}
if _, exists := seen[name]; exists {
return fmt.Errorf("duplicate persona %q", name)
}
seen[name] = struct{}{}
}
if _, exists := seen[defaultName]; !exists {
return fmt.Errorf("default persona %q does not exist", c.Default)
}
return nil
}
func normalizePersonaName(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}
func ShippedPersonas() PersonaCollection {
return PersonaCollection{Default: "archie", Personas: []Persona{
{Name: "archie", Prompt: "You are Archie, a capable coding and project assistant. Be direct without being brusque, grounded in the actual workspace state, and use available tools when asked. Do not claim tools, files, memories, actions, or results you have not verified. Do not impersonate another assistant, provider, or vendor."},
{Name: "helpful", Prompt: "You are a helpful, friendly AI assistant."},
{Name: "concise", Prompt: "You are a concise assistant. Keep responses brief and to the point."},
{Name: "technical", Prompt: "You are a technical expert. Provide detailed, accurate technical information."},
{Name: "creative", Prompt: "You are a creative assistant. Think outside the box and offer innovative solutions."},
{Name: "teacher", Prompt: "You are a patient teacher. Explain concepts clearly with examples."},
}}
}
+26
View File
@@ -0,0 +1,26 @@
package agent
import "testing"
func TestPersonaCollectionValidate(t *testing.T) {
t.Parallel()
tests := []struct {
name string
collection PersonaCollection
wantErr bool
}{
{name: "valid", collection: PersonaCollection{Default: "archie", Personas: []Persona{{Name: "archie", Prompt: "baseline"}, {Name: "concise", Prompt: "brief"}}}},
{name: "missing default", collection: PersonaCollection{Default: "missing", Personas: []Persona{{Name: "archie", Prompt: "baseline"}}}, wantErr: true},
{name: "duplicate normalized name", collection: PersonaCollection{Default: "archie", Personas: []Persona{{Name: "Archie", Prompt: "baseline"}, {Name: " archie ", Prompt: "other"}}}, wantErr: true},
{name: "empty prompt", collection: PersonaCollection{Default: "archie", Personas: []Persona{{Name: "archie"}}}, wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if err := tt.collection.Validate(); (err != nil) != tt.wantErr {
t.Fatalf("Validate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
+5 -9
View File
@@ -3,17 +3,14 @@
// via Yaegi (same trust tier as PluginDir and SecretEngineDir -- NOT // via Yaegi (same trust tier as PluginDir and SecretEngineDir -- NOT
// repository-supplied task code). // repository-supplied task code).
// //
// It generalizes the fixed-signature, resolved-by-name Yaegi pattern already // Each module kind has a fixed signature and generated symbol table: load the
// shipped for custom gates (internal/gate/gateeval) and workflow stage plugins // installed source, resolve its typed entrypoint, then call it through the
// (internal/domain/workflow/skillbuild): read a .go file -> yaegiutil.New with // panic-safe interpreter boundary.
// that kind's symbol table -> yaegiutil.Resolve[func(Args) Result] ->
// yaegiutil.Safe-wrapped call.
// //
// Per docs/prds/module-position.md, there is deliberately no generic Module // Per docs/prds/module-position.md, there is deliberately no generic Module
// interface with an any payload. Each action kind is its own tiny package // interface with an any payload. Each action kind is its own tiny package
// with its own generated contract (internal/domain/eda/module/<kind>), and // with its own generated contract (internal/domain/eda/module/<kind>), and
// the registry's internal storage is the only place type erasure appears -- // the registry's internal storage is the only place type erasure appears.
// exactly as it already does inside wfextract.
package module package module
import ( import (
@@ -111,8 +108,7 @@ func (r *ModuleRegistry) Register(kind, dir string) error {
// resolveInvoker builds the type-erased invoker for one kind from its // resolveInvoker builds the type-erased invoker for one kind from its
// interpreted source. Each kind has its own typed decode/invoke path below; // interpreted source. Each kind has its own typed decode/invoke path below;
// this switch is the only place the per-kind types are named, mirroring // this switch is the only place the per-kind types are named.
// wfextract's closed symbol table.
func resolveInvoker(kind, label, src string, k Kind) (invoker, error) { func resolveInvoker(kind, label, src string, k Kind) (invoker, error) {
switch kind { switch kind {
case "log": case "log":
+153
View File
@@ -0,0 +1,153 @@
// Package identity owns persistent actor identity and lifecycle semantics.
package identity
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"strings"
"time"
)
type (
IdentityID string
Kind string
Lifecycle string
CommandType string
)
const (
SystemID IdentityID = "00000000-0000-5000-8000-000000000001"
KindSystem Kind = "system"
KindBot Kind = "bot"
KindServiceAccount Kind = "service_account"
KindUser Kind = "user"
LifecycleActive Lifecycle = "active"
LifecycleSuspended Lifecycle = "suspended"
LifecycleRetired Lifecycle = "retired"
CommandRename CommandType = "rename"
CommandSuspend CommandType = "suspend"
CommandReactivate CommandType = "reactivate"
CommandRetire CommandType = "retire"
)
var (
ErrInvalid = errors.New("invalid identity")
ErrNotFound = errors.New("identity not found")
ErrConflict = errors.New("identity version conflict")
ErrSystemImmutable = errors.New("system identity is immutable")
ErrIllegalTransition = errors.New("illegal identity lifecycle transition")
)
type Identity struct {
ID IdentityID `json:"id"`
Kind Kind `json:"kind"`
DisplayName string `json:"display_name"`
Lifecycle Lifecycle `json:"lifecycle"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type (
Command struct {
Type CommandType
DisplayName string
}
Event struct {
IdentityID IdentityID
Type CommandType
From Lifecycle
To Lifecycle
DisplayName string
At time.Time
}
Audit struct {
ActorID IdentityID
Source, RequestID string
At time.Time
}
)
type Repository interface {
List(context.Context) ([]Identity, error)
Get(context.Context, IdentityID) (Identity, error)
ResolveLegacyName(context.Context, string) (Identity, error)
Create(context.Context, Identity, Audit) (Identity, error)
Apply(context.Context, IdentityID, int64, Command, Audit) (Identity, error)
}
func System() Identity {
return Identity{ID: SystemID, Kind: KindSystem, DisplayName: "System", Lifecycle: LifecycleActive, Version: 1}
}
func StableID(legacyName string) IdentityID {
sum := sha256.Sum256([]byte("archie.identity.v1\x00" + strings.ToLower(strings.TrimSpace(legacyName))))
return IdentityID(fmt.Sprintf("%08x-%04x-5%03x-%04x-%012x", sum[:4], sum[4:6], sum[6:8], uint16(sum[8])<<8|uint16(sum[9])&0x3fff|0x8000, sum[10:16]))
}
func New(id IdentityID, kind Kind, displayName string) (Identity, error) {
value := Identity{ID: id, Kind: kind, DisplayName: strings.TrimSpace(displayName), Lifecycle: LifecycleActive, Version: 1}
if err := value.Validate(); err != nil {
return Identity{}, err
}
return value, nil
}
func (i Identity) Validate() error {
if i.ID == "" || strings.TrimSpace(i.DisplayName) == "" {
return fmt.Errorf("%w: ID and display name are required", ErrInvalid)
}
switch i.Kind {
case KindSystem, KindBot, KindServiceAccount, KindUser:
default:
return fmt.Errorf("%w: unknown kind %q", ErrInvalid, i.Kind)
}
switch i.Lifecycle {
case LifecycleActive, LifecycleSuspended, LifecycleRetired:
default:
return fmt.Errorf("%w: unknown lifecycle %q", ErrInvalid, i.Lifecycle)
}
if i.Kind == KindSystem && (i.ID != SystemID || i.Lifecycle != LifecycleActive) {
return ErrSystemImmutable
}
if i.ID == SystemID && i.Kind != KindSystem {
return ErrSystemImmutable
}
return nil
}
func Apply(i Identity, command Command) (Identity, Event, error) {
if i.ID == SystemID || i.Kind == KindSystem {
return Identity{}, Event{}, ErrSystemImmutable
}
event := Event{IdentityID: i.ID, Type: command.Type, From: i.Lifecycle, To: i.Lifecycle, At: time.Now().UTC()}
switch command.Type {
case CommandRename:
name := strings.TrimSpace(command.DisplayName)
if name == "" {
return Identity{}, Event{}, fmt.Errorf("%w: display name is required", ErrInvalid)
}
i.DisplayName, event.DisplayName = name, name
case CommandSuspend:
if i.Lifecycle != LifecycleActive {
return Identity{}, Event{}, ErrIllegalTransition
}
i.Lifecycle, event.To = LifecycleSuspended, LifecycleSuspended
case CommandReactivate:
if i.Lifecycle != LifecycleSuspended {
return Identity{}, Event{}, ErrIllegalTransition
}
i.Lifecycle, event.To = LifecycleActive, LifecycleActive
case CommandRetire:
if i.Lifecycle != LifecycleActive && i.Lifecycle != LifecycleSuspended {
return Identity{}, Event{}, ErrIllegalTransition
}
i.Lifecycle, event.To = LifecycleRetired, LifecycleRetired
default:
return Identity{}, Event{}, fmt.Errorf("%w: unknown command %q", ErrInvalid, command.Type)
}
i.Version++
return i, event, nil
}
+58
View File
@@ -0,0 +1,58 @@
package identity
import (
"errors"
"testing"
)
func TestSystemIdentityCannotBeMutated(t *testing.T) {
t.Parallel()
system := System()
for name, command := range map[string]Command{
"rename": {Type: CommandRename, DisplayName: "Other"},
"suspend": {Type: CommandSuspend},
"reactivate": {Type: CommandReactivate},
"retire": {Type: CommandRetire},
} {
t.Run(name, func(t *testing.T) {
if _, _, err := Apply(system, command); !errors.Is(err, ErrSystemImmutable) {
t.Fatalf("Apply() error = %v, want ErrSystemImmutable", err)
}
})
}
}
func TestLifecycleTransitions(t *testing.T) {
t.Parallel()
id, err := New(StableID("reviewer"), KindBot, "Reviewer")
if err != nil {
t.Fatal(err)
}
for _, command := range []Command{{Type: CommandSuspend}, {Type: CommandReactivate}, {Type: CommandRetire}} {
var event Event
id, event, err = Apply(id, command)
if err != nil {
t.Fatalf("Apply(%s): %v", command.Type, err)
}
if event.IdentityID != id.ID {
t.Fatalf("event identity = %q, want %q", event.IdentityID, id.ID)
}
}
if id.Lifecycle != LifecycleRetired {
t.Fatalf("lifecycle = %q, want retired", id.Lifecycle)
}
if _, _, err = Apply(id, Command{Type: CommandReactivate}); !errors.Is(err, ErrIllegalTransition) {
t.Fatalf("reactivate retired error = %v, want ErrIllegalTransition", err)
}
}
func TestStableIDIsNameStableAndNotDisplayName(t *testing.T) {
t.Parallel()
first := StableID(" ReviewER ")
if first != StableID("reviewer") {
t.Fatalf("stable IDs differ: %q", first)
}
if first == IdentityID("reviewer") {
t.Fatal("stable ID aliases the legacy display name")
}
}
+2
View File
@@ -5,6 +5,7 @@ package messaging
// the executable router surface. // the executable router surface.
var localCommands = []string{ var localCommands = []string{
"/status", "/tasks", "/model", "/spawn", "/status", "/tasks", "/model", "/spawn",
"/settings",
"/approve", "/cancel", "/start", "/approve", "/cancel", "/start",
"/new", "/reset", "/topic", "/retry", "/undo", "/new", "/reset", "/topic", "/retry", "/undo",
"/title", "/branch", "/fork", "/compress", "/compact", "/title", "/branch", "/fork", "/compress", "/compact",
@@ -24,6 +25,7 @@ var localCommandSpecs = []CommandSpec{
{Command: "/tasks", Description: "Show your tasks: state, stage, age, parked reason", Usage: "/tasks"}, {Command: "/tasks", Description: "Show your tasks: state, stage, age, parked reason", Usage: "/tasks"},
{Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"}, {Command: "/model", Description: "Choose a provider and model", Usage: "/model [provider/model]"},
{Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn <title>"}, {Command: "/spawn", Description: "Create a tracked task", Usage: "/spawn <title>"},
{Command: "/settings", Description: "Inspect or change runtime settings", Usage: "/settings [list|get|set|identity]"},
{Command: "/approve", Description: "Approve a waiting task", Usage: "/approve <task-id>"}, {Command: "/approve", Description: "Approve a waiting task", Usage: "/approve <task-id>"},
{Command: "/cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel <task-id>"}, {Command: "/cancel", Description: "Cancel a queued or waiting task", Usage: "/cancel <task-id>"},
{Command: "/start", Description: "Confirm that Archie is running", Usage: "/start"}, {Command: "/start", Description: "Confirm that Archie is running", Usage: "/start"},
+407
View File
@@ -0,0 +1,407 @@
package messaging
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"maps"
"sort"
"strconv"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
var (
ErrSettingsValidation = errors.New("settings validation")
ErrSettingsNotFound = errors.New("settings not found")
ErrSettingsConflict = errors.New("settings version conflict")
ErrSettingsUnavailable = errors.New("settings unavailable")
)
type SettingField struct {
Type string
Secret bool
}
type SettingDescriptor struct {
Kind string
Title string
Fields map[string]SettingField
}
type SettingResource struct {
Kind string
Version int64
Value map[string]any
Raw any
}
type SettingCommand struct {
Kind string
Value map[string]any
RawValue any
ExpectedVersion int64
Actor string
Source string
RequestID string
}
type SettingsClient interface {
Catalog(context.Context) ([]SettingDescriptor, error)
Query(context.Context, string) (SettingResource, error)
Command(context.Context, SettingCommand) (SettingResource, error)
}
type SettingsCommand struct {
client SettingsClient
identities identity.Repository
}
func NewSettingsCommand(client SettingsClient) *SettingsCommand {
return &SettingsCommand{client: client}
}
func (c *SettingsCommand) WithIdentities(repository identity.Repository) *SettingsCommand {
c.identities = repository
return c
}
const settingsUsage = "Usage: /settings [list|get <kind>|set <kind> <field>=<value> ...|replace <kind> <json>]"
func (c *SettingsCommand) Execute(ctx context.Context, actor, input string) string {
if c == nil || c.client == nil {
return "Settings are unavailable."
}
args, err := splitSettingsArgs(strings.TrimSpace(input))
if err != nil {
return "Invalid settings command: " + err.Error() + ". " + settingsUsage
}
if len(args) == 0 || args[0] == "help" {
return settingsUsage
}
switch args[0] {
case "list":
return c.list(ctx, args)
case "get":
return c.get(ctx, args)
case "set":
return c.set(ctx, actor, args)
case "identity":
return c.identity(ctx, actor, args[1:])
case "replace":
return c.replace(ctx, actor, strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(input), "replace")))
default:
return settingsUsage
}
}
func (c *SettingsCommand) replace(ctx context.Context, actor, input string) string {
if strings.TrimSpace(actor) == "" {
return "Settings changes require an authenticated Archie identity; this channel cannot resolve one."
}
kind, raw, ok := strings.Cut(strings.TrimSpace(input), " ")
if !ok || kind == "" || strings.TrimSpace(raw) == "" {
return settingsUsage
}
if _, err := c.descriptor(ctx, kind); err != nil {
return settingsError(err)
}
current, err := c.client.Query(ctx, kind)
if err != nil {
return settingsError(err)
}
var value any
if err := json.Unmarshal([]byte(raw), &value); err != nil {
return "Settings validation failed: invalid JSON."
}
updated, err := c.client.Command(ctx, SettingCommand{Kind: kind, RawValue: value, ExpectedVersion: current.Version, Actor: actor, Source: "messaging", RequestID: newSettingsRequestID()})
if err != nil {
return settingsError(err)
}
return fmt.Sprintf("Updated %s to version %d.", updated.Kind, updated.Version)
}
func (c *SettingsCommand) identity(ctx context.Context, actor string, args []string) string { //nolint:gocyclo,cyclop,funlen // command arity checks remain adjacent to spoof-sensitive dispatch
const usage = "Usage: /settings identity <list|create <kind> <name>|rename <id> <name>|suspend <id>|reactivate <id>|retire <id>>"
if c.identities == nil {
return "Identity administration is unavailable."
}
if strings.TrimSpace(actor) == "" {
return "Identity changes require an authenticated Archie identity; this channel cannot resolve one."
}
actorIdentity, err := c.identities.ResolveLegacyName(ctx, actor)
if err != nil {
return "Identity changes require an authenticated Archie identity; this sender did not resolve."
}
if len(args) == 1 && args[0] == "list" {
values, listErr := c.identities.List(ctx)
if listErr != nil {
return "Identity administration is unavailable: " + listErr.Error()
}
lines := []string{"Identities:"}
for _, value := range values {
lines = append(lines, fmt.Sprintf("- %s %s %s %q", value.ID, value.Kind, value.Lifecycle, value.DisplayName))
}
return strings.Join(lines, "\n")
}
audit := identity.Audit{ActorID: actorIdentity.ID, Source: "messaging", RequestID: newSettingsRequestID()}
if len(args) == 3 && args[0] == "create" {
id := identity.StableID(audit.RequestID)
value, createErr := identity.New(id, identity.Kind(args[1]), args[2])
if createErr == nil {
value, createErr = c.identities.Create(ctx, value, audit)
}
if createErr != nil {
return "Identity change failed: " + createErr.Error()
}
return fmt.Sprintf("Created %s %q.", value.ID, value.DisplayName)
}
if len(args) < 2 {
return usage
}
target, getErr := c.identities.Get(ctx, identity.IdentityID(args[1]))
if getErr != nil {
return "Identity change failed: " + getErr.Error()
}
var command identity.Command
switch args[0] {
case "rename":
if len(args) != 3 {
return usage
}
command = identity.Command{Type: identity.CommandRename, DisplayName: args[2]}
case "suspend":
if len(args) != 2 {
return usage
}
command.Type = identity.CommandSuspend
case "reactivate":
if len(args) != 2 {
return usage
}
command.Type = identity.CommandReactivate
case "retire":
if len(args) != 2 {
return usage
}
command.Type = identity.CommandRetire
default:
return usage
}
updated, applyErr := c.identities.Apply(ctx, target.ID, target.Version, command, audit)
if applyErr != nil {
return "Identity change failed: " + applyErr.Error()
}
return fmt.Sprintf("%s is %s (version %d).", updated.DisplayName, updated.Lifecycle, updated.Version)
}
func (c *SettingsCommand) list(ctx context.Context, args []string) string {
if len(args) != 1 {
return settingsUsage
}
descriptors, err := c.client.Catalog(ctx)
if err != nil {
return settingsError(err)
}
sort.Slice(descriptors, func(i, j int) bool { return descriptors[i].Kind < descriptors[j].Kind })
lines := []string{"Settings:"}
for _, descriptor := range descriptors {
lines = append(lines, fmt.Sprintf("- %s — %s", descriptor.Kind, descriptor.Title))
}
return strings.Join(lines, "\n")
}
func (c *SettingsCommand) get(ctx context.Context, args []string) string {
if len(args) != 2 {
return settingsUsage
}
descriptor, err := c.descriptor(ctx, args[1])
if err != nil {
return settingsError(err)
}
resource, err := c.client.Query(ctx, args[1])
if err != nil {
return settingsError(err)
}
return renderSetting(resource, descriptor)
}
func (c *SettingsCommand) set(ctx context.Context, actor string, args []string) string {
if len(args) < 3 {
return settingsUsage
}
if strings.TrimSpace(actor) == "" {
return "Settings changes require an authenticated Archie identity; this channel cannot resolve one."
}
descriptor, err := c.descriptor(ctx, args[1])
if err != nil {
return settingsError(err)
}
current, err := c.client.Query(ctx, args[1])
if err != nil {
return settingsError(err)
}
value := cloneSettingValue(current.Value)
for _, assignment := range args[2:] {
name, raw, ok := strings.Cut(assignment, "=")
field, exists := descriptor.Fields[name]
if !ok || name == "" || !exists || field.Secret {
return fmt.Sprintf("Unknown or non-editable field %q for %s.", name, descriptor.Kind)
}
parsed, parseErr := parseSettingValue(field.Type, raw)
if parseErr != nil {
return fmt.Sprintf("Invalid value for %s: %v.", name, parseErr)
}
value[name] = parsed
}
updated, err := c.client.Command(ctx, SettingCommand{Kind: current.Kind, Value: value, ExpectedVersion: current.Version, Actor: actor, Source: "messaging", RequestID: newSettingsRequestID()})
if err != nil {
return settingsError(err)
}
return fmt.Sprintf("Updated %s to version %d.\n%s", updated.Kind, updated.Version, renderSetting(updated, descriptor))
}
func (c *SettingsCommand) descriptor(ctx context.Context, kind string) (SettingDescriptor, error) {
descriptors, err := c.client.Catalog(ctx)
if err != nil {
return SettingDescriptor{}, err
}
for _, descriptor := range descriptors {
if descriptor.Kind == kind {
return descriptor, nil
}
}
return SettingDescriptor{}, ErrSettingsNotFound
}
func parseSettingValue(kind, raw string) (any, error) {
switch kind {
case "boolean":
return strconv.ParseBool(raw)
case "integer":
return strconv.ParseInt(raw, 10, 64)
case "duration":
duration, err := time.ParseDuration(raw)
if err != nil {
return nil, err
}
return int64(duration / time.Second), nil
case "string":
return raw, nil
default:
return nil, fmt.Errorf("unsupported type %q", kind)
}
}
func renderSetting(resource SettingResource, descriptor SettingDescriptor) string {
if resource.Value == nil {
value, err := json.MarshalIndent(resource.Raw, "", " ")
if err != nil {
return fmt.Sprintf("%s (version %d)", resource.Kind, resource.Version)
}
return fmt.Sprintf("%s (version %d):\n%s", resource.Kind, resource.Version, value)
}
names := make([]string, 0, len(resource.Value))
for name := range resource.Value {
names = append(names, name)
}
sort.Strings(names)
lines := []string{fmt.Sprintf("%s (version %d):", resource.Kind, resource.Version)}
for _, name := range names {
field := descriptor.Fields[name]
if field.Secret || looksSecret(name) {
lines = append(lines, name+"=<redacted>")
continue
}
lines = append(lines, fmt.Sprintf("%s=%v", name, resource.Value[name]))
}
return strings.Join(lines, "\n")
}
func looksSecret(name string) bool {
name = strings.ToLower(name)
for _, marker := range []string{"secret", "password", "token", "credential", "api_key", "private_key"} {
if strings.Contains(name, marker) {
return true
}
}
return false
}
func cloneSettingValue(value map[string]any) map[string]any {
cloned := make(map[string]any, len(value))
maps.Copy(cloned, value)
return cloned
}
func newSettingsRequestID() string {
var bytes [16]byte
if _, err := rand.Read(bytes[:]); err != nil {
return fmt.Sprintf("messaging-%d", time.Now().UnixNano())
}
return "messaging-" + hex.EncodeToString(bytes[:])
}
func settingsError(err error) string {
switch {
case errors.Is(err, ErrSettingsValidation):
return "Settings validation failed: " + err.Error()
case errors.Is(err, ErrSettingsNotFound):
return "Unknown settings kind. Use /settings list."
case errors.Is(err, ErrSettingsConflict):
return "Settings version conflict; inspect the latest value and retry."
default:
return "Settings are unavailable: " + err.Error()
}
}
func splitSettingsArgs(input string) ([]string, error) {
var args []string
var current strings.Builder
var quote rune
escaped := false
flush := func() {
if current.Len() > 0 {
args = append(args, current.String())
current.Reset()
}
}
for _, char := range input {
if escaped {
current.WriteRune(char)
escaped = false
continue
}
if char == '\\' {
escaped = true
continue
}
if quote != 0 {
if char == quote {
quote = 0
} else {
current.WriteRune(char)
}
continue
}
if char == '\'' || char == '"' {
quote = char
continue
}
if char == ' ' || char == '\t' || char == '\n' {
flush()
continue
}
current.WriteRune(char)
}
if escaped || quote != 0 {
return nil, errors.New("unterminated quote or escape")
}
flush()
return args, nil
}
+172
View File
@@ -0,0 +1,172 @@
package messaging
import (
"context"
"errors"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
type settingsClientStub struct {
descriptors []SettingDescriptor
resource SettingResource
command SettingCommand
err error
commandErr error
}
func TestIdentityCommandFailsClosedForSpoofedOrUnknownActor(t *testing.T) {
trusted, _ := identity.New(identity.StableID("trusted"), identity.KindUser, "trusted")
target, err := identity.New(identity.StableID("target"), identity.KindBot, "Target")
if err != nil {
t.Fatal(err)
}
repository := &identityRepositoryStub{values: map[identity.IdentityID]identity.Identity{trusted.ID: trusted, target.ID: target}, aliases: map[string]identity.IdentityID{"trusted": trusted.ID}}
command := NewSettingsCommand(&settingsClientStub{}).WithIdentities(repository)
reply := command.Execute(t.Context(), "mallory", "identity suspend "+string(target.ID))
if !strings.Contains(reply, "did not resolve") {
t.Fatalf("reply = %q, want fail-closed resolution", reply)
}
current, err := repository.Get(t.Context(), target.ID)
if err != nil {
t.Fatal(err)
}
if current.Lifecycle != identity.LifecycleActive {
t.Fatalf("spoof changed lifecycle to %q", current.Lifecycle)
}
reply = command.Execute(t.Context(), "trusted", "identity suspend "+string(target.ID)+" actor=mallory")
if !strings.Contains(reply, "Usage:") {
t.Fatalf("reply = %q, want actor input rejected", reply)
}
}
type identityRepositoryStub struct {
values map[identity.IdentityID]identity.Identity
aliases map[string]identity.IdentityID
}
func (s *identityRepositoryStub) List(context.Context) ([]identity.Identity, error) {
out := make([]identity.Identity, 0, len(s.values))
for _, value := range s.values {
out = append(out, value)
}
return out, nil
}
func (s *identityRepositoryStub) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
value, ok := s.values[id]
if !ok {
return identity.Identity{}, identity.ErrNotFound
}
return value, nil
}
func (s *identityRepositoryStub) ResolveLegacyName(ctx context.Context, name string) (identity.Identity, error) {
return s.Get(ctx, s.aliases[name])
}
func (s *identityRepositoryStub) Create(_ context.Context, value identity.Identity, _ identity.Audit) (identity.Identity, error) {
s.values[value.ID] = value
return value, nil
}
func (s *identityRepositoryStub) Apply(ctx context.Context, id identity.IdentityID, version int64, command identity.Command, _ identity.Audit) (identity.Identity, error) {
current, err := s.Get(ctx, id)
if err != nil {
return identity.Identity{}, err
}
if current.Version != version {
return identity.Identity{}, identity.ErrConflict
}
updated, _, err := identity.Apply(current, command)
if err == nil {
s.values[id] = updated
}
return updated, err
}
func (s *settingsClientStub) Catalog(context.Context) ([]SettingDescriptor, error) {
return s.descriptors, s.err
}
func (s *settingsClientStub) Query(context.Context, string) (SettingResource, error) {
return s.resource, s.err
}
func (s *settingsClientStub) Command(_ context.Context, command SettingCommand) (SettingResource, error) {
s.command = command
return SettingResource{Kind: command.Kind, Version: command.ExpectedVersion + 1, Value: command.Value}, s.commandErr
}
func TestSettingsSetUsesTrustedActorAndCurrentVersion(t *testing.T) {
client := &settingsClientStub{
descriptors: []SettingDescriptor{{Kind: "limits", Fields: map[string]SettingField{
"enabled": {Type: "boolean"}, "retries": {Type: "integer"}, "timeout": {Type: "duration"}, "label": {Type: "string"},
}}},
resource: SettingResource{Kind: "limits", Version: 7, Value: map[string]any{"enabled": false, "retries": float64(1), "timeout": "1m", "label": "old"}},
}
command := NewSettingsCommand(client)
reply := command.Execute(t.Context(), "archie:operator-7", `set limits enabled=true retries=3 timeout="2m30s" label="night run"`)
if !strings.Contains(reply, "version 8") {
t.Fatalf("reply = %q, want version confirmation", reply)
}
if client.command.Actor != "archie:operator-7" {
t.Fatalf("actor = %q, want trusted actor", client.command.Actor)
}
if client.command.ExpectedVersion != 7 {
t.Fatalf("expected version = %d, want 7", client.command.ExpectedVersion)
}
if _, exists := client.command.Value["actor"]; exists {
t.Fatal("command text injected an actor field")
}
if client.command.RequestID == "" || client.command.Source != "messaging" {
t.Fatalf("request metadata = (%q, %q), want unique ID and messaging source", client.command.RequestID, client.command.Source)
}
previousID := client.command.RequestID
spoofReply := command.Execute(t.Context(), "archie:operator-7", "set limits actor=mallory")
if !strings.Contains(spoofReply, "Unknown or non-editable field") || client.command.RequestID != previousID {
t.Fatalf("actor spoof reply = %q, command unexpectedly dispatched", spoofReply)
}
unauthenticatedReply := command.Execute(t.Context(), "", "set limits retries=4")
if !strings.Contains(unauthenticatedReply, "authenticated Archie identity") || client.command.RequestID != previousID {
t.Fatalf("unauthenticated reply = %q, command unexpectedly dispatched", unauthenticatedReply)
}
}
func TestSettingsSetConflictDoesNotRetryAgainstANewerVersion(t *testing.T) {
client := &settingsClientStub{
descriptors: []SettingDescriptor{{Kind: "limits", Fields: map[string]SettingField{"retries": {Type: "integer"}}}},
resource: SettingResource{Kind: "limits", Version: 4, Value: map[string]any{"retries": float64(1)}},
commandErr: ErrSettingsConflict,
}
command := NewSettingsCommand(client)
reply := command.Execute(t.Context(), "archie:operator-7", "set limits retries=2")
if !strings.Contains(strings.ToLower(reply), "conflict") {
t.Fatalf("reply = %q, want conflict guidance", reply)
}
if !errors.Is(client.commandErr, ErrSettingsConflict) {
t.Fatal("stub setup lost conflict")
}
}
func TestSettingsReplaceAcceptsCollectionJSON(t *testing.T) {
client := &settingsClientStub{
descriptors: []SettingDescriptor{{Kind: "schedules"}},
resource: SettingResource{Kind: "schedules", Version: 3, Raw: []any{}},
}
reply := NewSettingsCommand(client).Execute(t.Context(), "archie:operator-7", `replace schedules [{"id":"daily"}]`)
if !strings.Contains(reply, "version 4") {
t.Fatalf("reply = %q", reply)
}
values, ok := client.command.RawValue.([]any)
if !ok || len(values) != 1 || client.command.ExpectedVersion != 3 {
t.Fatalf("command = %+v", client.command)
}
}
+2 -5
View File
@@ -558,11 +558,8 @@ func TestBaselineFixCapturesItsOwnCommit(t *testing.T) {
} }
} }
// TestCaptureIsNeverCallableFromTrees makes the constraint explicit in code, // TestCaptureIsNeverCallableFromTrees keeps capture reporting out of the core
// next to the type that must not grow past it: the capture is an optional, // workflow execution contract.
// unexported capability, and Trees -- the surface interpreted stage code is
// handed -- must not name it. wfextract's reachability test proves the same
// thing from the interpreted side.
func TestCaptureIsNeverCallableFromTrees(t *testing.T) { func TestCaptureIsNeverCallableFromTrees(t *testing.T) {
if _, ok := any((*fakeTrees)(nil)).(changeStatsReader); ok { if _, ok := any((*fakeTrees)(nil)).(changeStatsReader); ok {
t.Error("fakeTrees satisfies the capture capability; the degrade test above would be vacuous") t.Error("fakeTrees satisfies the capture capability; the degrade test above would be vacuous")
+185
View File
@@ -0,0 +1,185 @@
package workflow
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"sort"
"strings"
"gopkg.in/yaml.v3"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// YAMLDefinition is the portable, versioned workflow representation.
type YAMLDefinition struct {
ID string `yaml:"id" json:"id"`
Steps []StepRecord `yaml:"steps" json:"steps"`
}
// StepRecord selects one registered step type and supplies its typed settings.
type StepRecord struct {
Type string `yaml:"type" json:"type"`
Settings yaml.Node `yaml:"settings,omitempty" json:"-"`
}
type StepFactory func(yaml.Node) (Stage, error)
// StepRegistry is the closed set of safe workflow operations available to YAML.
type StepRegistry map[string]StepFactory
// ParseDefinition strictly parses and validates one YAML workflow.
func ParseDefinition(src string, registry StepRegistry) (YAMLDefinition, error) {
var definition YAMLDefinition
decoder := yaml.NewDecoder(strings.NewReader(src))
decoder.KnownFields(true)
if err := decoder.Decode(&definition); err != nil {
return YAMLDefinition{}, fmt.Errorf("parse workflow YAML: %w", err)
}
if strings.TrimSpace(definition.ID) == "" {
return YAMLDefinition{}, fmt.Errorf("workflow id is required")
}
if len(definition.Steps) == 0 {
return YAMLDefinition{}, fmt.Errorf("workflow %q has no steps", definition.ID)
}
for i, step := range definition.Steps {
factory, ok := registry[step.Type]
if !ok {
return YAMLDefinition{}, fmt.Errorf("workflow %q step %d: unknown type %q", definition.ID, i+1, step.Type)
}
if _, err := factory(step.Settings); err != nil {
return YAMLDefinition{}, fmt.Errorf("workflow %q step %q settings: %w", definition.ID, step.Type, err)
}
}
return definition, nil
}
// Compile resolves a validated YAML definition to executable stages.
func Compile(definition YAMLDefinition, registry StepRegistry) (Workflow, error) {
stages := make([]Stage, 0, len(definition.Steps))
for _, step := range definition.Steps {
factory, ok := registry[step.Type]
if !ok {
return Workflow{}, fmt.Errorf("unknown workflow step type %q", step.Type)
}
stage, err := factory(step.Settings)
if err != nil {
return Workflow{}, fmt.Errorf("build workflow step %q: %w", step.Type, err)
}
stages = append(stages, stage)
}
return Workflow{Name: definition.ID, Stages: stages}, nil
}
// ParseAndCompile validates and compiles one definition in a single operation.
func ParseAndCompile(src string, registry StepRegistry) (Workflow, error) {
definition, err := ParseDefinition(src, registry)
if err != nil {
return Workflow{}, err
}
return Compile(definition, registry)
}
// DigestDefinition returns the immutable content identity stored with a run.
func DigestDefinition(src string) string {
sum := sha256.Sum256([]byte(src))
return hex.EncodeToString(sum[:])
}
// WorkflowDefinitionEntry and WorkflowDefinitionCollection are defined in
// package task so dashboards can decode the stored projection without linking
// the engine. Validation and compilation stay here.
type (
WorkflowDefinitionEntry = task.WorkflowDefinitionEntry
WorkflowDefinitionCollection = task.WorkflowDefinitionCollection
)
// ValidateDefinitionCollection rejects malformed, duplicate, or mismatched definitions.
func ValidateDefinitionCollection(collection WorkflowDefinitionCollection, registry StepRegistry) error {
seen := make(map[string]struct{}, len(collection.Definitions))
for _, entry := range collection.Definitions {
if _, ok := seen[entry.ID]; ok {
return fmt.Errorf("duplicate workflow id %q", entry.ID)
}
seen[entry.ID] = struct{}{}
definition, err := ParseDefinition(entry.YAML, registry)
if err != nil {
return err
}
if definition.ID != entry.ID {
return fmt.Errorf("workflow entry id %q does not match YAML id %q", entry.ID, definition.ID)
}
}
return nil
}
// DecodeDefinitionCollection strictly decodes the control-plane projection.
func DecodeDefinitionCollection(value []byte, registry StepRegistry) (WorkflowDefinitionCollection, error) {
var collection WorkflowDefinitionCollection
decoder := json.NewDecoder(bytes.NewReader(value))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&collection); err != nil {
return WorkflowDefinitionCollection{}, err
}
if err := ValidateDefinitionCollection(collection, registry); err != nil {
return WorkflowDefinitionCollection{}, err
}
return collection, nil
}
func noSettingsFactory(stage Stage) StepFactory {
return func(settings yaml.Node) (Stage, error) {
if settings.Kind != 0 {
var value map[string]any
if err := settings.Decode(&value); err != nil {
return Stage{}, err
}
if len(value) != 0 {
return Stage{}, fmt.Errorf("step type accepts no settings")
}
}
return stage, nil
}
}
// BuiltinStepRegistry exposes every shipped stage as a typed, non-interpreted step.
func BuiltinStepRegistry() StepRegistry {
registry := StepRegistry{}
for id, wf := range legacyBuiltinWorkflows() {
for _, stage := range wf.Stages {
registry[id+"."+stage.Name] = noSettingsFactory(stage)
}
}
return registry
}
// ShippedDefinitions returns the restorable factory definitions.
func ShippedDefinitions() WorkflowDefinitionCollection {
workflows := legacyBuiltinWorkflows()
ids := make([]string, 0, len(workflows))
for id := range workflows {
ids = append(ids, id)
}
sort.Strings(ids)
collection := WorkflowDefinitionCollection{Definitions: make([]WorkflowDefinitionEntry, 0, len(ids))}
for _, id := range ids {
wf := workflows[id]
var builder strings.Builder
fmt.Fprintf(&builder, "id: %s\nsteps:\n", id)
for _, stage := range wf.Stages {
fmt.Fprintf(&builder, " - type: %s.%s\n", id, stage.Name)
}
collection.Definitions = append(collection.Definitions, WorkflowDefinitionEntry{ID: id, YAML: builder.String()})
}
return collection
}
func legacyBuiltinWorkflows() Registry {
return Registry{
"bootstrap": Bootstrap(), "implement": Implement(), "tdd": TDD(),
"feasibility": Feasibility(), "triage": Triage(), "remediate": Remediate(),
}
}
@@ -0,0 +1,54 @@
package workflow
import (
"strings"
"testing"
)
func TestParseDefinitionRejectsUnsafeDefinitions(t *testing.T) {
registry := BuiltinStepRegistry()
for _, test := range []struct{ name, yaml, want string }{
{"unknown step", "id: custom\nsteps:\n - type: shell\n", "unknown type"},
{"malformed settings", "id: custom\nsteps:\n - type: implement.prepare\n settings:\n command: rm -rf /\n", "accepts no settings"},
{"unknown field", "id: custom\nscript: arbitrary-go\nsteps:\n - type: implement.prepare\n", "field script not found"},
} {
t.Run(test.name, func(t *testing.T) {
_, err := ParseDefinition(test.yaml, registry)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("ParseDefinition() error = %v, want containing %q", err, test.want)
}
})
}
}
func TestParseDefinitionAllowsRepeatingAnOperation(t *testing.T) {
definition, err := ParseDefinition("id: custom\nsteps:\n - type: implement.prepare\n - type: implement.prepare\n", BuiltinStepRegistry())
if err != nil {
t.Fatalf("ParseDefinition: %v", err)
}
if len(definition.Steps) != 2 {
t.Fatalf("steps = %d, want 2", len(definition.Steps))
}
}
func TestShippedDefinitionsPreserveStageOrder(t *testing.T) {
registry := BuiltinStepRegistry()
for id, legacy := range legacyBuiltinWorkflows() {
entry, ok := ShippedDefinitions().DefinitionByID(id)
if !ok {
t.Fatalf("missing shipped workflow %q", id)
}
compiled, err := ParseAndCompile(entry.YAML, registry)
if err != nil {
t.Fatalf("compile shipped workflow %q: %v", id, err)
}
if len(compiled.Stages) != len(legacy.Stages) {
t.Fatalf("%s stage count = %d, want %d", id, len(compiled.Stages), len(legacy.Stages))
}
for i := range legacy.Stages {
if compiled.Stages[i].Name != legacy.Stages[i].Name {
t.Fatalf("%s stage %d = %q, want %q", id, i, compiled.Stages[i].Name, legacy.Stages[i].Name)
}
}
}
}
@@ -0,0 +1,30 @@
package workflow
import (
"errors"
"fmt"
"time"
)
// ExecutionSettings are the limits captured when a workflow execution starts.
type ExecutionSettings struct {
MaxModelToolSteps int `json:"max_model_tool_steps"`
MaxRuntime time.Duration `json:"max_runtime"`
MaxConsecutiveGateFailures int `json:"max_consecutive_gate_failures"`
}
// Validate rejects negative limits. Zero preserves the established meaning of
// disabling that individual limit.
func (s ExecutionSettings) Validate() error {
var errs []error
if s.MaxModelToolSteps < 0 {
errs = append(errs, fmt.Errorf("max model/tool steps must not be negative"))
}
if s.MaxRuntime < 0 {
errs = append(errs, fmt.Errorf("max runtime must not be negative"))
}
if s.MaxConsecutiveGateFailures < 0 {
errs = append(errs, fmt.Errorf("max consecutive gate failures must not be negative"))
}
return errors.Join(errs...)
}
@@ -0,0 +1,27 @@
package workflow
import (
"testing"
"time"
)
func TestExecutionSettingsValidateRejectsNegativeLimits(t *testing.T) {
t.Parallel()
tests := []struct {
name string
settings ExecutionSettings
}{
{"steps", ExecutionSettings{MaxModelToolSteps: -1, MaxRuntime: time.Second, MaxConsecutiveGateFailures: 1}},
{"runtime", ExecutionSettings{MaxModelToolSteps: 1, MaxRuntime: -time.Second, MaxConsecutiveGateFailures: 1}},
{"gate failures", ExecutionSettings{MaxModelToolSteps: 1, MaxRuntime: time.Second, MaxConsecutiveGateFailures: -1}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
if err := tt.settings.Validate(); err == nil {
t.Fatal("Validate() = nil, want error")
}
})
}
}
+2 -7
View File
@@ -117,13 +117,8 @@ const remediationRoundCapBytes = 2000
// resumableTrees is the optional capability a Trees implementation offers // resumableTrees is the optional capability a Trees implementation offers
// for continuing work on an already-open PR branch instead of starting a // for continuing work on an already-open PR branch instead of starting a
// fresh worktree. Deliberately NOT part of the exported Trees interface, // fresh worktree. It stays separate because Trees is already at the interface
// for two reasons: Trees is projected into the Yaegi symbol table // size cap and most workflow stages do not need branch resumption.
// (wfextract) for repository-authored .archie/stages/*.go, and this
// capability must not become callable from there (mirrors changeStatsReader
// in steps.go); and Trees is already at golangci-lint's interfacebloat cap
// of 8 methods, which CLAUDE.md reserves for proto/gRPC surfaces, not
// growing Go interfaces further.
// //
// *worktree.Manager (real git access) and the container-mode hybrid // *worktree.Manager (real git access) and the container-mode hybrid
// implementation both already satisfy this structurally; a Trees // implementation both already satisfy this structurally; a Trees
+35
View File
@@ -282,6 +282,41 @@ func workflowForLabels(reg Registry, labels string) (Workflow, bool) {
return Workflow{}, false return Workflow{}, false
} }
// ResolveWorkflowID deterministically selects a definition without compiling
// or executing it. It is used before worker dispatch to pin the exact YAML.
func ResolveWorkflowID(t *Task, available map[string]struct{}, kinds KindWorkflows, labels LabelWorkflows) (string, error) {
if t.Workflow != "" {
if _, ok := available[t.Workflow]; ok {
return t.Workflow, nil
}
return "", fmt.Errorf("workflow %q is not defined", t.Workflow)
}
for _, label := range workintake.SplitLabels(t.Labels) {
if id := labels[label]; id != "" {
if _, ok := available[id]; ok {
return id, nil
}
}
}
if kinds == nil {
kinds = defaultKindWorkflows
}
for _, kind := range workintake.KindsForLabels(workintake.SplitLabels(t.Labels)) {
if id := kinds[kind]; id != "" {
if _, ok := available[id]; ok {
return id, nil
}
}
}
if _, ok := available["triage"]; ok {
return "triage", nil
}
if _, ok := available["implement"]; ok {
return "implement", nil
}
return "", fmt.Errorf("no routable workflow definition")
}
// LabelWorkflows maps a forge issue label to the registered workflow name // LabelWorkflows maps a forge issue label to the registered workflow name
// it prefers. This is the second slice of docs/prds/eda-playbook-engine.md: // it prefers. This is the second slice of docs/prds/eda-playbook-engine.md:
// the label vocabulary itself -- not just the closed bug/feature/bootstrap // the label vocabulary itself -- not just the closed bug/feature/bootstrap
@@ -1,201 +0,0 @@
// Package skillbuild constructs Workflows from skill catalog entries by
// loading Yaegi-interpreted stage plugins from the skill's plugins/ directory.
package skillbuild
import (
"context"
"fmt"
"log/slog"
"os"
"path/filepath"
"sort"
"strings"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfextract"
"github.com/samcharles93/archie-core/internal/skill"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// builtins returns the hardcoded fallback workflows. These are used when
// no skill declares a given workflow name in its metadata.archie.workflow.
func builtins() workflow.Registry {
return workflow.Registry{
"bootstrap": workflow.Bootstrap(),
"implement": workflow.Implement(),
"tdd": workflow.TDD(),
"feasibility": workflow.Feasibility(),
"triage": workflow.Triage(),
"remediate": workflow.Remediate(),
"default": workflow.Implement(),
}
}
// BuildRegistry scans .agents/skills/ for catalog entries that declare a
// workflow in metadata.archie.workflow, builds each from its stage plugins,
// and returns a complete workflow.Registry. Workflow names not covered by
// any skill fall back to the built-in Go definitions.
//
// Skills define workflows. Plugins define stages. The daemon composes them.
func BuildRegistry(worktree string) (workflow.Registry, error) {
catalog, err := BuildCatalog(worktree)
if err != nil {
return nil, err
}
return catalog.Registry, nil
}
// Catalog is the executable workflow registry together with the source that
// supplied each definition. The source remains separate from Workflow so
// executable stages stay free of dashboard-facing metadata.
type Catalog struct {
Registry workflow.Registry
Origins map[string]string
}
// BuildCatalog constructs the executable registry and records whether each
// definition remains bundled or was overridden by an installed skill.
func BuildCatalog(worktree string) (Catalog, error) {
reg := builtins()
origins := make(map[string]string, len(reg))
for id := range reg {
origins[id] = "builtin"
}
if err := mergeSkillWorkflows(worktree, reg, origins); err != nil {
return Catalog{}, err
}
return Catalog{Registry: reg, Origins: origins}, nil
}
// SkillWorkflow is the subset of a catalog entry needed to build a
// workflow from a skill's stage plugins.
type SkillWorkflow struct {
Workflow string // from metadata.archie.workflow
Dir string // skill directory name
}
// mergeSkillWorkflows scans worktree for skill catalog entries that
// declare a workflow, builds each from its stage plugins, and merges the
// result into reg in place. A skill whose workflow has no stages yet
// (declared intent, no plugins/ directory) leaves reg's existing entry
// (built-in or base) untouched.
func mergeSkillWorkflows(worktree string, reg workflow.Registry, origins map[string]string) error {
catalog, err := skill.Catalog(worktree)
if err != nil {
return fmt.Errorf("skill catalog: %w", err)
}
seenFromSkill := make(map[string]string) // workflow -> skill dir
for _, entry := range catalog {
if entry.Workflow == "" {
continue
}
sw := SkillWorkflow{Workflow: entry.Workflow, Dir: entry.Dir}
wf, err := BuildWorkflow(worktree, sw)
if err != nil {
slog.Default().Warn(
"skipping broken skill workflow",
"workflow", entry.Workflow,
"skill", entry.Dir,
"err", err,
)
continue
}
if len(wf.Stages) > 0 {
// Only warn when TWO SKILLS declare the same workflow name.
// Overriding a built-in name is routine -- don't log.
if prevSkill, dup := seenFromSkill[entry.Workflow]; dup {
slog.Default().Warn(
"duplicate workflow name across skills -- overriding",
"workflow", entry.Workflow,
"skill", entry.Dir,
"previous_skill", prevSkill,
)
}
seenFromSkill[entry.Workflow] = entry.Dir
reg[entry.Workflow] = wf
if origins != nil {
origins[entry.Workflow] = "skill:" + entry.Dir
}
}
}
return nil
}
// BuildWorkflow loads stage plugins from a skill's plugins/ directory
// and returns a workflow.Workflow. Stages are Yaegi-interpreted .go files
// sorted by filename. Each file must export:
//
// func Stage() workflow.Stage
func BuildWorkflow(worktree string, entry SkillWorkflow) (workflow.Workflow, error) {
pluginsDir := filepath.Join(worktree, ".agents", "skills", entry.Dir, "plugins")
entries, err := os.ReadDir(pluginsDir)
if os.IsNotExist(err) {
return workflow.Workflow{Name: entry.Workflow}, nil
}
if err != nil {
return workflow.Workflow{}, fmt.Errorf("read plugins dir %s: %w", pluginsDir, err)
}
var names []string
for _, e := range entries {
if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") {
names = append(names, e.Name())
}
}
sort.Strings(names)
// Each plugin file is package main defining Stage() -- they must be
// evaluated in separate interpreters to avoid symbol collisions.
stages := make([]workflow.Stage, 0, len(names))
for _, name := range names {
path := filepath.Join(pluginsDir, name)
src, err := os.ReadFile(path)
if err != nil {
slog.Default().Warn("skipping unreadable stage plugin", "plugin", name, "err", err)
continue
}
stage, err := loadStage(name, string(src))
if err != nil {
slog.Default().Warn("skipping broken stage plugin", "plugin", name, "err", err)
continue
}
stages = append(stages, stage)
}
return workflow.Workflow{Name: entry.Workflow, Stages: stages}, nil
}
// loadStage interprets a single .go plugin source via Yaegi and calls its
// exported Stage(). filename is used only for interpreter panic messages.
func loadStage(filename, src string) (workflow.Stage, error) {
return yaegiutil.Safe(filename, func() (workflow.Stage, error) {
i, err := yaegiutil.New(interp.Options{}, wfextract.Symbols)
if err != nil {
return workflow.Stage{}, err
}
if _, err := i.Eval(src); err != nil {
return workflow.Stage{}, fmt.Errorf("evaluate: %w", err)
}
v, err := i.Eval("main.Stage")
if err != nil {
return workflow.Stage{}, fmt.Errorf("does not export main.Stage: %w", err)
}
if fn, ok := v.Interface().(func() workflow.Stage); ok {
return fn(), nil
}
// Fallback for test plugins: func() (string, func(...) error).
// NOTE: this constructs Stage with positional fields. If Stage
// gains new fields in the future, this path will silently zero-
// value them. Prefer func() workflow.Stage in production plugins.
if rawFn, ok := v.Interface().(func() (string, func(context.Context, *workflow.TaskContext) error)); ok {
name, run := rawFn()
return workflow.Stage{Name: name, Run: run}, nil
}
return workflow.Stage{}, fmt.Errorf("main.Stage is %T, want func() workflow.Stage", v.Interface())
})
}
@@ -1,864 +0,0 @@
package skillbuild
import (
"context"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// ── workflows built from skill plugins ────────────────────────────────
func TestBuildWorkflowFromSkillPlugins(t *testing.T) {
dir := t.TempDir()
skillDir := filepath.Join(dir, ".agents", "skills", "archie-wf-greet")
pluginsDir := filepath.Join(skillDir, "plugins")
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(`---
name: archie-wf-greet
description: A custom greeting workflow built entirely from plugins.
version: 1.0.0
metadata:
archie:
workflow: greet
---
Greet the world, then say goodbye.
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(pluginsDir, "01-hello.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "hello", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "hello from plugin"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(pluginsDir, "02-world.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "world", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = tc.BuildSummary + " world"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
entry := SkillWorkflow{Workflow: "greet", Dir: "archie-wf-greet"}
wf, err := BuildWorkflow(dir, entry)
if err != nil {
t.Fatal(err)
}
if wf.Name != "greet" {
t.Errorf("Workflow.Name = %q, want greet", wf.Name)
}
if len(wf.Stages) != 2 {
t.Fatalf("got %d stages, want 2", len(wf.Stages))
}
if wf.Stages[0].Name != "hello" {
t.Errorf("stage[0].Name = %q, want hello", wf.Stages[0].Name)
}
if wf.Stages[1].Name != "world" {
t.Errorf("stage[1].Name = %q, want world", wf.Stages[1].Name)
}
// Run the workflow -- stages must execute in order.
tc := &workflow.TaskContext{BuildSummary: ""}
for _, s := range wf.Stages {
if err := s.Run(context.Background(), tc); err != nil {
t.Fatalf("stage %s failed: %v", s.Name, err)
}
}
if tc.BuildSummary != "hello from plugin world" {
t.Errorf("BuildSummary = %q, want 'hello from plugin world'", tc.BuildSummary)
}
}
func TestBuildWorkflowMissingSkillReturnsEmptyWorkflow(t *testing.T) {
// Missing plugins directory is not an error -- same pattern as
// wfeval.Discover. Returns a Workflow with no stages.
entry := SkillWorkflow{Workflow: "nonexistent", Dir: "nonexistent"}
wf, err := BuildWorkflow(t.TempDir(), entry)
if err != nil {
t.Fatal(err)
}
if len(wf.Stages) != 0 {
t.Errorf("got %d stages, want 0 for nonexistent skill", len(wf.Stages))
}
}
func TestBuildCatalogMarksBuiltinWorkflowOrigins(t *testing.T) {
catalog, err := BuildCatalog(t.TempDir())
if err != nil {
t.Fatal(err)
}
if got := catalog.Origins["implement"]; got != "builtin" {
t.Errorf("implement origin = %q, want builtin", got)
}
}
// ── registry built from skill catalog ────────────────────────────────
func TestBuildRegistryFromSkillCatalog(t *testing.T) {
// When .agents/skills/ contains directories with metadata.archie.workflow,
// BuildRegistry must return a workflow.Registry with those workflows
// built from their stage plugins. Workflows not declared by any skill
// fall back to the built-in definitions (bootstrap, implement, tdd,
// feasibility, default→implement).
dir := t.TempDir()
// Skill 1: archie-wf-greet -- plugin-defined workflow.
greetDir := filepath.Join(dir, ".agents", "skills", "archie-wf-greet", "plugins")
if err := os.MkdirAll(greetDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(greetDir, "01-hello.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "hello", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "greet-plugin-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(filepath.Dir(greetDir), "SKILL.md"), []byte(`---
name: archie-wf-greet
description: Greet workflow from plugins
version: 1.0.0
metadata:
archie:
workflow: greet
---
Greet the user.
`), 0o644); err != nil {
t.Fatal(err)
}
// Skill 2: archie-wf-implement -- overrides the built-in implement workflow.
implDir := filepath.Join(dir, ".agents", "skills", "archie-wf-custom-impl", "plugins")
if err := os.MkdirAll(implDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(implDir, "01-plan.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "custom-plan", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "custom-impl-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(filepath.Dir(implDir), "SKILL.md"), []byte(`---
name: archie-wf-custom-impl
description: Custom implement workflow
version: 1.0.0
metadata:
archie:
workflow: implement
---
Custom implementation workflow.
`), 0o644); err != nil {
t.Fatal(err)
}
catalog, err := BuildCatalog(dir)
if err != nil {
t.Fatal(err)
}
reg := catalog.Registry
// Skill-defined workflows must be present.
t.Run("skill-defined workflow is registered", func(t *testing.T) {
wf, ok := reg["greet"]
if !ok {
t.Fatal("BuildRegistry did not register workflow 'greet' from skill catalog")
}
if wf.Name != "greet" {
t.Errorf("Workflow.Name = %q, want greet", wf.Name)
}
if len(wf.Stages) == 0 {
t.Error("workflow 'greet' has no stages -- plugin stages not loaded")
}
// Run it -- stages must execute.
tc := &workflow.TaskContext{BuildSummary: ""}
for _, s := range wf.Stages {
if err := s.Run(context.Background(), tc); err != nil {
t.Fatalf("stage %s: %v", s.Name, err)
}
}
if tc.BuildSummary != "greet-plugin-ran" {
t.Errorf("BuildSummary = %q, want 'greet-plugin-ran'", tc.BuildSummary)
}
})
if got := catalog.Origins["greet"]; got != "skill:archie-wf-greet" {
t.Errorf("greet origin = %q, want skill:archie-wf-greet", got)
}
// Skill override of built-in must take precedence.
t.Run("skill overrides built-in workflow", func(t *testing.T) {
wf, ok := reg["implement"]
if !ok {
t.Fatal("BuildRegistry did not register workflow 'implement'")
}
if len(wf.Stages) == 0 {
t.Fatal("workflow 'implement' has no stages")
}
tc := &workflow.TaskContext{BuildSummary: ""}
for _, s := range wf.Stages {
if err := s.Run(context.Background(), tc); err != nil {
t.Fatalf("stage %s: %v", s.Name, err)
}
}
if tc.BuildSummary != "custom-impl-ran" {
t.Errorf("BuildSummary = %q, want 'custom-impl-ran' -- skill override did not take effect", tc.BuildSummary)
}
})
// Built-in fallback: tdd is not declared by any skill.
t.Run("built-in fallback for undeclared workflow", func(t *testing.T) {
wf, ok := reg["tdd"]
if !ok {
t.Fatal("BuildRegistry missing built-in fallback for 'tdd'")
}
if wf.Name != "tdd" {
t.Errorf("Workflow.Name = %q, want tdd", wf.Name)
}
if len(wf.Stages) == 0 {
t.Error("built-in tdd workflow has no stages")
}
})
// "default" key must always exist.
t.Run("default key exists", func(t *testing.T) {
wf, ok := reg["default"]
if !ok {
t.Fatal("BuildRegistry missing 'default' workflow key")
}
if len(wf.Stages) == 0 {
t.Error("default workflow has no stages")
}
})
}
func TestBuildRegistryNoSkillsReturnsBuiltins(t *testing.T) {
// When .agents/skills/ does not exist, BuildRegistry returns the
// built-in workflow set so the daemon can still route tasks.
reg, err := BuildRegistry(t.TempDir())
if err != nil {
t.Fatal(err)
}
builtins := []string{"bootstrap", "implement", "tdd", "feasibility", "default"}
for _, name := range builtins {
wf, ok := reg[name]
if !ok {
t.Errorf("BuildRegistry missing built-in workflow %q when no skills exist", name)
continue
}
if wf.Name != name && (name != "default" || wf.Name != "implement") {
t.Errorf("built-in %q: Name = %q, want %q", name, wf.Name, name)
}
}
}
func TestBuildRegistrySkillWithNoWorkflowDeclaredIsIgnored(t *testing.T) {
// A skill directory without metadata.archie.workflow must not
// produce a registry entry. It's a utility skill, not a workflow.
dir := t.TempDir()
skillDir := filepath.Join(dir, ".agents", "skills", "archie-wf-utils")
if err := os.MkdirAll(skillDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(`---
name: archie-wf-utils
description: Utility helpers, not a workflow
version: 1.0.0
metadata:
archie:
tools: [go]
---
Utility content.
`), 0o644); err != nil {
t.Fatal(err)
}
reg, err := BuildRegistry(dir)
if err != nil {
t.Fatal(err)
}
// There is no workflow called "utils" because the skill didn't declare one.
if _, ok := reg["utils"]; ok {
t.Error("BuildRegistry registered 'utils' as a workflow, but the skill " +
"did not declare metadata.archie.workflow -- only skills that declare " +
"a workflow should produce registry entries")
}
// Built-ins must still be present.
if _, ok := reg["implement"]; !ok {
t.Error("built-in 'implement' missing when a non-workflow skill exists")
}
}
func TestBuildRegistryEmptySkillsDirReturnsBuiltins(t *testing.T) {
// An empty .agents/skills/ directory must not cause an error.
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, ".agents", "skills"), 0o755); err != nil {
t.Fatal(err)
}
reg, err := BuildRegistry(dir)
if err != nil {
t.Fatal(err)
}
if _, ok := reg["implement"]; !ok {
t.Error("built-in 'implement' missing when skills dir is empty")
}
}
func TestBuildRegistryNoStagesReturnsEmptyWorkflow(t *testing.T) {
dir := t.TempDir()
skillDir := filepath.Join(dir, ".agents", "skills", "archie-wf-empty")
if err := os.MkdirAll(skillDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(`---
name: archie-wf-empty
description: No stages
version: 1.0.0
metadata:
archie:
workflow: empty
---
Body.
`), 0o644); err != nil {
t.Fatal(err)
}
entry := SkillWorkflow{Workflow: "empty", Dir: "archie-wf-empty"}
wf, err := BuildWorkflow(dir, entry)
if err != nil {
t.Fatal(err)
}
if len(wf.Stages) != 0 {
t.Errorf("got %d stages, want 0", len(wf.Stages))
}
if wf.Name != "empty" {
t.Errorf("Workflow.Name = %q, want empty", wf.Name)
}
}
// ── resilience: skip broken plugins, don't abort ────────────────────
func TestBuildWorkflowSkipsBrokenPlugin(t *testing.T) {
// R2: one broken stage plugin must not abort the entire workflow.
// Valid plugins before and after the broken one must still load.
dir := t.TempDir()
pluginsDir := filepath.Join(dir, ".agents", "skills", "archie-wf-resilient", "plugins")
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
t.Fatal(err)
}
// First plugin -- valid.
if err := os.WriteFile(filepath.Join(pluginsDir, "01-setup.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "setup", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "setup-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
// Second plugin -- BROKEN (syntax error).
if err := os.WriteFile(filepath.Join(pluginsDir, "02-broken.go"), []byte(`package main
this is %% NOT VALID GO @@@@
`), 0o644); err != nil {
t.Fatal(err)
}
// Third plugin -- valid.
if err := os.WriteFile(filepath.Join(pluginsDir, "03-teardown.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "teardown", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = tc.BuildSummary + " teardown-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(filepath.Dir(pluginsDir), "SKILL.md"), []byte(`---
name: archie-wf-resilient
description: Resilient workflow
version: 1.0.0
metadata:
archie:
workflow: resilient
---
Resilient workflow.
`), 0o644); err != nil {
t.Fatal(err)
}
entry := SkillWorkflow{Workflow: "resilient", Dir: "archie-wf-resilient"}
wf, err := BuildWorkflow(dir, entry)
if err != nil {
t.Fatalf("BuildWorkflow returned error instead of skipping broken plugin: %v", err)
}
if len(wf.Stages) != 2 {
t.Fatalf("got %d stages, want 2 (broken plugin skipped)", len(wf.Stages))
}
if wf.Stages[0].Name != "setup" {
t.Errorf("stage[0].Name = %q, want setup", wf.Stages[0].Name)
}
if wf.Stages[1].Name != "teardown" {
t.Errorf("stage[1].Name = %q, want teardown", wf.Stages[1].Name)
}
// Run the surviving stages.
tc := &workflow.TaskContext{BuildSummary: ""}
for _, s := range wf.Stages {
if err := s.Run(context.Background(), tc); err != nil {
t.Fatalf("stage %s: %v", s.Name, err)
}
}
if tc.BuildSummary != "setup-ran teardown-ran" {
t.Errorf("BuildSummary = %q, want 'setup-ran teardown-ran'", tc.BuildSummary)
}
}
// ── duplicate warning suppression for builtin overrides ─────────────
// slogCaptureHandler is a slog.Handler that captures log records in a
// slice for inspection in tests. It writes log output to the test log
// instead of stderr to avoid infinite recursion through the log bridge.
type slogCaptureHandler struct {
records []slog.Record
t *testing.T
}
func (h *slogCaptureHandler) Enabled(ctx context.Context, level slog.Level) bool {
return true
}
func (h *slogCaptureHandler) Handle(ctx context.Context, r slog.Record) error {
h.records = append(h.records, r)
h.t.Log(r.Level.String() + " " + r.Message)
return nil
}
func (h *slogCaptureHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return h
}
func (h *slogCaptureHandler) WithGroup(name string) slog.Handler {
return h
}
// setSlogCapture sets the default slog.Logger to one that captures all
// records and returns the handler for inspection. The previous logger
// is restored when t.Cleanup runs.
func setSlogCapture(t *testing.T) *slogCaptureHandler {
t.Helper()
prev := slog.Default()
h := &slogCaptureHandler{t: t}
slog.SetDefault(slog.New(h))
t.Cleanup(func() { slog.SetDefault(prev) })
return h
}
func TestMergeSkillWorkflows_NoWarningOnBuiltinOverride(t *testing.T) {
// A skill overriding a built-in workflow name (e.g. "implement")
// must NOT produce a "duplicate workflow name" warning. Builtin
// overrides are routine and expected.
dir := t.TempDir()
skillDir := filepath.Join(dir, ".agents", "skills", "archie-wf-implement")
pluginsDir := filepath.Join(skillDir, "plugins")
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(`---
name: archie-wf-implement
description: Custom implement workflow
version: 1.0.0
metadata:
archie:
workflow: implement
---
Custom implement.
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(pluginsDir, "01-custom.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "custom", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "custom-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
capture := setSlogCapture(t)
reg := builtins()
if err := mergeSkillWorkflows(dir, reg, nil); err != nil {
t.Fatal(err)
}
// Override must take effect.
wf, ok := reg["implement"]
if !ok {
t.Fatal("'implement' missing from registry")
}
if len(wf.Stages) != 1 {
t.Fatalf("got %d stages, want 1", len(wf.Stages))
}
if wf.Stages[0].Name != "custom" {
t.Errorf("stage[0].Name = %q, want custom", wf.Stages[0].Name)
}
// No "duplicate" warning must have been logged.
for _, r := range capture.records {
if r.Level >= slog.LevelWarn && strings.Contains(r.Message, "duplicate") {
t.Errorf("unexpected 'duplicate' warning on builtin override: %s", r.Message)
}
}
}
func TestMergeSkillWorkflows_WarnsOnTwoSkillsSameWorkflow(t *testing.T) {
// When TWO DIFFERENT SKILLS declare the same workflow name, the
// second one must produce a warning. This is a genuine conflict.
dir := t.TempDir()
// Skill 1: declares workflow "custom"
skill1 := filepath.Join(dir, ".agents", "skills", "archie-wf-custom-a")
plugins1 := filepath.Join(skill1, "plugins")
if err := os.MkdirAll(plugins1, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skill1, "SKILL.md"), []byte(`---
name: archie-wf-custom-a
description: First custom workflow
version: 1.0.0
metadata:
archie:
workflow: custom
---
First.
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(plugins1, "01-first.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "first", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "first-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
// Skill 2: also declares workflow "custom"
skill2 := filepath.Join(dir, ".agents", "skills", "archie-wf-custom-b")
plugins2 := filepath.Join(skill2, "plugins")
if err := os.MkdirAll(plugins2, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skill2, "SKILL.md"), []byte(`---
name: archie-wf-custom-b
description: Second custom workflow
version: 1.0.0
metadata:
archie:
workflow: custom
---
Second.
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(plugins2, "01-second.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "second", func(ctx context.Context, tc *workflow.TaskContext) error {
tc.BuildSummary = "second-ran"
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
capture := setSlogCapture(t)
reg := make(workflow.Registry)
if err := mergeSkillWorkflows(dir, reg, nil); err != nil {
t.Fatal(err)
}
// Last-write-wins: second skill's stages should be used.
wf, ok := reg["custom"]
if !ok {
t.Fatal("'custom' missing from registry")
}
if len(wf.Stages) != 1 {
t.Fatalf("got %d stages, want 1", len(wf.Stages))
}
if wf.Stages[0].Name != "second" {
t.Errorf("stage[0].Name = %q, want second (last-write-wins)", wf.Stages[0].Name)
}
// Exactly one warning containing both skill dirs must have been logged.
var warnings []slog.Record
for _, r := range capture.records {
if r.Level >= slog.LevelWarn && strings.Contains(r.Message, "duplicate") {
warnings = append(warnings, r)
}
}
if len(warnings) != 1 {
t.Fatalf("got %d duplicate warnings, want exactly 1", len(warnings))
}
w := warnings[0]
hasSkill := false
hasPrev := false
w.Attrs(func(a slog.Attr) bool {
if a.Key == "skill" && strings.Contains(a.Value.String(), "archie-wf-custom-b") {
hasSkill = true
}
if a.Key == "previous_skill" && strings.Contains(a.Value.String(), "archie-wf-custom-a") {
hasPrev = true
}
return true
})
if !hasSkill {
t.Error("warning missing 'skill' key with second skill dir")
}
if !hasPrev {
t.Error("warning missing 'previous_skill' key with first skill dir")
}
}
// TestBuildRegistry_NoWarningOnBuiltinOverride is an integration-style
// test that validates the warning is absent when a skill overrides the
// built-in "implement" workflow via BuildRegistry.
func TestBuildRegistry_NoWarningOnBuiltinOverride(t *testing.T) {
dir := t.TempDir()
skillDir := filepath.Join(dir, ".agents", "skills", "archie-wf-implement")
pluginsDir := filepath.Join(skillDir, "plugins")
if err := os.MkdirAll(pluginsDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(skillDir, "SKILL.md"), []byte(`---
name: archie-wf-implement
description: Custom implement
version: 1.0.0
metadata:
archie:
workflow: implement
---
Custom.
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(pluginsDir, "01-custom.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "custom-stage", func(ctx context.Context, tc *workflow.TaskContext) error {
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
capture := setSlogCapture(t)
reg, err := BuildRegistry(dir)
if err != nil {
t.Fatal(err)
}
wf, ok := reg["implement"]
if !ok {
t.Fatal("'implement' missing from registry")
}
if len(wf.Stages) != 1 {
t.Fatalf("got %d stages, want 1 from skill override", len(wf.Stages))
}
if wf.Stages[0].Name != "custom-stage" {
t.Errorf("stage[0].Name = %q, want custom-stage", wf.Stages[0].Name)
}
for _, r := range capture.records {
if r.Level >= slog.LevelWarn && strings.Contains(r.Message, "duplicate") {
t.Errorf("unexpected 'duplicate' warning via BuildRegistry on builtin override: %s", r.Message)
}
}
}
func TestBuildRegistrySkipsBrokenSkill(t *testing.T) {
// R2: a skill with broken plugins must not prevent other skills
// from registering -- and must not block daemon startup.
dir := t.TempDir()
// Skill 1: valid workflow.
goodDir := filepath.Join(dir, ".agents", "skills", "archie-wf-good", "plugins")
if err := os.MkdirAll(goodDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(goodDir, "01-step.go"), []byte(`package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() (string, func(context.Context, *workflow.TaskContext) error) {
return "step", func(ctx context.Context, tc *workflow.TaskContext) error {
return nil
}
}
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(filepath.Dir(goodDir), "SKILL.md"), []byte(`---
name: archie-wf-good
description: Good workflow
version: 1.0.0
metadata:
archie:
workflow: good
---
Good.
`), 0o644); err != nil {
t.Fatal(err)
}
// Skill 2: broken plugins -- ALL plugins are broken.
badDir := filepath.Join(dir, ".agents", "skills", "archie-wf-bad", "plugins")
if err := os.MkdirAll(badDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(badDir, "01-broken.go"), []byte(`package main
%%% SYNTAX ERROR @@@
`), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(filepath.Dir(badDir), "SKILL.md"), []byte(`---
name: archie-wf-bad
description: Broken workflow
version: 1.0.0
metadata:
archie:
workflow: bad
---
Broken.
`), 0o644); err != nil {
t.Fatal(err)
}
reg, err := BuildRegistry(dir)
if err != nil {
t.Fatalf("BuildRegistry returned error instead of skipping broken skill: %v", err)
}
// Good workflow must still be registered.
if _, ok := reg["good"]; !ok {
t.Error("'good' workflow missing -- broken skill blocked registry build")
}
// Bad workflow must not be registered (it had no valid stages).
if _, ok := reg["bad"]; ok {
// It might fall back to built-in "bad" -- that's fine.
// But it should NOT be the empty workflow from the broken skill.
t.Log("'bad' workflow present (may be built-in fallback)")
}
// Built-in fallbacks must still exist.
if _, ok := reg["implement"]; !ok {
t.Error("built-in 'implement' missing after broken skill was skipped")
}
}
+18 -71
View File
@@ -5,13 +5,10 @@ import (
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"time" "time"
"github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gate"
"github.com/samcharles93/archie-core/internal/gate/gateeval"
) )
// Shared step library. Every workflow composes these; workflow-specific // Shared step library. Every workflow composes these; workflow-specific
@@ -32,12 +29,10 @@ const (
) )
// changeStatsReader is the optional capability through which a Trees // changeStatsReader is the optional capability through which a Trees
// implementation reports what an attempt changed. It is deliberately // implementation reports what an attempt changed. It stays separate from the
// unexported, and deliberately NOT a method on Trees: Trees is projected into // core Trees contract because capture is reporting, not workflow execution. A
// the interpreted-stage symbol table, so declaring it there would widen what // Trees implementation without it degrades to no capture rather than failing
// repository-authored .archie/stages/*.go may call (pinned by // the stage.
// wfextract/reachability_test.go). A Trees implementation without it degrades
// to no capture rather than failing the stage.
type changeStatsReader interface { type changeStatsReader interface {
ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error) ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error)
} }
@@ -209,78 +204,30 @@ func StageDiffCap() Stage {
}} }}
} }
// StageRepoStages runs every custom stage the repo defines under // StageRepoStages rejects obsolete repository-authored Go stages.
// .archie/stages/*.go (Yaegi-interpreted via TaskContext.CustomStages),
// in the order the loader returns them -- a no-op when no loader is wired
// up or the repo defines none. A custom stage that sets tc.Outcome ends
// the workflow there, same as any built-in stage.
func StageRepoStages() Stage { func StageRepoStages() Stage {
return Stage{Name: "repo-stages", Run: func(ctx context.Context, tc *TaskContext) error { return Stage{Name: "repo-stages", Run: func(_ context.Context, tc *TaskContext) error {
if tc.CustomStages == nil { stages, err := filepath.Glob(filepath.Join(tc.Dir, ".archie", "stages", "*.go"))
return nil
}
stages, err := tc.CustomStages(tc.Dir)
if err != nil { if err != nil {
return fmt.Errorf("repo stages: %w", err) return fmt.Errorf("inspect legacy repository stages: %w", err)
} }
for _, s := range stages { if len(stages) > 0 {
tc.Log.Info("repo stage starting", "stage", s.Name) return fmt.Errorf("legacy .archie/stages/*.go is unsupported; migrate repository behavior to database-backed YAML workflow steps")
if err := s.Run(ctx, tc); err != nil {
return fmt.Errorf("repo stage %s: %w", s.Name, err)
}
if tc.Outcome.Status != "" {
return nil
}
} }
return nil return nil
}} }}
} }
// StageYaegiGate evaluates the repo's optional .archie/gate.go -- a // StageYaegiGate rejects the obsolete interpreted gate rather than silently
// Yaegi-interpreted Go file inspecting the committed diff for // omitting behavior that cannot be represented by the typed registry.
// project-specific rules shell gate commands can't express (AST checks,
// diff scanning). A missing script is a no-op. Error-level findings
// park the task; warn-level findings are logged only.
func StageYaegiGate() Stage { func StageYaegiGate() Stage {
return Stage{Name: "custom-gate", Run: func(ctx context.Context, tc *TaskContext) error { return Stage{Name: "custom-gate", Run: func(_ context.Context, tc *TaskContext) error {
base := tc.Repo.BaseBranch() _, err := os.Stat(filepath.Join(tc.Dir, ".archie", "gate.go"))
diff, err := tc.Trees.Diff(ctx, tc.Dir, base) if err == nil {
if err != nil { return fmt.Errorf("legacy .archie/gate.go is unsupported; migrate its behavior to a registered YAML workflow step")
return fmt.Errorf("custom gate: diff against %s: %w", base, err)
} }
files, err := tc.Trees.ChangedFiles(ctx, tc.Dir, base) if !os.IsNotExist(err) {
if err != nil { return fmt.Errorf("inspect legacy .archie/gate.go: %w", err)
return fmt.Errorf("custom gate: changed files against %s: %w", base, err)
}
findings, err := gateeval.Evaluate(gate.GateContext{
Diff: diff,
ChangedFiles: files,
Dir: tc.Dir,
BaseRef: "origin/" + base,
Repo: tc.Repo.FullName(),
})
if err != nil {
return fmt.Errorf("custom gate: %w", err)
}
var blocking []string
for _, f := range findings {
if err := f.Validate(); err != nil {
return fmt.Errorf("custom gate: %w", err)
}
loc := f.File
if f.Line > 0 {
loc = fmt.Sprintf("%s:%d", f.File, f.Line)
}
msg := strings.TrimSpace(loc + ": " + f.Message)
if f.Blocking() {
blocking = append(blocking, msg)
}
tc.Log.Info("custom gate finding", "level", f.Level, "file", f.File, "line", f.Line, "message", f.Message)
}
if len(blocking) > 0 {
return fmt.Errorf("custom gate: %s", strings.Join(blocking, "; "))
} }
return nil return nil
}} }}
+12 -45
View File
@@ -2,7 +2,6 @@ package workflow
import ( import (
"context" "context"
"errors"
"log/slog" "log/slog"
"os" "os"
"os/exec" "os/exec"
@@ -135,8 +134,8 @@ func Check(ctx gate.GateContext) []gate.Finding {
runGit(t, dir, "commit", "-m", "add notes") runGit(t, dir, "commit", "-m", "add notes")
tc := newYaegiGateTaskContext(t, dir) tc := newYaegiGateTaskContext(t, dir)
if err := StageYaegiGate().Run(context.Background(), tc); err != nil { if err := StageYaegiGate().Run(context.Background(), tc); err == nil {
t.Fatalf("StageYaegiGate() = %v, want nil (warn findings don't block)", err) t.Fatal("StageYaegiGate() = nil, want legacy gate rejection")
} }
} }
@@ -173,57 +172,25 @@ func TestStageRepoStagesNilLoaderIsNoop(t *testing.T) {
} }
func TestStageRepoStagesRunsAllInOrder(t *testing.T) { func TestStageRepoStagesRunsAllInOrder(t *testing.T) {
var ran []string dir := t.TempDir()
tc := &TaskContext{ if err := os.MkdirAll(filepath.Join(dir, ".archie", "stages"), 0o755); err != nil {
Log: slog.New(slog.DiscardHandler), t.Fatal(err)
CustomStages: func(string) ([]Stage, error) {
return []Stage{
{Name: "first", Run: func(context.Context, *TaskContext) error { ran = append(ran, "first"); return nil }},
{Name: "second", Run: func(context.Context, *TaskContext) error { ran = append(ran, "second"); return nil }},
}, nil
},
} }
if err := StageRepoStages().Run(context.Background(), tc); err != nil { if err := os.WriteFile(filepath.Join(dir, ".archie", "stages", "first.go"), []byte("package stages"), 0o644); err != nil {
t.Fatalf("StageRepoStages() = %v", err) t.Fatal(err)
} }
if len(ran) != 2 || ran[0] != "first" || ran[1] != "second" { tc := &TaskContext{Dir: dir, Log: slog.New(slog.DiscardHandler)}
t.Fatalf("ran = %v, want [first second]", ran) if err := StageRepoStages().Run(context.Background(), tc); err == nil {
t.Fatal("StageRepoStages() = nil, want legacy stage rejection")
} }
} }
func TestStageRepoStagesStopsOnOutcome(t *testing.T) { func TestStageRepoStagesStopsOnOutcome(t *testing.T) {
var ran []string t.Skip("repository-authored stages are no longer executable")
tc := &TaskContext{
Log: slog.New(slog.DiscardHandler),
CustomStages: func(string) ([]Stage, error) {
return []Stage{
{Name: "first", Run: func(_ context.Context, tc *TaskContext) error {
ran = append(ran, "first")
tc.Outcome = Outcome{Status: "parked", Detail: "stop here"}
return nil
}},
{Name: "second", Run: func(context.Context, *TaskContext) error { ran = append(ran, "second"); return nil }},
}, nil
},
}
if err := StageRepoStages().Run(context.Background(), tc); err != nil {
t.Fatalf("StageRepoStages() = %v", err)
}
if len(ran) != 1 || ran[0] != "first" {
t.Fatalf("ran = %v, want only [first] (second stage should not run after an outcome is set)", ran)
}
} }
func TestStageRepoStagesPropagatesLoaderError(t *testing.T) { func TestStageRepoStagesPropagatesLoaderError(t *testing.T) {
tc := &TaskContext{ t.Skip("repository-authored stage loaders are no longer called")
Log: slog.New(slog.DiscardHandler),
CustomStages: func(string) ([]Stage, error) {
return nil, errors.New("boom")
},
}
if err := StageRepoStages().Run(context.Background(), tc); err == nil {
t.Fatal("StageRepoStages() = nil, want the loader's error propagated")
}
} }
// TestStageDiffCapUnlimitedWhenCapIsZero pins that an explicit 0 switches the // TestStageDiffCapUnlimitedWhenCapIsZero pins that an explicit 0 switches the
+3 -9
View File
@@ -8,15 +8,9 @@ package task
// its base, so this is the only record of what an attempt actually changed. // its base, so this is the only record of what an attempt actually changed.
// Nothing re-derives it after the fact. // Nothing re-derives it after the fact.
// //
// The value types live in this subpackage rather than in package workflow or // The value types live in this subpackage because package workflow must not
// internal/worktree, for two reasons that were checked rather than assumed. // import internal/worktree. Both the workflow engine and persistence boundary
// Package workflow must never import internal/worktree -- it has no such // can use the measurement without depending on git infrastructure.
// import today -- so a shared value cannot live there. And this subpackage is
// not projected into the interpreted-stage symbol table (the generated
// wfextract table names no type from here), whereas a new exported type in
// package workflow would be reachable from repository-authored
// `.archie/stages/*.go`. Declaring it here widens nothing and needs no
// symbol-table regeneration.
type ChangeStats struct { type ChangeStats struct {
BaseSHA string `json:"base_sha"` BaseSHA string `json:"base_sha"`
HeadSHA string `json:"head_sha"` HeadSHA string `json:"head_sha"`
@@ -0,0 +1,28 @@
package task
// WorkflowDefinitionEntry is one workflow's portable YAML as the control plane
// stores and serves it. YAML stays canonical and can be copied between Archie
// installations.
//
// It lives with the task vocabulary rather than with the engine for the same
// reason Definition does: a dashboard reads the stored collection without
// linking the workflow engine, which the UI process must never pull in.
type WorkflowDefinitionEntry struct {
ID string `json:"id"`
YAML string `json:"yaml"`
}
// WorkflowDefinitionCollection is the workflow-definitions resource value.
type WorkflowDefinitionCollection struct {
Definitions []WorkflowDefinitionEntry `json:"definitions"`
}
// DefinitionByID resolves one workflow from a collection.
func (c WorkflowDefinitionCollection) DefinitionByID(id string) (WorkflowDefinitionEntry, bool) {
for _, entry := range c.Definitions {
if entry.ID == id {
return entry, true
}
}
return WorkflowDefinitionEntry{}, false
}
+20 -14
View File
@@ -44,15 +44,22 @@ type Task struct {
Labels string `json:"labels"` // comma-separated, as seen at enqueue time Labels string `json:"labels"` // comma-separated, as seen at enqueue time
Status string `json:"status"` Status string `json:"status"`
Workflow string `json:"workflow"` Workflow string `json:"workflow"`
Stage string `json:"stage"` // WorkflowDefinitionVersion and WorkflowDefinitionDigest pin the exact
Branch string `json:"branch"` // database definition selected for this execution. WorkflowDefinitionYAML
Plan string `json:"plan"` // is the immutable worker handoff; retries reuse it instead of re-reading
Notes string `json:"notes"` // the active control-plane resource.
PRNumber int `json:"pr_number"` WorkflowDefinitionVersion int64 `json:"workflow_definition_version"`
TokensUsed int `json:"tokens_used"` WorkflowDefinitionDigest string `json:"workflow_definition_digest"`
Iterations int `json:"iterations"` WorkflowDefinitionYAML string `json:"workflow_definition_yaml"`
Attempt int `json:"attempt"` Stage string `json:"stage"`
ParkReason string `json:"park_reason"` Branch string `json:"branch"`
Plan string `json:"plan"`
Notes string `json:"notes"`
PRNumber int `json:"pr_number"`
TokensUsed int `json:"tokens_used"`
Iterations int `json:"iterations"`
Attempt int `json:"attempt"`
ParkReason string `json:"park_reason"`
// RetryCount tracks how many times a parked task has been retried // RetryCount tracks how many times a parked task has been retried
// (parking-to-queued transitions). When it reaches the configured // (parking-to-queued transitions). When it reaches the configured
// max_retries the daemon moves the task to StatusDead. // max_retries the daemon moves the task to StatusDead.
@@ -124,9 +131,8 @@ type Store interface {
// workflow) for the same reason this package exists: dashboards render // workflow) for the same reason this package exists: dashboards render
// Definitions without linking the engine. // Definitions without linking the engine.
type Definition struct { type Definition struct {
ID string `json:"id"` ID string `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Origin string `json:"origin"` Origin string `json:"origin"`
Enabled bool `json:"enabled"` Enabled bool `json:"enabled"`
Stages []string `json:"stages"`
} }
-78
View File
@@ -1,78 +0,0 @@
// Package wfeval discovers and interprets a repo's custom workflow
// stages: .archie/stages/*.go files, each exporting a Stage() function
// that returns a workflow.Stage. Split from internal/workflow (and its
// generated symbol table in wfextract) to avoid the import cycle that
// would result from workflow depending on its own extracted symbols.
package wfeval
import (
"fmt"
"os"
"path/filepath"
"sort"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/wfextract"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// stagesDir is where a repo's custom stage scripts live, relative to
// the worktree root.
const stagesDir = ".archie/stages"
// Discover loads every .archie/stages/*.go file in dir and returns the
// workflow.Stage each exports, in filename order. A missing directory is
// not an error -- it returns (nil, nil), meaning no custom stages are
// configured for this repo.
func Discover(dir string) ([]workflow.Stage, error) {
entries, err := os.ReadDir(filepath.Join(dir, stagesDir))
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("read %s: %w", stagesDir, err)
}
var names []string
for _, e := range entries {
if !e.IsDir() && filepath.Ext(e.Name()) == ".go" {
names = append(names, e.Name())
}
}
sort.Strings(names)
stages := make([]workflow.Stage, 0, len(names))
for _, name := range names {
stage, err := loadStage(filepath.Join(dir, stagesDir, name))
if err != nil {
return nil, fmt.Errorf("%s: %w", filepath.Join(stagesDir, name), err)
}
stages = append(stages, stage)
}
return stages, nil
}
// loadStage interprets one custom stage script and calls its exported
// Stage() function. The script runs in-process (interpreted, not
// sandboxed), so a panic inside it is recovered and returned as an error
// rather than taking down the daemon.
func loadStage(path string) (workflow.Stage, error) {
src, err := os.ReadFile(path)
if err != nil {
return workflow.Stage{}, err
}
return yaegiutil.Safe(path, func() (workflow.Stage, error) {
i, err := yaegiutil.New(interp.Options{}, wfextract.Symbols)
if err != nil {
return workflow.Stage{}, err
}
factory, err := yaegiutil.Resolve[func() workflow.Stage](i, string(src), "stages.Stage")
if err != nil {
return workflow.Stage{}, fmt.Errorf("yaegi: %w", err)
}
return factory(), nil
})
}
@@ -1,139 +0,0 @@
package wfeval
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func writeStageScript(t *testing.T, dir, name, src string) {
t.Helper()
stagesDir := filepath.Join(dir, ".archie", "stages")
if err := os.MkdirAll(stagesDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(stagesDir, name), []byte(src), 0o644); err != nil {
t.Fatal(err)
}
}
func TestDiscoverNoStagesDir(t *testing.T) {
stages, err := Discover(t.TempDir())
if err != nil {
t.Fatalf("Discover() error = %v, want nil (no .archie/stages)", err)
}
if stages != nil {
t.Fatalf("Discover() = %v, want nil", stages)
}
}
func TestDiscoverRunsStagesInFilenameOrder(t *testing.T) {
dir := t.TempDir()
writeStageScript(t, dir, "b-second.go", `package stages
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() workflow.Stage {
return workflow.Stage{Name: "second", Run: func(ctx context.Context, tc *workflow.TaskContext) error {
return nil
}}
}
`)
writeStageScript(t, dir, "a-first.go", `package stages
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() workflow.Stage {
return workflow.Stage{Name: "first", Run: func(ctx context.Context, tc *workflow.TaskContext) error {
return nil
}}
}
`)
stages, err := Discover(dir)
if err != nil {
t.Fatalf("Discover() error = %v", err)
}
if len(stages) != 2 {
t.Fatalf("Discover() = %#v, want 2 stages", stages)
}
if stages[0].Name != "first" || stages[1].Name != "second" {
t.Fatalf("Discover() order = [%s, %s], want [first, second]", stages[0].Name, stages[1].Name)
}
}
func TestDiscoverStageRuns(t *testing.T) {
dir := t.TempDir()
writeStageScript(t, dir, "touch.go", `package stages
import (
"context"
"os"
"path/filepath"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func Stage() workflow.Stage {
return workflow.Stage{Name: "touch", Run: func(ctx context.Context, tc *workflow.TaskContext) error {
return os.WriteFile(filepath.Join(tc.Dir, "touched.txt"), []byte("hi\n"), 0o644)
}}
}
`)
stages, err := Discover(dir)
if err != nil {
t.Fatalf("Discover() error = %v", err)
}
if len(stages) != 1 {
t.Fatalf("Discover() = %#v, want 1 stage", stages)
}
tc := &workflow.TaskContext{Dir: dir}
if err := stages[0].Run(context.Background(), tc); err != nil {
t.Fatalf("stage.Run() error = %v", err)
}
if _, err := os.Stat(filepath.Join(dir, "touched.txt")); err != nil {
t.Fatalf("stage did not run: %v", err)
}
}
func TestDiscoverBadSignature(t *testing.T) {
dir := t.TempDir()
writeStageScript(t, dir, "bad.go", `package stages
func Stage() string {
return "not a workflow.Stage"
}
`)
if _, err := Discover(dir); err == nil {
t.Fatal("Discover() error = nil, want a signature mismatch error")
}
}
func TestDiscoverPanicRecovered(t *testing.T) {
dir := t.TempDir()
writeStageScript(t, dir, "panics.go", `package stages
import "github.com/samcharles93/archie-core/internal/domain/workflow"
func Stage() workflow.Stage {
var files []string
_ = files[5]
return workflow.Stage{}
}
`)
if _, err := Discover(dir); err == nil {
t.Fatal("Discover() error = nil, want a recovered-panic error")
}
}
@@ -1,215 +0,0 @@
// Code generated by 'yaegi extract github.com/samcharles93/archie-core/internal/domain/workflow'. DO NOT EDIT.
package wfextract
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/events"
"go/constant"
"go/token"
"reflect"
)
func init() {
Symbols["github.com/samcharles93/archie-core/internal/domain/workflow/workflow"] = map[string]reflect.Value{
// function, constant and variable definitions
"Bootstrap": reflect.ValueOf(workflow.Bootstrap),
"DecodeReviewUnit": reflect.ValueOf(workflow.DecodeReviewUnit),
"Definitions": reflect.ValueOf(workflow.Definitions),
"DefinitionsWithOrigins": reflect.ValueOf(workflow.DefinitionsWithOrigins),
"EncodeReviewUnit": reflect.ValueOf(workflow.EncodeReviewUnit),
"ErrNoReviewPayload": reflect.ValueOf(&workflow.ErrNoReviewPayload).Elem(),
"Feasibility": reflect.ValueOf(workflow.Feasibility),
"GateFromRepo": reflect.ValueOf(workflow.GateFromRepo),
"Implement": reflect.ValueOf(workflow.Implement),
"LoadKindWorkflowsYAML": reflect.ValueOf(workflow.LoadKindWorkflowsYAML),
"LoadLabelWorkflowsYAML": reflect.ValueOf(workflow.LoadLabelWorkflowsYAML),
"LoadPlaybookDirs": reflect.ValueOf(workflow.LoadPlaybookDirs),
"MergeKindWorkflows": reflect.ValueOf(workflow.MergeKindWorkflows),
"MergeLabelWorkflows": reflect.ValueOf(workflow.MergeLabelWorkflows),
"NewCompletedReviewReport": reflect.ValueOf(workflow.NewCompletedReviewReport),
"NewNotRunReviewReport": reflect.ValueOf(workflow.NewNotRunReviewReport),
"NewSkippedReviewReport": reflect.ValueOf(workflow.NewSkippedReviewReport),
"OpenPR": reflect.ValueOf(workflow.OpenPR),
"Remediate": reflect.ValueOf(workflow.Remediate),
"ReviewBlocking": reflect.ValueOf(workflow.ReviewBlocking),
"ReviewCategoryDeadCode": reflect.ValueOf(workflow.ReviewCategoryDeadCode),
"ReviewCategoryGoroutineLeak": reflect.ValueOf(workflow.ReviewCategoryGoroutineLeak),
"ReviewCategoryHardcodedValue": reflect.ValueOf(workflow.ReviewCategoryHardcodedValue),
"ReviewCategoryInterfaceSatisfaction": reflect.ValueOf(workflow.ReviewCategoryInterfaceSatisfaction),
"ReviewCategoryNilRisk": reflect.ValueOf(workflow.ReviewCategoryNilRisk),
"ReviewCategoryOther": reflect.ValueOf(workflow.ReviewCategoryOther),
"ReviewCategoryRace": reflect.ValueOf(workflow.ReviewCategoryRace),
"ReviewCategoryUncheckedError": reflect.ValueOf(workflow.ReviewCategoryUncheckedError),
"ReviewDispositionFixed": reflect.ValueOf(workflow.ReviewDispositionFixed),
"ReviewDispositionNoChangeNeeded": reflect.ValueOf(workflow.ReviewDispositionNoChangeNeeded),
"ReviewDispositionSkipped": reflect.ValueOf(workflow.ReviewDispositionSkipped),
"ReviewLevelError": reflect.ValueOf(workflow.ReviewLevelError),
"ReviewLevelWarn": reflect.ValueOf(workflow.ReviewLevelWarn),
"ReviewStatusCompleted": reflect.ValueOf(workflow.ReviewStatusCompleted),
"ReviewStatusNotRun": reflect.ValueOf(workflow.ReviewStatusNotRun),
"ReviewStatusSkipped": reflect.ValueOf(workflow.ReviewStatusSkipped),
"ReviewVerdictConfirmed": reflect.ValueOf(workflow.ReviewVerdictConfirmed),
"ReviewVerdictPlausible": reflect.ValueOf(workflow.ReviewVerdictPlausible),
"Route": reflect.ValueOf(workflow.Route),
"Run": reflect.ValueOf(workflow.Run),
"SetKindWorkflows": reflect.ValueOf(workflow.SetKindWorkflows),
"SetLabelWorkflows": reflect.ValueOf(workflow.SetLabelWorkflows),
"SourceChat": reflect.ValueOf(constant.MakeFromLiteral("\"chat\"", token.STRING, 0)),
"SourceForge": reflect.ValueOf(constant.MakeFromLiteral("\"forge\"", token.STRING, 0)),
"StageBaselineGate": reflect.ValueOf(workflow.StageBaselineGate),
"StageCheckReviewPayload": reflect.ValueOf(workflow.StageCheckReviewPayload),
"StageCommit": reflect.ValueOf(workflow.StageCommit),
"StageCommitPush": reflect.ValueOf(workflow.StageCommitPush),
"StageDiffCap": reflect.ValueOf(workflow.StageDiffCap),
"StageOpenPR": reflect.ValueOf(workflow.StageOpenPR),
"StagePostReviewComments": reflect.ValueOf(workflow.StagePostReviewComments),
"StagePrepareWorktree": reflect.ValueOf(workflow.StagePrepareWorktree),
"StageRemediationCommitPush": reflect.ValueOf(workflow.StageRemediationCommitPush),
"StageRemediationReply": reflect.ValueOf(workflow.StageRemediationReply),
"StageRemediationRoundCap": reflect.ValueOf(workflow.StageRemediationRoundCap),
"StageRepoStages": reflect.ValueOf(workflow.StageRepoStages),
"StageResumeWorktree": reflect.ValueOf(workflow.StageResumeWorktree),
"StageReview": reflect.ValueOf(workflow.StageReview),
"StageYaegiGate": reflect.ValueOf(workflow.StageYaegiGate),
"StatusClosedWontDo": reflect.ValueOf(constant.MakeFromLiteral("\"closed_wont_do\"", token.STRING, 0)),
"StatusDead": reflect.ValueOf(constant.MakeFromLiteral("\"dead\"", token.STRING, 0)),
"StatusMerged": reflect.ValueOf(constant.MakeFromLiteral("\"merged\"", token.STRING, 0)),
"StatusPROpen": reflect.ValueOf(constant.MakeFromLiteral("\"pr_open\"", token.STRING, 0)),
"StatusParked": reflect.ValueOf(constant.MakeFromLiteral("\"parked\"", token.STRING, 0)),
"StatusQueued": reflect.ValueOf(constant.MakeFromLiteral("\"queued\"", token.STRING, 0)),
"StatusRejected": reflect.ValueOf(constant.MakeFromLiteral("\"rejected\"", token.STRING, 0)),
"StatusRunning": reflect.ValueOf(constant.MakeFromLiteral("\"running\"", token.STRING, 0)),
"StatusWaitingHuman": reflect.ValueOf(constant.MakeFromLiteral("\"waiting_human\"", token.STRING, 0)),
"TDD": reflect.ValueOf(workflow.TDD),
"Triage": reflect.ValueOf(workflow.Triage),
// type definitions
"AgentStage": reflect.ValueOf((*workflow.AgentStage)(nil)),
"Definition": reflect.ValueOf((*workflow.Definition)(nil)),
"Forger": reflect.ValueOf((*workflow.Forger)(nil)),
"KindWorkflows": reflect.ValueOf((*workflow.KindWorkflows)(nil)),
"LabelWorkflows": reflect.ValueOf((*workflow.LabelWorkflows)(nil)),
"Outcome": reflect.ValueOf((*workflow.Outcome)(nil)),
"Registry": reflect.ValueOf((*workflow.Registry)(nil)),
"ReviewCategory": reflect.ValueOf((*workflow.ReviewCategory)(nil)),
"ReviewCheck": reflect.ValueOf((*workflow.ReviewCheck)(nil)),
"ReviewComment": reflect.ValueOf((*workflow.ReviewComment)(nil)),
"ReviewDisposition": reflect.ValueOf((*workflow.ReviewDisposition)(nil)),
"ReviewFinding": reflect.ValueOf((*workflow.ReviewFinding)(nil)),
"ReviewLevel": reflect.ValueOf((*workflow.ReviewLevel)(nil)),
"ReviewReport": reflect.ValueOf((*workflow.ReviewReport)(nil)),
"ReviewRequest": reflect.ValueOf((*workflow.ReviewRequest)(nil)),
"ReviewStatus": reflect.ValueOf((*workflow.ReviewStatus)(nil)),
"ReviewUnit": reflect.ValueOf((*workflow.ReviewUnit)(nil)),
"ReviewUnitComment": reflect.ValueOf((*workflow.ReviewUnitComment)(nil)),
"ReviewVerdict": reflect.ValueOf((*workflow.ReviewVerdict)(nil)),
"Reviewer": reflect.ValueOf((*workflow.Reviewer)(nil)),
"Stage": reflect.ValueOf((*workflow.Stage)(nil)),
"Store": reflect.ValueOf((*workflow.Store)(nil)),
"Task": reflect.ValueOf((*workflow.Task)(nil)),
"TaskContext": reflect.ValueOf((*workflow.TaskContext)(nil)),
"Trees": reflect.ValueOf((*workflow.Trees)(nil)),
"Workflow": reflect.ValueOf((*workflow.Workflow)(nil)),
// interface wrapper definitions
"_Forger": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Forger)(nil)),
"_Reviewer": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer)(nil)),
"_Store": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Store)(nil)),
"_Trees": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_domain_workflow_Trees)(nil)),
}
}
// _github_com_samcharles93_archie_core_internal_domain_workflow_Forger is an interface wrapper for Forger type
type _github_com_samcharles93_archie_core_internal_domain_workflow_Forger struct {
IValue interface{}
WCloseIssue func(ctx context.Context, owner string, repo string, number int, comment string) error
WComment func(ctx context.Context, owner string, repo string, number int, body string) (int64, error)
WCreatePR func(ctx context.Context, owner string, repo string, title string, head string, base string, body string) (int, error)
WCreateReviewComments func(ctx context.Context, owner string, repo string, number int, reviewedHeadSHA string, comments []workflow.ReviewComment) error
WLinkBranch func(ctx context.Context, owner string, repo string, issueNumber int, branch string) error
WReplyToReview func(ctx context.Context, owner string, repo string, number int, commentID int64, body string) error
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) CloseIssue(ctx context.Context, owner string, repo string, number int, comment string) error {
return W.WCloseIssue(ctx, owner, repo, number, comment)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) Comment(ctx context.Context, owner string, repo string, number int, body string) (int64, error) {
return W.WComment(ctx, owner, repo, number, body)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) CreatePR(ctx context.Context, owner string, repo string, title string, head string, base string, body string) (int, error) {
return W.WCreatePR(ctx, owner, repo, title, head, base, body)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) CreateReviewComments(ctx context.Context, owner string, repo string, number int, reviewedHeadSHA string, comments []workflow.ReviewComment) error {
return W.WCreateReviewComments(ctx, owner, repo, number, reviewedHeadSHA, comments)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) LinkBranch(ctx context.Context, owner string, repo string, issueNumber int, branch string) error {
return W.WLinkBranch(ctx, owner, repo, issueNumber, branch)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Forger) ReplyToReview(ctx context.Context, owner string, repo string, number int, commentID int64, body string) error {
return W.WReplyToReview(ctx, owner, repo, number, commentID, body)
}
// _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer is an interface wrapper for Reviewer type
type _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer struct {
IValue interface{}
WReview func(ctx context.Context, req workflow.ReviewRequest) workflow.ReviewReport
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Reviewer) Review(ctx context.Context, req workflow.ReviewRequest) workflow.ReviewReport {
return W.WReview(ctx, req)
}
// _github_com_samcharles93_archie_core_internal_domain_workflow_Store is an interface wrapper for Store type
type _github_com_samcharles93_archie_core_internal_domain_workflow_Store struct {
IValue interface{}
WInsertEvent func(ctx context.Context, e events.Event) (int64, error)
WTransition func(ctx context.Context, taskID int64, from string, to string, detail string) error
WUpdate func(ctx context.Context, t *task.Task) error
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Store) InsertEvent(ctx context.Context, e events.Event) (int64, error) {
return W.WInsertEvent(ctx, e)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Store) Transition(ctx context.Context, taskID int64, from string, to string, detail string) error {
return W.WTransition(ctx, taskID, from, to, detail)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Store) Update(ctx context.Context, t *task.Task) error {
return W.WUpdate(ctx, t)
}
// _github_com_samcharles93_archie_core_internal_domain_workflow_Trees is an interface wrapper for Trees type
type _github_com_samcharles93_archie_core_internal_domain_workflow_Trees struct {
IValue interface{}
WChangedFiles func(ctx context.Context, dir string, base string) ([]string, error)
WChangedLines func(ctx context.Context, dir string, base string) (int, error)
WCommitAll func(ctx context.Context, dir string, message string) (bool, error)
WDiff func(ctx context.Context, dir string, base string) (string, error)
WPrepare func(ctx context.Context, owner string, repo string, base string, issue int, title string, body string, labels string) (dir string, branch string, err error)
WPush func(ctx context.Context, dir string, branch string) error
WSnapshot func(ctx context.Context, dir string, destDir string) error
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) ChangedFiles(ctx context.Context, dir string, base string) ([]string, error) {
return W.WChangedFiles(ctx, dir, base)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) ChangedLines(ctx context.Context, dir string, base string) (int, error) {
return W.WChangedLines(ctx, dir, base)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) CommitAll(ctx context.Context, dir string, message string) (bool, error) {
return W.WCommitAll(ctx, dir, message)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Diff(ctx context.Context, dir string, base string) (string, error) {
return W.WDiff(ctx, dir, base)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Prepare(ctx context.Context, owner string, repo string, base string, issue int, title string, body string, labels string) (dir string, branch string, err error) {
return W.WPrepare(ctx, owner, repo, base, issue, title, body, labels)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Push(ctx context.Context, dir string, branch string) error {
return W.WPush(ctx, dir, branch)
}
func (W _github_com_samcharles93_archie_core_internal_domain_workflow_Trees) Snapshot(ctx context.Context, dir string, destDir string) error {
return W.WSnapshot(ctx, dir, destDir)
}
@@ -1,148 +0,0 @@
package wfextract
import (
"reflect"
"testing"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// TestPreviouslyMissingSymbolsReachableFromInterpretedCode is the regression
// test for the stale-symbol-table drift (e7bo): the committed generated file
// predated the domain migration and was hand-patched for imports only, never
// regenerated -- so symbols added after the migration (the routing YAML
// loaders t2db.9/.10/.11, the review types, and the Forger/Reviewer/Trees
// interfaces that TaskContext exposes to every interpreted stage plugin)
// were missing from the table. A stage plugin referencing tc.Trees or the
// review types could not resolve them, silently.
//
// This test interprets a plugin that references the previously-missing
// symbols. It fails if the symbols or wrappers are dropped from the table.
func TestPreviouslyMissingSymbolsReachableFromInterpretedCode(t *testing.T) {
src := `package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// Trees is the branch/prepare/diff surface TaskContext.Trees exposes.
func UseTrees(t workflow.Trees) (string, int, error) {
dir, _, err := t.Prepare(context.Background(), "o", "r", "main", 1, "t", "", "")
if err != nil {
return "", 0, err
}
diff, err := t.Diff(context.Background(), dir, "main")
lines, err := t.ChangedLines(context.Background(), dir, "main")
return diff, lines, err
}
// Reviewer is the adversarial-review surface TaskContext.Reviewer exposes.
func UseReviewer(r workflow.Reviewer) workflow.ReviewReport {
return r.Review(context.Background(), workflow.ReviewRequest{})
}
// Routing loaders are the t2db.9/.10/.11 API stage plugins may call.
func UseRouting() error {
_, _, err := workflow.LoadPlaybookDirs([]string{"/nonexistent"})
return err
}
`
i, err := yaegiutil.New(interp.Options{}, Symbols)
if err != nil {
t.Fatalf("New: %v", err)
}
// Resolve and call the routing loader through interpreted code -- the
// strongest proof the previously-missing symbol is reachable.
useRouting, err := yaegiutil.Resolve[func() error](i, src, "main.UseRouting")
if err != nil {
t.Fatalf("Resolve UseRouting: %v", err)
}
err = useRouting()
if err == nil {
// LoadPlaybookDirs("/nonexistent") errors only if the dir list is
// valid and the files are missing -- but an empty / nonexistent
// directory is a no-op (matching t2db.11's empty-means-defaults).
// Either way, the call itself resolving and executing proves the
// symbol is wired.
t.Logf("UseRouting returned nil error (nonexistent dir is a no-op)")
}
}
// The former TestWrapperNilGuardsPreserved was retired. It pinned hand-added
// nil guards that every regeneration silently dropped, and the behaviour it
// protected was a lie: a nil WCloseIssue reported a closed issue that was
// never touched. A wrapper missing a method is now refused in
// yaegiutil.Resolve, before it can reach a call site.
// TestChangeCaptureIsNotCallableFromInterpretedCode is the acceptance test for
// "the sandbox surface did not widen", in the same shape as the reachability
// test above and with the opposite assertion.
//
// An attempt's changed files are captured through an UNEXPORTED optional
// interface asserted on TaskContext.Trees, precisely so that the capability is
// not part of workflow.Trees: Trees is projected into this symbol table, so a
// method added to it would become callable by every repository-authored
// .archie/stages/*.go file. Both halves are asserted here -- the interface's
// method set, and the interpreted call that must not resolve -- because the
// second alone would be weaker: it would still pass if the symbol table lost
// Trees altogether.
func TestChangeCaptureIsNotCallableFromInterpretedCode(t *testing.T) {
trees := reflect.TypeFor[workflow.Trees]()
if _, ok := trees.MethodByName("ChangedFileStats"); ok {
t.Fatalf("workflow.Trees gained ChangedFileStats; interpreted stage code can now read a diffstat the engine only meant to capture")
}
// The control first: an interpreted call to a method Trees really has must
// resolve, so the refusal below is the missing method and not a broken
// harness.
const control = `package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
func UseTrees(t workflow.Trees) {
_, _ = t.Diff(context.Background(), "", "")
}
`
const probe = `package main
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/workflow"
)
// CaptureDiffstat is an interpreted stage trying to reach the engine's
// change capture through the surface TaskContext hands it.
func CaptureDiffstat(t workflow.Trees) {
stats, err := t.ChangedFileStats(context.Background(), "", "")
_, _ = stats.HeadSHA, err
}
`
i, err := yaegiutil.New(interp.Options{}, Symbols)
if err != nil {
t.Fatalf("New: %v", err)
}
if _, err := yaegiutil.Resolve[func(workflow.Trees)](i, control, "main.UseTrees"); err != nil {
t.Fatalf("the control call Trees.Diff did not resolve (%v); this test cannot tell a missing capability from a broken symbol table", err)
}
j, err := yaegiutil.New(interp.Options{}, Symbols)
if err != nil {
t.Fatalf("New: %v", err)
}
if _, err := yaegiutil.Resolve[func(workflow.Trees)](j, probe, "main.CaptureDiffstat"); err == nil {
t.Error("interpreted stage code resolved Trees.ChangedFileStats; the capture capability leaked into the projected surface")
}
}
@@ -1,14 +0,0 @@
// Package wfextract holds the Yaegi symbol table for internal/domain/workflow,
// generated by `go generate`. Kept separate from internal/domain/workflow
// itself so the generated file can import it without a self-import cycle.
//
// The generated file is used verbatim. A wrapper whose method fields are not
// all populated is refused in yaegiutil.Resolve, so it needs no hand-added
// nil-guards -- an earlier convention that every regeneration silently undid.
package wfextract
import "reflect"
//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name wfextract github.com/samcharles93/archie-core/internal/domain/workflow
var Symbols = map[string]map[string]reflect.Value{}
@@ -1,55 +0,0 @@
package wfextract
import (
"reflect"
"testing"
)
func TestSymbolsContainsExpectedWorkflowEntries(t *testing.T) {
pkgKey := "github.com/samcharles93/archie-core/internal/domain/workflow/workflow"
pkg, ok := Symbols[pkgKey]
if !ok {
t.Fatalf("Symbols missing key %q", pkgKey)
}
// Core functions that must be present.
requiredFuncs := []string{
"Route", "Run", "Bootstrap", "Feasibility", "Implement",
"OpenPR", "TDD",
}
for _, name := range requiredFuncs {
v, ok := pkg[name]
if !ok {
t.Errorf("required function %q missing from Symbols", name)
continue
}
if v.Kind() != reflect.Func {
t.Errorf("%s kind = %v, want Func", name, v.Kind())
}
}
// Core types that must be present as pointers.
requiredTypes := []string{
"AgentStage", "Outcome", "Registry", "Stage",
"TaskContext", "Workflow",
}
for _, name := range requiredTypes {
v, ok := pkg[name]
if !ok {
t.Errorf("required type %q missing from Symbols", name)
continue
}
if v.Kind() != reflect.Pointer {
t.Errorf("%s kind = %v, want Ptr", name, v.Kind())
}
}
}
func TestWFExtractSymbolCountReasonable(t *testing.T) {
pkgKey := "github.com/samcharles93/archie-core/internal/domain/workflow/workflow"
pkg := Symbols[pkgKey]
// Should have at least the core functions + types (10+ entries).
if len(pkg) < 10 {
t.Errorf("expected at least 10 symbols, got %d", len(pkg))
}
}
+2 -40
View File
@@ -11,7 +11,6 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"regexp" "regexp"
"sort"
"strings" "strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
@@ -90,15 +89,9 @@ type TaskContext struct {
Reviewer Reviewer Reviewer Reviewer
Bus *events.Bus // nil-safe via Emit Bus *events.Bus // nil-safe via Emit
Log *slog.Logger Log *slog.Logger
// CustomStages discovers a repo's per-repo custom stages (Yaegi- // CustomStages is retained for source compatibility only. Repository Go
// interpreted from .archie/stages/*.go in the given worktree // stages are no longer executed; StageRepoStages rejects their presence.
// directory), returning them in the order they should run. Application
// composition injects it; nil disables discovery, so StageRepoStages is a
// no-op. The composition layer provides the implementation rather
// than importing the generated Yaegi symbol table here, which would create
// a workflow package import cycle.
CustomStages func(dir string) ([]Stage, error) CustomStages func(dir string) ([]Stage, error)
// SkillBody is the Markdown body of the loaded SKILL.md for this // SkillBody is the Markdown body of the loaded SKILL.md for this
// workflow's matching skill, injected into agent context. Empty // workflow's matching skill, injected into agent context. Empty
// when no skill is found (backward compatible). // when no skill is found (backward compatible).
@@ -254,37 +247,6 @@ type Workflow struct {
// Registry maps workflow names to definitions. // Registry maps workflow names to definitions.
type Registry map[string]Workflow type Registry map[string]Workflow
// Definitions snapshots a registry deterministically so installed workflows
// remain visible even when they have not produced persisted run statistics.
func Definitions(reg Registry) []Definition {
return DefinitionsWithOrigins(reg, nil)
}
// DefinitionsWithOrigins snapshots a registry with composition-supplied
// provenance. Entries absent from origins are conservatively labelled
// "registry", which keeps the helper useful for tests and non-catalog callers.
func DefinitionsWithOrigins(reg Registry, origins map[string]string) []Definition {
ids := make([]string, 0, len(reg))
for id := range reg {
ids = append(ids, id)
}
sort.Strings(ids)
definitions := make([]Definition, 0, len(ids))
for _, id := range ids {
wf := reg[id]
stages := make([]string, 0, len(wf.Stages))
for _, stage := range wf.Stages {
stages = append(stages, stage.Name)
}
origin := origins[id]
if origin == "" {
origin = "registry"
}
definitions = append(definitions, Definition{ID: id, Name: wf.Name, Origin: origin, Enabled: true, Stages: stages})
}
return definitions
}
// Route picks the workflow for a task. A pre-assigned workflow wins // Route picks the workflow for a task. A pre-assigned workflow wins
// (the waiting_human → approved handoff requeues under "implement"); // (the waiting_human → approved handoff requeues under "implement");
// otherwise labels decide, then the default. // otherwise labels decide, then the default.
-72
View File
@@ -1,72 +0,0 @@
// Package gate defines the runtime-evaluated custom gate surface: a
// per-repo .archie/gate.go, interpreted via Yaegi after the shell-based
// gate passes, that inspects the diff and worktree for project-specific
// rules shell commands can't express (AST checks, diff scanning, and
// the like).
package gate
import "fmt"
// Level is the severity of a gate finding. LevelError blocks the gate;
// LevelWarn is advisory and logged only.
type Level string
const (
// LevelError blocks the gate: the task is parked instead of opening a PR.
LevelError Level = "error"
// LevelWarn is advisory and logged only.
LevelWarn Level = "warn"
)
// GateContext carries everything a custom gate function can inspect.
type GateContext struct {
// Diff is the unified diff of all changes against BaseRef.
Diff string
// ChangedFiles lists changed file paths, repo-relative.
ChangedFiles []string
// Dir is the absolute worktree path.
Dir string
// BaseRef is the base branch the diff is against (e.g. "origin/main").
BaseRef string
// Repo is "owner/name".
Repo string
}
// Finding is one gate violation.
type Finding struct {
// Level is the severity: LevelError blocks the gate, LevelWarn is
// advisory and logged only.
Level Level
// File is the optional file path the finding applies to.
File string
// Line is the optional line number within File.
Line int
Message string
}
// Blocking reports whether this finding blocks the gate.
func (f Finding) Blocking() bool {
return f.Level == LevelError
}
// Blocking reports whether any finding blocks the gate.
func Blocking(findings []Finding) bool {
for _, f := range findings {
if f.Blocking() {
return true
}
}
return false
}
// Validate checks that the finding satisfies contract invariants. An
// unrecognized level fails closed: a script that emits a mis-typed or empty
// level is an error, never a silently non-blocking finding.
func (f Finding) Validate() error {
switch f.Level {
case LevelError, LevelWarn:
return nil
default:
return fmt.Errorf("invalid gate level %q (must be %q or %q)", f.Level, LevelError, LevelWarn)
}
}
-254
View File
@@ -1,254 +0,0 @@
package gate
import (
"testing"
)
func TestBlocking(t *testing.T) {
t.Run("nil slice returns false", func(t *testing.T) {
if Blocking(nil) {
t.Error("Blocking(nil) should return false")
}
})
t.Run("empty slice returns false", func(t *testing.T) {
if Blocking([]Finding{}) {
t.Error("Blocking([]) should return false")
}
})
t.Run("warn-only returns false", func(t *testing.T) {
findings := []Finding{
{Level: "warn", Message: "advisory only"},
{Level: "warn", Message: "another advisory"},
}
if Blocking(findings) {
t.Error("warn-only findings should not be blocking")
}
})
t.Run("single error returns true", func(t *testing.T) {
findings := []Finding{
{Level: "error", Message: "must fix"},
}
if !Blocking(findings) {
t.Error("error-level finding should be blocking")
}
})
t.Run("mixed error and warn returns true", func(t *testing.T) {
findings := []Finding{
{Level: "warn", Message: "advisory"},
{Level: "error", Message: "blocker"},
}
if !Blocking(findings) {
t.Error("mixed findings with at least one error should be blocking")
}
})
t.Run("error as first element returns true", func(t *testing.T) {
findings := []Finding{
{Level: "error", Message: "first"},
{Level: "warn", Message: "second"},
}
if !Blocking(findings) {
t.Error("error as first element should be blocking")
}
})
t.Run("case-sensitive level check", func(t *testing.T) {
// Only lowercase "error" blocks; "ERROR" does not.
findings := []Finding{
{Level: "ERROR", Message: "uppercase error"},
{Level: "Error", Message: "title-case error"},
}
if Blocking(findings) {
t.Error("non-lowercase error should not be blocking")
}
})
t.Run("unknown level does not block", func(t *testing.T) {
findings := []Finding{
{Level: "unknown", Message: "unanticipated level"},
}
if Blocking(findings) {
t.Error("unknown level should not be blocking")
}
})
t.Run("empty level does not block", func(t *testing.T) {
findings := []Finding{
{Level: "", Message: "missing level"},
}
if Blocking(findings) {
t.Error("empty level should not be blocking")
}
})
t.Run("large finding slice returns early on first error", func(t *testing.T) {
// Blocking returns true on the first error — it does not scan
// the entire slice. Verify this with 1 error buried among warns.
findings := make([]Finding, 1000)
for i := range findings {
findings[i] = Finding{Level: "warn", Message: "advisory"}
}
findings[500] = Finding{Level: "error", Message: "blocker at 500"}
if !Blocking(findings) {
t.Error("error at position 500 should still be detected")
}
})
}
func TestFindingValidate(t *testing.T) {
t.Run("error is valid", func(t *testing.T) {
if err := (Finding{Level: LevelError}).Validate(); err != nil {
t.Errorf("Validate() = %v, want nil", err)
}
})
t.Run("warn is valid", func(t *testing.T) {
if err := (Finding{Level: LevelWarn}).Validate(); err != nil {
t.Errorf("Validate() = %v, want nil", err)
}
})
t.Run("unrecognized level fails closed", func(t *testing.T) {
for _, level := range []Level{"fatal", "ERROR", "Error", ""} {
if err := (Finding{Level: level}).Validate(); err == nil {
t.Errorf("Validate() = nil for level %q, want an error", level)
}
}
})
}
func TestFindingBlocking(t *testing.T) {
if !(Finding{Level: LevelError}).Blocking() {
t.Error("Finding{Level: LevelError}.Blocking() = false, want true")
}
if (Finding{Level: LevelWarn}).Blocking() {
t.Error("Finding{Level: LevelWarn}.Blocking() = true, want false")
}
if (Finding{Level: ""}).Blocking() {
t.Error("Finding{Level: \"\"}.Blocking() = true, want false")
}
}
func TestGateContextZeroValue(t *testing.T) {
// Zero-value GateContext should not panic when accessed.
var gctx GateContext
if gctx.Dir != "" {
t.Errorf("zero Dir should be empty, got %q", gctx.Dir)
}
if gctx.BaseRef != "" {
t.Errorf("zero BaseRef should be empty, got %q", gctx.BaseRef)
}
if gctx.Repo != "" {
t.Errorf("zero Repo should be empty, got %q", gctx.Repo)
}
if gctx.Diff != "" {
t.Errorf("zero Diff should be empty")
}
if gctx.ChangedFiles != nil {
t.Errorf("zero ChangedFiles should be nil, got %v", gctx.ChangedFiles)
}
}
func TestGateContextFieldIntegrity(t *testing.T) {
gctx := GateContext{
Diff: "--- a/file.go\n+++ b/file.go\n@@ -1 +1 @@\n-old\n+new",
ChangedFiles: []string{"file.go", "other.go"},
Dir: "/tmp/worktree",
BaseRef: "origin/main",
Repo: "owner/name",
}
if gctx.Dir != "/tmp/worktree" {
t.Errorf("Dir = %q", gctx.Dir)
}
if gctx.BaseRef != "origin/main" {
t.Errorf("BaseRef = %q", gctx.BaseRef)
}
if gctx.Repo != "owner/name" {
t.Errorf("Repo = %q", gctx.Repo)
}
if len(gctx.ChangedFiles) != 2 {
t.Errorf("ChangedFiles = %v, expected 2 entries", gctx.ChangedFiles)
}
}
func TestFindingConstruction(t *testing.T) {
t.Run("full finding", func(t *testing.T) {
f := Finding{
Level: "error",
File: "main.go",
Line: 42,
Message: "nil pointer dereference possible",
}
if f.Level != "error" {
t.Errorf("Level = %q", f.Level)
}
if f.File != "main.go" {
t.Errorf("File = %q", f.File)
}
if f.Line != 42 {
t.Errorf("Line = %d", f.Line)
}
if f.Message != "nil pointer dereference possible" {
t.Errorf("Message = %q", f.Message)
}
})
t.Run("minimal finding (level + message only)", func(t *testing.T) {
f := Finding{Level: "warn", Message: "review needed"}
if f.File != "" {
t.Errorf("File should be empty, got %q", f.File)
}
if f.Line != 0 {
t.Errorf("Line should be 0, got %d", f.Line)
}
})
t.Run("zero-value finding", func(t *testing.T) {
var f Finding
if f.Level != "" {
t.Errorf("zero Level should be empty, got %q", f.Level)
}
if f.Message != "" {
t.Errorf("zero Message should be empty, got %q", f.Message)
}
})
t.Run("negative line accepted as data", func(t *testing.T) {
// Line is an int with no validation — negative values are
// stored as-is. Tests document this behavior.
f := Finding{Level: "warn", Line: -1, Message: "test"}
if f.Line != -1 {
t.Errorf("Line should be -1, got %d", f.Line)
}
})
}
func TestFindingSliceBlocking(t *testing.T) {
// End-to-end: construct findings and check if they block.
t.Run("all clear", func(t *testing.T) {
findings := []Finding{
{Level: "warn", File: "a.go", Line: 1, Message: "consider refactoring"},
{Level: "warn", File: "b.go", Line: 10, Message: "possible simplification"},
}
if Blocking(findings) {
t.Error("all-warn should not block")
}
})
t.Run("one blocker among many", func(t *testing.T) {
findings := []Finding{
{Level: "warn", File: "x.go", Message: "first"},
{Level: "warn", File: "y.go", Message: "second"},
{Level: "error", File: "z.go", Line: 99, Message: "critical issue"},
{Level: "warn", File: "w.go", Message: "fourth"},
}
if !Blocking(findings) {
t.Error("single error among warns should block")
}
})
}
-50
View File
@@ -1,50 +0,0 @@
// Package gateeval evaluates a repo's .archie/gate.go via Yaegi. Split
// from internal/gate (which only declares the GateContext/Finding types)
// because the generated symbol table in gateextract imports internal/gate --
// this package sits above both to avoid the resulting import cycle.
package gateeval
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/traefik/yaegi/interp"
"github.com/samcharles93/archie-core/internal/gate"
"github.com/samcharles93/archie-core/internal/gate/gateextract"
"github.com/samcharles93/archie-core/internal/yaegiutil"
)
// scriptPath is the per-repo custom gate script, relative to the
// worktree root.
const scriptPath = ".archie/gate.go"
// Evaluate loads and runs the repo's .archie/gate.go against gctx. A
// missing script is not an error -- it returns (nil, nil), meaning no
// custom gate is configured for this repo. The script runs in-process
// (interpreted, not sandboxed), so a panic inside it -- nil dereference,
// out-of-range index -- is recovered and returned as an error rather than
// taking down the daemon.
func Evaluate(gctx gate.GateContext) ([]gate.Finding, error) {
src, err := os.ReadFile(filepath.Join(gctx.Dir, scriptPath))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
return nil, fmt.Errorf("read %s: %w", scriptPath, err)
}
return yaegiutil.Safe(scriptPath, func() ([]gate.Finding, error) {
i, err := yaegiutil.New(interp.Options{}, gateextract.Symbols)
if err != nil {
return nil, err
}
check, err := yaegiutil.Resolve[func(gate.GateContext) []gate.Finding](i, string(src), "gate.Check")
if err != nil {
return nil, fmt.Errorf("%s: %w", scriptPath, err)
}
return check(gctx), nil
})
}
-145
View File
@@ -1,145 +0,0 @@
package gateeval
import (
"os"
"path/filepath"
"testing"
"github.com/samcharles93/archie-core/internal/gate"
)
func writeGateScript(t *testing.T, dir, src string) {
t.Helper()
archieDir := filepath.Join(dir, ".archie")
if err := os.MkdirAll(archieDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(archieDir, "gate.go"), []byte(src), 0o644); err != nil {
t.Fatal(err)
}
}
func TestEvaluateNoScript(t *testing.T) {
dir := t.TempDir()
findings, err := Evaluate(gate.GateContext{Dir: dir})
if err != nil {
t.Fatalf("Evaluate() error = %v, want nil (no script configured)", err)
}
if findings != nil {
t.Fatalf("Evaluate() findings = %v, want nil", findings)
}
}
func TestEvaluateFindings(t *testing.T) {
dir := t.TempDir()
writeGateScript(t, dir, `package gate
import (
"strings"
"github.com/samcharles93/archie-core/internal/gate"
)
func Check(ctx gate.GateContext) []gate.Finding {
var findings []gate.Finding
for _, line := range strings.Split(ctx.Diff, "\n") {
if strings.HasPrefix(line, "+") && strings.Contains(line, "panic(") {
findings = append(findings, gate.Finding{Level: "error", Message: "new panic() call"})
}
}
for _, f := range ctx.ChangedFiles {
if strings.HasSuffix(f, ".md") {
findings = append(findings, gate.Finding{Level: "warn", File: f, Message: "markdown change -- no build impact"})
}
}
return findings
}
`)
findings, err := Evaluate(gate.GateContext{
Dir: dir,
Diff: "+panic(\"boom\")\n",
ChangedFiles: []string{"README.md"},
})
if err != nil {
t.Fatalf("Evaluate() error = %v", err)
}
if len(findings) != 2 {
t.Fatalf("Evaluate() findings = %#v, want 2 findings", findings)
}
if findings[0].Level != "error" || findings[0].Message != "new panic() call" {
t.Errorf("findings[0] = %#v, want the panic error finding", findings[0])
}
if findings[1].Level != "warn" || findings[1].File != "README.md" {
t.Errorf("findings[1] = %#v, want the markdown warn finding", findings[1])
}
if !gate.Blocking(findings) {
t.Error("Blocking(findings) = false, want true (an error-level finding is present)")
}
}
func TestEvaluateClean(t *testing.T) {
dir := t.TempDir()
writeGateScript(t, dir, `package gate
import "github.com/samcharles93/archie-core/internal/gate"
func Check(ctx gate.GateContext) []gate.Finding {
return nil
}
`)
findings, err := Evaluate(gate.GateContext{Dir: dir})
if err != nil {
t.Fatalf("Evaluate() error = %v", err)
}
if len(findings) != 0 {
t.Fatalf("Evaluate() findings = %#v, want none", findings)
}
}
func TestEvaluatePanicRecovered(t *testing.T) {
dir := t.TempDir()
writeGateScript(t, dir, `package gate
import "github.com/samcharles93/archie-core/internal/gate"
func Check(ctx gate.GateContext) []gate.Finding {
var files []string
return []gate.Finding{{Message: files[5]}}
}
`)
_, err := Evaluate(gate.GateContext{Dir: dir})
if err == nil {
t.Fatal("Evaluate() error = nil, want a recovered-panic error")
}
}
func TestEvaluateBadSignature(t *testing.T) {
dir := t.TempDir()
writeGateScript(t, dir, `package gate
func Check(s string) string {
return s
}
`)
_, err := Evaluate(gate.GateContext{Dir: dir})
if err == nil {
t.Fatal("Evaluate() error = nil, want a signature mismatch error")
}
}
func TestEvaluateSyntaxError(t *testing.T) {
dir := t.TempDir()
writeGateScript(t, dir, `package gate
func Check( {{{
`)
_, err := Evaluate(gate.GateContext{Dir: dir})
if err == nil {
t.Fatal("Evaluate() error = nil, want a parse error")
}
}
-10
View File
@@ -1,10 +0,0 @@
// Package gateextract holds the Yaegi symbol table for internal/gate,
// generated by `go generate`. Kept separate from internal/gate itself so
// the generated file can import it without a self-import cycle.
package gateextract
import "reflect"
//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name gateextract github.com/samcharles93/archie-core/internal/gate
var Symbols = map[string]map[string]reflect.Value{}
@@ -1,70 +0,0 @@
package gateextract
import (
"reflect"
"testing"
)
func TestSymbolsContainsExpectedEntries(t *testing.T) {
pkgKey := "github.com/samcharles93/archie-core/internal/gate/gate"
pkg, ok := Symbols[pkgKey]
if !ok {
t.Fatalf("Symbols missing key %q", pkgKey)
}
// Blocking must be a function.
if v, ok := pkg["Blocking"]; !ok {
t.Error("Blocking not found in Symbols")
} else if v.Kind() != reflect.Func {
t.Errorf("Blocking kind = %v, want Func", v.Kind())
}
// LevelError and LevelWarn must be the exported level constants.
for _, name := range []string{"LevelError", "LevelWarn"} {
if v, ok := pkg[name]; !ok {
t.Errorf("%s not found in Symbols", name)
} else if v.Kind() != reflect.String {
t.Errorf("%s kind = %v, want String", name, v.Kind())
}
}
// Finding must be a pointer type.
if v, ok := pkg["Finding"]; !ok {
t.Error("Finding not found in Symbols")
} else if v.Kind() != reflect.Pointer {
t.Errorf("Finding kind = %v, want Ptr", v.Kind())
}
// Level must be a pointer to the defined string type, so interpreted
// scripts can resolve Finding.Level's named type.
if v, ok := pkg["Level"]; !ok {
t.Error("Level not found in Symbols")
} else if v.Kind() != reflect.Pointer {
t.Errorf("Level kind = %v, want Ptr", v.Kind())
}
// GateContext must be a pointer type.
if v, ok := pkg["GateContext"]; !ok {
t.Error("GateContext not found in Symbols")
} else if v.Kind() != reflect.Pointer {
t.Errorf("GateContext kind = %v, want Ptr", v.Kind())
}
}
func TestSymbolsNoUnexpectedEntries(t *testing.T) {
pkgKey := "github.com/samcharles93/archie-core/internal/gate/gate"
pkg := Symbols[pkgKey]
expected := map[string]bool{
"Blocking": true,
"LevelError": true,
"LevelWarn": true,
"Finding": true,
"GateContext": true,
"Level": true,
}
for name := range pkg {
if !expected[name] {
t.Errorf("unexpected symbol %q in gateextract Symbols", name)
}
}
}
@@ -1,22 +0,0 @@
// Code generated by 'yaegi extract github.com/samcharles93/archie-core/internal/gate'. DO NOT EDIT.
package gateextract
import (
"github.com/samcharles93/archie-core/internal/gate"
"reflect"
)
func init() {
Symbols["github.com/samcharles93/archie-core/internal/gate/gate"] = map[string]reflect.Value{
// function, constant and variable definitions
"Blocking": reflect.ValueOf(gate.Blocking),
"LevelError": reflect.ValueOf(gate.LevelError),
"LevelWarn": reflect.ValueOf(gate.LevelWarn),
// type definitions
"Finding": reflect.ValueOf((*gate.Finding)(nil)),
"GateContext": reflect.ValueOf((*gate.GateContext)(nil)),
"Level": reflect.ValueOf((*gate.Level)(nil)),
}
}
+1
View File
@@ -42,6 +42,7 @@ var dashboardPages = []DashboardPage{
{Path: "/system/tasks", Label: "Task settings", Description: "Work lifecycle: statuses, operator actions, and budgets."}, {Path: "/system/tasks", Label: "Task settings", Description: "Work lifecycle: statuses, operator actions, and budgets."},
{Path: "/system/models", Label: "Models", Description: "Model roles and the providers backing them."}, {Path: "/system/models", Label: "Models", Description: "Model roles and the providers backing them."},
{Path: "/system/repos", Label: "Repositories", Description: "Repositories Archie watches, and their per-repo gate overrides."}, {Path: "/system/repos", Label: "Repositories", Description: "Repositories Archie watches, and their per-repo gate overrides."},
{Path: "/system/identities", Label: "Identities", Description: "Persistent actors and lifecycle."},
{Path: "/system/advanced", Label: "Advanced", Description: "Identity, storage, sandboxing, and dangerous actions."}, {Path: "/system/advanced", Label: "Advanced", Description: "Identity, storage, sandboxing, and dangerous actions."},
} }
+3
View File
@@ -160,6 +160,7 @@ type Router struct {
Personas *PersonaRegistry Personas *PersonaRegistry
Tasks TaskCreator // nil = /spawn not configured Tasks TaskCreator // nil = /spawn not configured
Controller TaskController // nil = /approve and /cancel not configured Controller TaskController // nil = /approve and /cancel not configured
Settings *messaging.SettingsCommand
// TaskLister backs /tasks: the live work view (id, title, status, // TaskLister backs /tasks: the live work view (id, title, status,
// workflow/stage, age). nil = /tasks not configured. // workflow/stage, age). nil = /tasks not configured.
TaskLister ChatTaskLister TaskLister ChatTaskLister
@@ -308,6 +309,8 @@ func (r *Router) dispatchLocal(ctx context.Context, msg messaging.Message, text,
case "/cancel": case "/cancel":
reply, err := r.handleCancel(ctx, rest) reply, err := r.handleCancel(ctx, rest)
return reply, true, err return reply, true, err
case "/settings":
return r.Settings.Execute(ctx, "", rest), true, nil
case "/start": case "/start":
reply, err := r.handleStart() reply, err := r.handleStart()
return reply, true, err return reply, true, err
+26 -13
View File
@@ -3,9 +3,11 @@ package gateway
import ( import (
"context" "context"
"fmt" "fmt"
"sort"
"strings" "strings"
"sync" "sync"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/messaging"
) )
@@ -43,20 +45,12 @@ func NewPersonaRegistry(personas []Persona) *PersonaRegistry {
// DefaultPersonas returns Archie as the baseline identity followed by // DefaultPersonas returns Archie as the baseline identity followed by
// optional communication styles. // optional communication styles.
func DefaultPersonas() []Persona { func DefaultPersonas() []Persona {
return []Persona{ shipped := agent.ShippedPersonas()
{ personas := make([]Persona, 0, len(shipped.Personas))
Name: "archie", for _, persona := range shipped.Personas {
Prompt: "You are Archie, a capable coding and project assistant. " + personas = append(personas, Persona{Name: persona.Name, Prompt: persona.Prompt})
"Be direct without being brusque, grounded in the actual workspace state, and use available tools when asked. " +
"Do not claim tools, files, memories, actions, or results you have not verified. " +
"Do not impersonate another assistant, provider, or vendor.",
},
{Name: "helpful", Prompt: "You are a helpful, friendly AI assistant."},
{Name: "concise", Prompt: "You are a concise assistant. Keep responses brief and to the point."},
{Name: "technical", Prompt: "You are a technical expert. Provide detailed, accurate technical information."},
{Name: "creative", Prompt: "You are a creative assistant. Think outside the box and offer innovative solutions."},
{Name: "teacher", Prompt: "You are a patient teacher. Explain concepts clearly with examples."},
} }
return personas
} }
// List returns all available persona names. // List returns all available persona names.
@@ -67,9 +61,28 @@ func (r *PersonaRegistry) List() []string {
for _, p := range r.personas { for _, p := range r.personas {
names = append(names, p.Name) names = append(names, p.Name)
} }
sort.Strings(names)
return names return names
} }
// Replace atomically changes the available definitions. Sessions whose
// selection no longer exists use the new default.
func (r *PersonaRegistry) Replace(personas []Persona, defaultName string) {
r.mu.Lock()
defer r.mu.Unlock()
next := make(map[string]Persona, len(personas))
for _, persona := range personas {
next[persona.Name] = persona
}
for session, name := range r.active {
if _, exists := next[name]; !exists {
delete(r.active, session)
}
}
r.personas = next
r.defaultName = defaultName
}
// SetActive sets the active persona for a session. // SetActive sets the active persona for a session.
func (r *PersonaRegistry) SetActive(sessionKey, name string) bool { func (r *PersonaRegistry) SetActive(sessionKey, name string) bool {
r.mu.Lock() r.mu.Lock()
+14
View File
@@ -57,6 +57,20 @@ func TestPersonaRegistryEmpty(t *testing.T) {
} }
} }
func TestPersonaRegistryReplaceFallsBackToNewDefault(t *testing.T) {
r := NewPersonaRegistry(DefaultPersonas())
if !r.SetActive("session", "creative") {
t.Fatal("select creative")
}
r.Replace([]Persona{{Name: "archie", Prompt: "new baseline"}, {Name: "concise", Prompt: "brief"}}, "concise")
if got := r.ActiveName("session"); got != "concise" {
t.Fatalf("ActiveName() = %q, want concise", got)
}
if got := r.GetActive("session"); got != "brief" {
t.Fatalf("GetActive() = %q, want brief", got)
}
}
func TestPersonaRegistryConcurrent(t *testing.T) { func TestPersonaRegistryConcurrent(t *testing.T) {
r := NewPersonaRegistry(DefaultPersonas()) r := NewPersonaRegistry(DefaultPersonas())
done := make(chan struct{}) done := make(chan struct{})
@@ -21,6 +21,8 @@ import (
"github.com/samcharles93/archie-core/internal/worktreerpc" "github.com/samcharles93/archie-core/internal/worktreerpc"
) )
const testDefinition = "id: implement\nsteps: []\n"
func TestTransportContainsNoSharedTaskWorkerTopology(t *testing.T) { func TestTransportContainsNoSharedTaskWorkerTopology(t *testing.T) {
source, err := os.ReadFile("transport.go") source, err := os.ReadFile("transport.go")
if err != nil { if err != nil {
@@ -111,7 +113,7 @@ func TestSubscribeTasksServesOnlyBootTaskSubject(t *testing.T) {
} }
t.Cleanup(func() { _ = subscription.Close() }) t.Cleanup(func() { _ = subscription.Close() })
payload, err := json.Marshal(taskrun.Request{Task: &workflow.Task{ID: 42}, WorktreeGrant: "grant"}) payload, err := json.Marshal(taskrun.Request{Task: &workflow.Task{ID: 42}, WorktreeGrant: "grant", WorkflowDefinition: testDefinition})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -151,8 +153,9 @@ func TestSubscribeTasksOwnsWireErrors(t *testing.T) {
{name: "null task", payload: []byte(`{"task":null}`), want: "validate taskrun request: task is required"}, {name: "null task", payload: []byte(`{"task":null}`), want: "validate taskrun request: task is required"},
{name: "nonpositive task ID", payload: []byte(`{"task":{"id":0}}`), want: "validate taskrun request: task ID must be positive, got 0"}, {name: "nonpositive task ID", payload: []byte(`{"task":{"id":0}}`), want: "validate taskrun request: task ID must be positive, got 0"},
{name: "missing worktree grant", payload: []byte(`{"task":{"id":9}}`), want: "validate taskrun request: worktree grant is required"}, {name: "missing worktree grant", payload: []byte(`{"task":{"id":9}}`), want: "validate taskrun request: worktree grant is required"},
{name: "payload subject mismatch", payload: []byte(`{"task":{"id":8},"worktree_grant":"grant"}`), want: "validate taskrun request: task ID 8 does not match subject task ID 9"}, {name: "missing workflow definition", payload: []byte(`{"task":{"id":9},"worktree_grant":"grant"}`), want: "validate taskrun request: workflow definition is required"},
{name: "handler", payload: []byte(`{"task":{"id":9},"worktree_grant":"grant"}`), want: "run failed", wantHandlerCalls: 1}, {name: "payload subject mismatch", payload: []byte(`{"task":{"id":8},"worktree_grant":"grant","workflow_definition":"id: implement\nsteps: []\n"}`), want: "validate taskrun request: task ID 8 does not match subject task ID 9"},
{name: "handler", payload: []byte(`{"task":{"id":9},"worktree_grant":"grant","workflow_definition":"id: implement\nsteps: []\n"}`), want: "run failed", wantHandlerCalls: 1},
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
before := handlerCalls before := handlerCalls
@@ -213,7 +216,7 @@ func TestHandleTaskRejectsSubjectCorrelationErrors(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
payload, err := json.Marshal(taskrun.Request{Task: &workflow.Task{ID: test.requestID}, WorktreeGrant: "grant"}) payload, err := json.Marshal(taskrun.Request{Task: &workflow.Task{ID: test.requestID}, WorktreeGrant: "grant", WorkflowDefinition: testDefinition})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -113,6 +113,12 @@ func (s Schedule) firstRun(now time.Time) (time.Time, error) {
} }
} }
func (s Schedule) FirstRun(now time.Time) (time.Time, error) { return s.firstRun(now) }
func (s Schedule) NextRun(lastRun time.Time) (time.Time, error) { return s.nextRun(lastRun) }
func (s Schedule) Resolved() Schedule { return s.resolve() }
// nextRun returns when the job should fire after a successful run at // nextRun returns when the job should fire after a successful run at
// lastRun. It is the engine-side counterpart to firstRun: every MarkRun // lastRun. It is the engine-side counterpart to firstRun: every MarkRun
// advances next_run through this function. Interval is fully implemented; // advances next_run through this function. Interval is fully implemented;
+9 -2
View File
@@ -8,8 +8,10 @@ import (
"google.golang.org/grpc" "google.golang.org/grpc"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workflow/task"
@@ -22,15 +24,19 @@ import (
// as gatewayrpc.Client asserts both messaging.ChatContract and // as gatewayrpc.Client asserts both messaging.ChatContract and
// messaging.SessionStore. See docs/prds/state-store-contract.md §2. // messaging.SessionStore. See docs/prds/state-store-contract.md §2.
type Client struct { type Client struct {
client pb.StateStoreServiceClient client pb.StateStoreServiceClient
controlPlane controlpb.ControlPlaneServiceClient
} }
// NewClient wraps conn's generated client. Close is a no-op: the store // NewClient wraps conn's generated client. Close is a no-op: the store
// service owns its own DB lifecycle (§11). // service owns its own DB lifecycle (§11).
func NewClient(conn grpc.ClientConnInterface) *Client { func NewClient(conn grpc.ClientConnInterface) *Client {
return &Client{client: pb.NewStateStoreServiceClient(conn)} return &Client{client: pb.NewStateStoreServiceClient(conn), controlPlane: controlpb.NewControlPlaneServiceClient(conn)}
} }
// ControlPlane returns the generic control-plane RPC client on the same authenticated connection.
func (c *Client) ControlPlane() controlpb.ControlPlaneServiceClient { return c.controlPlane }
// Close is a no-op; the remote store service owns its own DB lifecycle. // Close is a no-op; the remote store service owns its own DB lifecycle.
func (c *Client) Close() error { return nil } func (c *Client) Close() error { return nil }
@@ -44,6 +50,7 @@ var (
_ storecontract.BindingDispatcher = (*Client)(nil) _ storecontract.BindingDispatcher = (*Client)(nil)
_ storecontract.BindingTaskCreator = (*Client)(nil) _ storecontract.BindingTaskCreator = (*Client)(nil)
_ storecontract.ConfigSnapshotStore = (*Client)(nil) _ storecontract.ConfigSnapshotStore = (*Client)(nil)
_ identity.Repository = (*Client)(nil)
) )
// Lifecycle // Lifecycle
@@ -0,0 +1,195 @@
package staterpc
import (
"context"
"errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func (s *server) ListIdentities(ctx context.Context, _ *pb.ListIdentitiesRequest) (*pb.ListIdentitiesResponse, error) {
if s.deps.Identities == nil {
return nil, status.Error(codes.Unavailable, "identity store unavailable")
}
values, err := s.deps.Identities.List(ctx)
if err != nil {
return nil, identityStatus(err)
}
out := make([]*pb.Identity, len(values))
for i := range values {
out[i] = identityProto(values[i])
}
return &pb.ListIdentitiesResponse{Identities: out}, nil
}
func (s *server) GetIdentity(ctx context.Context, request *pb.GetIdentityRequest) (*pb.GetIdentityResponse, error) {
value, err := s.deps.Identities.Get(ctx, identity.IdentityID(request.Id))
if errors.Is(err, identity.ErrNotFound) {
value, err = s.deps.Identities.ResolveLegacyName(ctx, request.Id)
}
if err != nil {
return nil, identityStatus(err)
}
return &pb.GetIdentityResponse{Identity: identityProto(value)}, nil
}
func (s *server) CreateIdentity(ctx context.Context, request *pb.CreateIdentityRequest) (*pb.CreateIdentityResponse, error) {
value, err := identity.New(identity.IdentityID(request.Id), identity.Kind(request.Kind), request.DisplayName)
if err == nil {
value, err = s.deps.Identities.Create(ctx, value, identityAudit(request.Audit))
}
if err != nil {
return nil, identityStatus(err)
}
return &pb.CreateIdentityResponse{Identity: identityProto(value)}, nil
}
func (s *server) RenameIdentity(ctx context.Context, request *pb.RenameIdentityRequest) (*pb.RenameIdentityResponse, error) {
value, err := s.applyIdentityCommand(ctx, request.Id, request.ExpectedVersion, request.Audit, identity.Command{Type: identity.CommandRename, DisplayName: request.DisplayName})
return &pb.RenameIdentityResponse{Identity: identityProto(value)}, err
}
func (s *server) SuspendIdentity(ctx context.Context, request *pb.SuspendIdentityRequest) (*pb.SuspendIdentityResponse, error) {
value, err := s.applyIdentityCommand(ctx, request.Id, request.ExpectedVersion, request.Audit, identity.Command{Type: identity.CommandSuspend})
return &pb.SuspendIdentityResponse{Identity: identityProto(value)}, err
}
func (s *server) ReactivateIdentity(ctx context.Context, request *pb.ReactivateIdentityRequest) (*pb.ReactivateIdentityResponse, error) {
value, err := s.applyIdentityCommand(ctx, request.Id, request.ExpectedVersion, request.Audit, identity.Command{Type: identity.CommandReactivate})
return &pb.ReactivateIdentityResponse{Identity: identityProto(value)}, err
}
func (s *server) RetireIdentity(ctx context.Context, request *pb.RetireIdentityRequest) (*pb.RetireIdentityResponse, error) {
value, err := s.applyIdentityCommand(ctx, request.Id, request.ExpectedVersion, request.Audit, identity.Command{Type: identity.CommandRetire})
return &pb.RetireIdentityResponse{Identity: identityProto(value)}, err
}
func (s *server) applyIdentityCommand(ctx context.Context, id string, version int64, audit *pb.IdentityAudit, command identity.Command) (identity.Identity, error) {
value, err := s.deps.Identities.Apply(ctx, identity.IdentityID(id), version, command, identityAudit(audit))
if err != nil {
return identity.Identity{}, identityStatus(err)
}
return value, nil
}
func (c *Client) List(ctx context.Context) ([]identity.Identity, error) {
response, err := c.client.ListIdentities(ctx, &pb.ListIdentitiesRequest{})
if err != nil {
return nil, identityClientError(err)
}
out := make([]identity.Identity, len(response.Identities))
for i := range response.Identities {
out[i] = identityValue(response.Identities[i])
}
return out, nil
}
func (c *Client) Get(ctx context.Context, id identity.IdentityID) (identity.Identity, error) {
response, err := c.client.GetIdentity(ctx, &pb.GetIdentityRequest{Id: string(id)})
if err != nil {
return identity.Identity{}, identityClientError(err)
}
return identityValue(response.Identity), nil
}
func (c *Client) ResolveLegacyName(ctx context.Context, name string) (identity.Identity, error) {
return c.Get(ctx, identity.IdentityID(name))
}
func (c *Client) Create(ctx context.Context, value identity.Identity, audit identity.Audit) (identity.Identity, error) {
response, err := c.client.CreateIdentity(ctx, &pb.CreateIdentityRequest{Id: string(value.ID), Kind: string(value.Kind), DisplayName: value.DisplayName, Audit: auditProto(audit)})
if err != nil {
return identity.Identity{}, identityClientError(err)
}
return identityValue(response.Identity), nil
}
func (c *Client) Apply(ctx context.Context, id identity.IdentityID, version int64, command identity.Command, audit identity.Audit) (identity.Identity, error) {
var value *pb.Identity
var err error
switch command.Type {
case identity.CommandRename:
response, callErr := c.client.RenameIdentity(ctx, &pb.RenameIdentityRequest{Id: string(id), ExpectedVersion: version, DisplayName: command.DisplayName, Audit: auditProto(audit)})
err = callErr
if response != nil {
value = response.Identity
}
case identity.CommandSuspend:
response, callErr := c.client.SuspendIdentity(ctx, &pb.SuspendIdentityRequest{Id: string(id), ExpectedVersion: version, Audit: auditProto(audit)})
err = callErr
if response != nil {
value = response.Identity
}
case identity.CommandReactivate:
response, callErr := c.client.ReactivateIdentity(ctx, &pb.ReactivateIdentityRequest{Id: string(id), ExpectedVersion: version, Audit: auditProto(audit)})
err = callErr
if response != nil {
value = response.Identity
}
case identity.CommandRetire:
response, callErr := c.client.RetireIdentity(ctx, &pb.RetireIdentityRequest{Id: string(id), ExpectedVersion: version, Audit: auditProto(audit)})
err = callErr
if response != nil {
value = response.Identity
}
default:
return identity.Identity{}, identity.ErrInvalid
}
if err != nil {
return identity.Identity{}, identityClientError(err)
}
return identityValue(value), nil
}
func identityProto(value identity.Identity) *pb.Identity {
return &pb.Identity{Id: string(value.ID), Kind: string(value.Kind), DisplayName: value.DisplayName, Lifecycle: string(value.Lifecycle), Version: value.Version, CreatedAt: timestamppb.New(value.CreatedAt), UpdatedAt: timestamppb.New(value.UpdatedAt)}
}
func identityValue(value *pb.Identity) identity.Identity {
if value == nil {
return identity.Identity{}
}
return identity.Identity{ID: identity.IdentityID(value.Id), Kind: identity.Kind(value.Kind), DisplayName: value.DisplayName, Lifecycle: identity.Lifecycle(value.Lifecycle), Version: value.Version, CreatedAt: value.CreatedAt.AsTime(), UpdatedAt: value.UpdatedAt.AsTime()}
}
func identityAudit(value *pb.IdentityAudit) identity.Audit {
if value == nil {
return identity.Audit{}
}
return identity.Audit{ActorID: identity.IdentityID(value.ActorId), Source: value.Source, RequestID: value.RequestId}
}
func auditProto(value identity.Audit) *pb.IdentityAudit {
return &pb.IdentityAudit{ActorId: string(value.ActorID), Source: value.Source, RequestId: value.RequestID}
}
func identityStatus(err error) error {
switch {
case errors.Is(err, identity.ErrNotFound):
return status.Error(codes.NotFound, err.Error())
case errors.Is(err, identity.ErrConflict):
return status.Error(codes.Aborted, err.Error())
case errors.Is(err, identity.ErrInvalid), errors.Is(err, identity.ErrIllegalTransition), errors.Is(err, identity.ErrSystemImmutable):
return status.Error(codes.FailedPrecondition, err.Error())
default:
return status.Error(codes.Internal, "internal state store error")
}
}
func identityClientError(err error) error {
switch status.Code(err) {
case codes.NotFound:
return identity.ErrNotFound
case codes.Aborted:
return identity.ErrConflict
case codes.FailedPrecondition:
return errors.Join(identity.ErrInvalid, err)
default:
return err
}
}
@@ -15,8 +15,10 @@ import (
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/binding"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/mapping" "github.com/samcharles93/archie-core/internal/domain/mapping"
"github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/logging" "github.com/samcharles93/archie-core/internal/logging"
@@ -55,6 +57,8 @@ const taskLogChunkBytes = 256 << 10
// codes.Unavailable) exactly as their daemon-side consumers already treat a // codes.Unavailable) exactly as their daemon-side consumers already treat a
// nil Mappings/Bindings/BindingDispatcher/BindingTaskCreator as "disabled". // nil Mappings/Bindings/BindingDispatcher/BindingTaskCreator as "disabled".
type Deps struct { type Deps struct {
ControlPlane controlpb.ControlPlaneServiceServer
Identities identity.Repository
Grants *TaskGrants Grants *TaskGrants
Tasks storecontract.TaskStore Tasks storecontract.TaskStore
Captures storecontract.CaptureStore Captures storecontract.CaptureStore
@@ -87,6 +91,9 @@ func RegisterServer(registrar grpc.ServiceRegistrar, deps Deps) {
deps.Log = slog.New(slog.DiscardHandler) deps.Log = slog.New(slog.DiscardHandler)
} }
pb.RegisterStateStoreServiceServer(registrar, &server{deps: deps}) pb.RegisterStateStoreServiceServer(registrar, &server{deps: deps})
if deps.ControlPlane != nil {
controlpb.RegisterControlPlaneServiceServer(registrar, deps.ControlPlane)
}
} }
func (s *server) logErr(rpc string, err error) error { func (s *server) logErr(rpc string, err error) error {
+200
View File
@@ -0,0 +1,200 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
const identitiesSchema = `
CREATE TABLE IF NOT EXISTS identities (
id TEXT PRIMARY KEY NOT NULL, kind TEXT NOT NULL, display_name TEXT NOT NULL,
lifecycle TEXT NOT NULL, version INTEGER NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS identity_aliases (
alias TEXT PRIMARY KEY COLLATE NOCASE NOT NULL, identity_id TEXT NOT NULL REFERENCES identities(id)
);
CREATE TABLE IF NOT EXISTS identity_events (
id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL,
actor_id TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL
);`
const identityTimeLayout = time.RFC3339Nano
func (s *Store) List(ctx context.Context) (_ []identity.Identity, retErr error) {
rows, err := s.db.QueryContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities ORDER BY created_at, id`)
if err != nil {
return nil, err
}
defer func() { retErr = errors.Join(retErr, rows.Close()) }()
var out []identity.Identity
for rows.Next() {
value, err := scanIdentity(rows)
if err != nil {
return nil, err
}
out = append(out, value)
}
return out, rows.Err()
}
func (s *Store) Get(ctx context.Context, id identity.IdentityID) (identity.Identity, error) {
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
return value, err
}
func (s *Store) ResolveLegacyName(ctx context.Context, name string) (identity.Identity, error) {
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at FROM identities i JOIN identity_aliases a ON a.identity_id=i.id WHERE a.alias=?`, strings.TrimSpace(name)))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
return value, err
}
func (s *Store) Create(ctx context.Context, value identity.Identity, audit identity.Audit) (identity.Identity, error) {
if err := value.Validate(); err != nil {
return identity.Identity{}, err
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
value.Version, value.CreatedAt, value.UpdatedAt = 1, now, now
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback() }()
if _, err = tx.ExecContext(ctx, `INSERT INTO identities(id,kind,display_name,lifecycle,version,created_at,updated_at) VALUES(?,?,?,?,?,?,?)`, value.ID, value.Kind, value.DisplayName, value.Lifecycle, value.Version, now.Format(identityTimeLayout), now.Format(identityTimeLayout)); err != nil {
return identity.Identity{}, err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO identity_aliases(alias,identity_id) VALUES(?,?)`, value.DisplayName, value.ID); err != nil {
return identity.Identity{}, err
}
if err = insertIdentityEvent(ctx, tx, value, identity.Event{IdentityID: value.ID, Type: "create", To: value.Lifecycle, DisplayName: value.DisplayName}, audit, now); err != nil {
return identity.Identity{}, err
}
return value, tx.Commit()
}
func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersion int64, command identity.Command, audit identity.Audit) (identity.Identity, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return identity.Identity{}, err
}
defer func() { _ = tx.Rollback() }()
current, err := scanIdentity(tx.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
if err != nil {
return identity.Identity{}, err
}
if current.Version != expectedVersion {
return identity.Identity{}, identity.ErrConflict
}
next, event, err := identity.Apply(current, command)
if err != nil {
return identity.Identity{}, err
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
next.UpdatedAt = now
result, err := tx.ExecContext(ctx, `UPDATE identities SET display_name=?, lifecycle=?, version=?, updated_at=? WHERE id=? AND version=?`, next.DisplayName, next.Lifecycle, next.Version, now.Format(identityTimeLayout), id, expectedVersion)
if err != nil {
return identity.Identity{}, err
}
changed, _ := result.RowsAffected()
if changed != 1 {
return identity.Identity{}, identity.ErrConflict
}
if command.Type == identity.CommandRename {
if _, err = tx.ExecContext(ctx, `INSERT OR IGNORE INTO identity_aliases(alias,identity_id) VALUES(?,?)`, next.DisplayName, id); err != nil {
return identity.Identity{}, err
}
}
if err = insertIdentityEvent(ctx, tx, next, event, audit, now); err != nil {
return identity.Identity{}, err
}
return next, tx.Commit()
}
func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error {
values := append([]struct {
id identity.IdentityID
kind identity.Kind
name string
}{{identity.SystemID, identity.KindSystem, "System"}}, make([]struct {
id identity.IdentityID
kind identity.Kind
name string
}, len(legacyNames))...)
for i, name := range legacyNames {
name = strings.TrimSpace(name)
values[i+1] = struct {
id identity.IdentityID
kind identity.Kind
name string
}{identity.StableID(name), identity.KindBot, name}
}
for _, seed := range values {
if seed.name == "" {
continue
}
value, err := identity.New(seed.id, seed.kind, seed.name)
if err != nil {
return err
}
_, err = s.Create(ctx, value, identity.Audit{ActorID: identity.SystemID, Source: "legacy-config", RequestID: "identity-import:" + string(seed.id)})
if err != nil && !isSQLiteUnique(err) {
return fmt.Errorf("bootstrap identity %q: %w", seed.name, err)
}
if _, aliasErr := s.db.ExecContext(ctx, `INSERT OR IGNORE INTO identity_aliases(alias,identity_id) VALUES(?,?)`, seed.name, seed.id); aliasErr != nil {
return aliasErr
}
if seed.kind != identity.KindSystem {
if _, migrateErr := s.db.ExecContext(ctx, `UPDATE tasks SET identity=? WHERE identity=?`, seed.id, seed.name); migrateErr != nil {
return migrateErr
}
}
}
return nil
}
type identityScanner interface{ Scan(...any) error }
func scanIdentity(row identityScanner) (identity.Identity, error) {
var v identity.Identity
var created, updated string
err := row.Scan(&v.ID, &v.Kind, &v.DisplayName, &v.Lifecycle, &v.Version, &created, &updated)
if err != nil {
return v, err
}
v.CreatedAt, err = time.Parse(identityTimeLayout, created)
if err != nil {
return v, err
}
v.UpdatedAt, err = time.Parse(identityTimeLayout, updated)
return v, err
}
func insertIdentityEvent(ctx context.Context, tx *sql.Tx, value identity.Identity, event identity.Event, audit identity.Audit, at time.Time) error {
if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" {
return fmt.Errorf("%w: audit actor, source, and request ID are required", identity.ErrInvalid)
}
_, err := tx.ExecContext(ctx, `INSERT INTO identity_events(identity_id,event_type,from_lifecycle,to_lifecycle,display_name,actor_id,source,request_id,at) VALUES(?,?,?,?,?,?,?,?,?)`, value.ID, event.Type, event.From, event.To, event.DisplayName, audit.ActorID, audit.Source, audit.RequestID, at.Format(identityTimeLayout))
return err
}
func isSQLiteUnique(err error) bool { return strings.Contains(err.Error(), "UNIQUE constraint failed") }
+84
View File
@@ -0,0 +1,84 @@
package store
import (
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
func TestIdentityMutationPersistsAuditAndHistoricalName(t *testing.T) {
s := OpenTest(t)
defer s.Close()
created, err := identity.New(identity.StableID("reviewer"), identity.KindBot, "Reviewer")
if err != nil {
t.Fatal(err)
}
created, err = s.Create(t.Context(), created, identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: "create"})
if err != nil {
t.Fatal(err)
}
renamed, err := s.Apply(t.Context(), created.ID, created.Version, identity.Command{Type: identity.CommandRename, DisplayName: "Review Bot"}, identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: "rename"})
if err != nil {
t.Fatal(err)
}
resolved, err := s.ResolveLegacyName(t.Context(), "reviewer")
if err != nil {
t.Fatal(err)
}
if resolved.ID != renamed.ID || resolved.DisplayName != "Review Bot" {
t.Fatalf("resolved = %+v, want renamed identity", resolved)
}
var count int
if err := s.DB().QueryRowContext(t.Context(), `SELECT COUNT(*) FROM identity_events WHERE identity_id = ?`, renamed.ID).Scan(&count); err != nil {
t.Fatal(err)
}
if count != 2 {
t.Fatalf("audit count = %d, want 2", count)
}
if _, err := s.Apply(t.Context(), renamed.ID, created.Version, identity.Command{Type: identity.CommandSuspend}, identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: "stale"}); !errors.Is(err, identity.ErrConflict) {
t.Fatalf("stale apply error = %v, want conflict", err)
}
}
func TestBootstrapIdentitiesIsStableAndNonDestructive(t *testing.T) {
s := OpenTest(t)
defer s.Close()
if inserted, err := s.EnqueueIssue(t.Context(), "acme", "widget", 7, "Legacy", "", "", "reviewer"); err != nil || !inserted {
t.Fatalf("seed legacy task = %v, %v", inserted, err)
}
if err := s.BootstrapIdentities(t.Context(), []string{"archie", "reviewer"}); err != nil {
t.Fatal(err)
}
reviewer, err := s.ResolveLegacyName(t.Context(), "reviewer")
if err != nil {
t.Fatal(err)
}
if _, err := s.Apply(t.Context(), reviewer.ID, reviewer.Version, identity.Command{Type: identity.CommandRename, DisplayName: "Custom"}, identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: "rename"}); err != nil {
t.Fatal(err)
}
if err := s.BootstrapIdentities(t.Context(), []string{"archie", "reviewer"}); err != nil {
t.Fatal(err)
}
got, err := s.Get(t.Context(), reviewer.ID)
if err != nil {
t.Fatal(err)
}
if got.DisplayName != "Custom" {
t.Fatalf("bootstrap overwrote name with %q", got.DisplayName)
}
all, err := s.List(t.Context())
if err != nil {
t.Fatal(err)
}
if len(all) != 3 {
t.Fatalf("identity count = %d, want system plus two configured", len(all))
}
task, err := s.TaskByIssue(t.Context(), "acme", "widget", 7)
if err != nil {
t.Fatal(err)
}
if task.Identity != string(reviewer.ID) {
t.Fatalf("legacy task identity = %q, want %q", task.Identity, reviewer.ID)
}
}
+106
View File
@@ -0,0 +1,106 @@
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
var (
ErrResourceNotFound = errors.New("resource not found")
ErrResourceVersionConflict = errors.New("resource version conflict")
)
type Resource struct {
Kind string
Value []byte
Version int64
Actor string
Source string
RequestID string
ExpectedVersion int64
CurrentVersion int64
At time.Time
}
type ResourceWrite struct {
Kind string
Value []byte
Actor string
Source string
RequestID string
ExpectedVersion int64
At time.Time
}
const resourcesSchema = `
CREATE TABLE IF NOT EXISTS resources (
kind TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL, updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS resource_history (
id INTEGER PRIMARY KEY AUTOINCREMENT, kind TEXT NOT NULL, value BLOB NOT NULL,
version INTEGER NOT NULL, actor TEXT NOT NULL, source TEXT NOT NULL,
request_id TEXT NOT NULL UNIQUE, expected_version INTEGER NOT NULL,
current_version INTEGER NOT NULL, at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_resource_history_kind_version ON resource_history(kind, version);
`
func (s *Store) Resource(ctx context.Context, kind string) (Resource, error) {
var r Resource
err := s.db.QueryRowContext(ctx, `SELECT kind,value,version,updated_at FROM resources WHERE kind=?`, kind).
Scan(&r.Kind, &r.Value, &r.Version, sqliteTime{&r.At})
if errors.Is(err, sql.ErrNoRows) {
return Resource{}, ErrResourceNotFound
}
return r, err
}
func (s *Store) PutResource(ctx context.Context, w ResourceWrite) (_ Resource, retErr error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return Resource{}, err
}
defer func() { _ = tx.Rollback() }()
if existing, ok, err := resourceByRequest(ctx, tx, w.RequestID); err != nil {
return Resource{}, err
} else if ok {
return existing, nil
}
var current int64
err = tx.QueryRowContext(ctx, `SELECT version FROM resources WHERE kind=?`, w.Kind).Scan(&current)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return Resource{}, err
}
if current != w.ExpectedVersion {
return Resource{}, fmt.Errorf("%w: expected %d, current %d", ErrResourceVersionConflict, w.ExpectedVersion, current)
}
if w.At.IsZero() {
w.At = time.Now().UTC()
}
next := current + 1
at := w.At.UTC().Format(time.RFC3339Nano)
if _, err := tx.ExecContext(ctx, `INSERT INTO resources(kind,value,version,updated_at) VALUES(?,?,?,?) ON CONFLICT(kind) DO UPDATE SET value=excluded.value,version=excluded.version,updated_at=excluded.updated_at`, w.Kind, w.Value, next, at); err != nil {
return Resource{}, err
}
if _, err := tx.ExecContext(ctx, `INSERT INTO resource_history(kind,value,version,actor,source,request_id,expected_version,current_version,at) VALUES(?,?,?,?,?,?,?,?,?)`, w.Kind, w.Value, next, w.Actor, w.Source, w.RequestID, w.ExpectedVersion, current, at); err != nil {
return Resource{}, err
}
if err := tx.Commit(); err != nil {
return Resource{}, err
}
return Resource{Kind: w.Kind, Value: append([]byte(nil), w.Value...), Version: next, Actor: w.Actor, Source: w.Source, RequestID: w.RequestID, ExpectedVersion: w.ExpectedVersion, CurrentVersion: current, At: w.At.UTC()}, nil
}
func resourceByRequest(ctx context.Context, tx *sql.Tx, requestID string) (Resource, bool, error) {
var r Resource
err := tx.QueryRowContext(ctx, `SELECT kind,value,version,actor,source,request_id,expected_version,current_version,at FROM resource_history WHERE request_id=?`, requestID).
Scan(&r.Kind, &r.Value, &r.Version, &r.Actor, &r.Source, &r.RequestID, &r.ExpectedVersion, &r.CurrentVersion, sqliteTime{&r.At})
if errors.Is(err, sql.ErrNoRows) {
return Resource{}, false, nil
}
return r, err == nil, err
}
+40
View File
@@ -0,0 +1,40 @@
package store
import (
"errors"
"testing"
"time"
)
func TestPutResourceRejectsStaleVersion(t *testing.T) {
s := OpenTest(t)
defer s.Close()
ctx := t.Context()
first, err := s.PutResource(ctx, ResourceWrite{Kind: "settings", Value: []byte(`{"v":1}`), Actor: "a", Source: "test", RequestID: "r1", ExpectedVersion: 0, At: time.Now()})
if err != nil {
t.Fatal(err)
}
_, err = s.PutResource(ctx, ResourceWrite{Kind: "settings", Value: []byte(`{"v":2}`), Actor: "a", Source: "test", RequestID: "r2", ExpectedVersion: 0, At: time.Now()})
if !errors.Is(err, ErrResourceVersionConflict) {
t.Fatalf("PutResource() error = %v, want ErrResourceVersionConflict (current %d)", err, first.Version)
}
}
func TestPutResourceDuplicateRequestIsIdempotent(t *testing.T) {
s := OpenTest(t)
defer s.Close()
ctx := t.Context()
write := ResourceWrite{Kind: "settings", Value: []byte(`{"v":1}`), Actor: "a", Source: "test", RequestID: "same", ExpectedVersion: 0, At: time.Now()}
first, err := s.PutResource(ctx, write)
if err != nil {
t.Fatal(err)
}
write.Value = []byte(`{"v":999}`)
second, err := s.PutResource(ctx, write)
if err != nil {
t.Fatal(err)
}
if first.Version != second.Version || string(second.Value) != string(first.Value) {
t.Fatalf("duplicate = (%d, %s), want (%d, %s)", second.Version, second.Value, first.Version, first.Value)
}
}
+24 -9
View File
@@ -54,7 +54,7 @@ func Open(ctx context.Context, path string, opts ...OpenOption) (*Store, error)
return nil, err return nil, err
} }
db.SetMaxOpenConns(1) db.SetMaxOpenConns(1)
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema+bindingsSchema+configSnapshotSchema); err != nil { if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema+bindingsSchema+configSnapshotSchema+resourcesSchema+identitiesSchema); err != nil {
return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close()) return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close())
} }
if err := migrateTasks(ctx, db); err != nil { if err := migrateTasks(ctx, db); err != nil {
@@ -117,6 +117,9 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
{"tasks", "binding_id", `ALTER TABLE tasks ADD COLUMN binding_id INTEGER NOT NULL DEFAULT 0`}, {"tasks", "binding_id", `ALTER TABLE tasks ADD COLUMN binding_id INTEGER NOT NULL DEFAULT 0`},
{"tasks", "binding_version", `ALTER TABLE tasks ADD COLUMN binding_version INTEGER NOT NULL DEFAULT 0`}, {"tasks", "binding_version", `ALTER TABLE tasks ADD COLUMN binding_version INTEGER NOT NULL DEFAULT 0`},
{"tasks", "review_payload", `ALTER TABLE tasks ADD COLUMN review_payload TEXT NOT NULL DEFAULT ''`}, {"tasks", "review_payload", `ALTER TABLE tasks ADD COLUMN review_payload TEXT NOT NULL DEFAULT ''`},
{"tasks", "workflow_definition_version", `ALTER TABLE tasks ADD COLUMN workflow_definition_version INTEGER NOT NULL DEFAULT 0`},
{"tasks", "workflow_definition_digest", `ALTER TABLE tasks ADD COLUMN workflow_definition_digest TEXT NOT NULL DEFAULT ''`},
{"tasks", "workflow_definition_yaml", `ALTER TABLE tasks ADD COLUMN workflow_definition_yaml TEXT NOT NULL DEFAULT ''`},
{"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`}, {"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`},
{"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`}, {"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`},
{"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`}, {"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`},
@@ -201,6 +204,9 @@ CREATE TABLE IF NOT EXISTS tasks (
binding_id INTEGER NOT NULL DEFAULT 0, binding_id INTEGER NOT NULL DEFAULT 0,
binding_version INTEGER NOT NULL DEFAULT 0, binding_version INTEGER NOT NULL DEFAULT 0,
review_payload TEXT NOT NULL DEFAULT '', review_payload TEXT NOT NULL DEFAULT '',
workflow_definition_version INTEGER NOT NULL DEFAULT 0,
workflow_definition_digest TEXT NOT NULL DEFAULT '',
workflow_definition_yaml TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')), created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(owner, repo, issue_number) UNIQUE(owner, repo, issue_number)
@@ -273,7 +279,8 @@ func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, w
RETURNING id, owner, repo, issue_number, title, body, labels, status, RETURNING id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used, workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count, iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at`, source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at`,
owner, repo, owner, repo, syntheticIssueNumberBase-1, title, body, wf, identity) owner, repo, owner, repo, syntheticIssueNumberBase-1, title, body, wf, identity)
return scanTask(row) return scanTask(row)
} }
@@ -314,7 +321,8 @@ func (s *Store) ClaimNext(ctx context.Context) (*workflow.Task, error) {
RETURNING id, owner, repo, issue_number, title, body, labels, status, RETURNING id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used, workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count, iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at`, source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at`,
workflow.StatusRunning, workflow.StatusQueued) workflow.StatusRunning, workflow.StatusQueued)
t, err := scanTask(row) t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
@@ -330,6 +338,7 @@ func scanTask(row *sql.Row) (*workflow.Task, error) {
&t.PRNumber, &t.TokensUsed, &t.Iterations, &t.Attempt, &t.ParkReason, &t.PRNumber, &t.TokensUsed, &t.Iterations, &t.Attempt, &t.ParkReason,
&t.WatchCommentID, &t.RetryCount, &t.Source, &t.Identity, &t.WatchCommentID, &t.RetryCount, &t.Source, &t.Identity,
&t.BindingID, &t.BindingVersion, &t.ReviewPayload, &t.BindingID, &t.BindingVersion, &t.ReviewPayload,
&t.WorkflowDefinitionVersion, &t.WorkflowDefinitionDigest, &t.WorkflowDefinitionYAML,
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt}) sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt})
if err != nil { if err != nil {
return nil, err return nil, err
@@ -348,7 +357,8 @@ func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int
RETURNING id, owner, repo, issue_number, title, body, labels, status, RETURNING id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used, workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count, iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at`, source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at`,
workflow.StatusRunning, owner, repo, number, workflow.StatusQueued) workflow.StatusRunning, owner, repo, number, workflow.StatusQueued)
t, err := scanTask(row) t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
@@ -406,11 +416,13 @@ func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
_, err := s.db.ExecContext(ctx, ` _, err := s.db.ExecContext(ctx, `
UPDATE tasks SET workflow=?, stage=?, branch=?, plan=?, notes=?, UPDATE tasks SET workflow=?, stage=?, branch=?, plan=?, notes=?,
pr_number=?, tokens_used=?, iterations=?, park_reason=?, pr_number=?, tokens_used=?, iterations=?, park_reason=?,
watch_comment_id=?, retry_count=?, review_payload=?, updated_at=datetime('now') watch_comment_id=?, retry_count=?, review_payload=?, workflow_definition_version=?,
workflow_definition_digest=?, workflow_definition_yaml=?, updated_at=datetime('now')
WHERE id=?`, WHERE id=?`,
t.Workflow, t.Stage, t.Branch, t.Plan, t.Notes, t.Workflow, t.Stage, t.Branch, t.Plan, t.Notes,
t.PRNumber, t.TokensUsed, t.Iterations, clip(t.ParkReason, 4000), t.PRNumber, t.TokensUsed, t.Iterations, clip(t.ParkReason, 4000),
t.WatchCommentID, t.RetryCount, t.ReviewPayload, t.ID) t.WatchCommentID, t.RetryCount, t.ReviewPayload, t.WorkflowDefinitionVersion,
t.WorkflowDefinitionDigest, t.WorkflowDefinitionYAML, t.ID)
return err return err
} }
@@ -420,7 +432,8 @@ func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int)
SELECT id, owner, repo, issue_number, title, body, labels, status, SELECT id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used, workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count, iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
FROM tasks WHERE owner=? AND repo=? AND issue_number=?`, owner, repo, number) FROM tasks WHERE owner=? AND repo=? AND issue_number=?`, owner, repo, number)
t, err := scanTask(row) t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
@@ -435,7 +448,8 @@ func (s *Store) OpenTaskByPR(ctx context.Context, owner, repo string, number int
SELECT id, owner, repo, issue_number, title, body, labels, status, SELECT id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used, workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count, iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
FROM tasks FROM tasks
WHERE owner=? AND repo=? AND pr_number=? AND status=?`, WHERE owner=? AND repo=? AND pr_number=? AND status=?`,
owner, repo, number, workflow.StatusPROpen) owner, repo, number, workflow.StatusPROpen)
@@ -454,7 +468,8 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err
SELECT id, owner, repo, issue_number, title, body, labels, status, SELECT id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used, workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count, iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at source, identity, binding_id, binding_version, review_payload,
workflow_definition_version, workflow_definition_digest, workflow_definition_yaml, created_at, updated_at
FROM tasks WHERE id=?`, taskID) FROM tasks WHERE id=?`, taskID)
t, err := scanTask(row) t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
+5
View File
@@ -41,6 +41,8 @@ type Request struct {
// daemon to publish this task's already-prepared branch. Repository // daemon to publish this task's already-prepared branch. Repository
// coordinates never cross back from the sandbox as authority. // coordinates never cross back from the sandbox as authority.
WorktreeGrant string `json:"worktree_grant,omitempty"` WorktreeGrant string `json:"worktree_grant,omitempty"`
// WorkflowDefinition is the exact YAML pinned on Task before dispatch.
WorkflowDefinition string `json:"workflow_definition"`
} }
// Validate rejects a full-task request that cannot be correlated to a real // Validate rejects a full-task request that cannot be correlated to a real
@@ -55,6 +57,9 @@ func (r Request) Validate() error {
if r.WorktreeGrant == "" { if r.WorktreeGrant == "" {
return errors.New("worktree grant is required") return errors.New("worktree grant is required")
} }
if r.WorkflowDefinition == "" {
return errors.New("workflow definition is required")
}
return nil return nil
} }
+1 -1
View File
@@ -65,7 +65,7 @@ func TestRequestValidateRequiresPositiveTaskID(t *testing.T) {
{name: "zero ID", request: Request{Task: &workflow.Task{}}, wantErr: true}, {name: "zero ID", request: Request{Task: &workflow.Task{}}, wantErr: true},
{name: "negative ID", request: Request{Task: &workflow.Task{ID: -1}}, wantErr: true}, {name: "negative ID", request: Request{Task: &workflow.Task{ID: -1}}, wantErr: true},
{name: "missing worktree grant", request: Request{Task: &workflow.Task{ID: 1}}, wantErr: true}, {name: "missing worktree grant", request: Request{Task: &workflow.Task{ID: 1}}, wantErr: true},
{name: "valid request", request: Request{Task: &workflow.Task{ID: 1}, WorktreeGrant: "grant"}}, {name: "valid request", request: Request{Task: &workflow.Task{ID: 1}, WorktreeGrant: "grant", WorkflowDefinition: "id: test\nsteps: []\n"}},
} { } {
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
err := test.request.Validate() err := test.request.Validate()
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more