feat(instructions): layer instance, organisation, workflow and repository instructions into every agent stage

This commit is contained in:
sam committed 2026-10-17 23:42:39 +11:00
1 parent 3ec7a60aa9
commit a6eb136f66
26 files changed
+1021 -662

No files matched your search

@@ -258,6 +258,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
Log: log,
Guardrails: dependencies.guardrails,
}
tc.Instructions = req.Instructions
configureTaskContext(tc, workDir)
if req.Repo.PersistentStorage {
+5 -2
View File
@@ -98,8 +98,9 @@ type boot struct {
// dialed to the standalone archie-state-store gRPC service at
// [services.state].target. It is set by openStateStoreAdapter, which
// requires [services.state].target to be set.
stateStore storecontract.TaskStore
taskModels daemon.TaskModels
stateStore storecontract.TaskStore
taskModels daemon.TaskModels
taskInstructions daemon.TaskInstructions
// accessChain is the daemon's policy engine, built once from the stored
// policies (openAccessChain); accessProblems is what the readiness
// surface reports. Both are nil when no policy store is wired.
@@ -300,6 +301,7 @@ func (b *boot) openStateStoreAdapter(ctx context.Context) error {
b.credentialWatch = &credentialWatch{reporter: alert.Reporter{Raiser: alerts, Log: b.log, By: "archied"}}
}
b.taskModels = client
b.taskInstructions = client
b.controlPlaneRPC = client.ControlPlane()
b.controlPlane = controlplane.NewRPCClient(b.controlPlaneRPC)
b.applyStatus = applystatus.New(b.processName, client, b.log)
@@ -593,6 +595,7 @@ func (b *boot) buildDaemon() {
KitLauncher: b.kitLauncher,
ModelEgress: b.modelEgress,
TaskModels: b.taskModels,
TaskInstructions: b.taskInstructions,
IssueSources: b.issueSources,
OrgPrincipals: b.orgPrincipals,
RootIdentityID: identity.StableID(servicekit.IdentityNames(b.cfg)[0]),
+25
View File
@@ -0,0 +1,25 @@
package controlplane
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// InstructionsFor returns the system org's instructions and orgID's own.
// A system-org caller has no separate organisation layer.
func (s *Server) InstructionsFor(ctx context.Context, orgID string) (instance, organisation string, err error) {
var system agent.Soul
if err := s.readResource(ctx, storecontract.DefaultOrgID, SoulKind, &system); err != nil {
return "", "", err
}
if orgID == "" || orgID == storecontract.DefaultOrgID {
return system.Text, "", nil
}
var own agent.Soul
if err := s.readResource(ctx, orgID, SoulKind, &own); err != nil {
return "", "", err
}
return system.Text, own.Text, nil
}
+1 -1
View File
@@ -13,7 +13,7 @@ const SoulKind = "soul"
func soulDefinition() Definition {
return Definition{
Kind: SoulKind,
Title: "SOUL",
Title: "Instructions",
Document: agent.Soul{},
ApplyMode: "live",
// Seeded empty. An unowned SOUL reads the identity's file and then the
+1
View File
@@ -552,4 +552,5 @@ func controlPlaneDeps(deps *staterpc.Deps, control *controlplane.Server) {
models, err := control.ModelsFor(ctx, orgID)
return models.Aliases, models.Providers, err
}
deps.OrgInstructions = control.InstructionsFor
}
+3
View File
@@ -98,6 +98,9 @@ type Repo struct {
// Connection names the ForgeConnection this repository is reached
// through. Empty is a repository the instance's root forge owns.
Connection string `toml:"connection" json:"connection" yaml:"connection"`
// Instructions are the repository's layer of the instructions every agent
// run on it follows.
Instructions string `toml:"instructions" json:"instructions,omitempty" yaml:"instructions"`
// Base is the branch PRs target. Defaults to "main".
Base string `toml:"base" json:"base" yaml:"base"`
// Gate is the repo's gate command list, e.g. [["go","vet","./..."],
File diff suppressed because it is too large. Load diff
@@ -75,6 +75,7 @@ const (
StateStoreService_StartStep_FullMethodName = "/state.v1.StateStoreService/StartStep"
StateStoreService_RecordUsage_FullMethodName = "/state.v1.StateStoreService/RecordUsage"
StateStoreService_TaskModels_FullMethodName = "/state.v1.StateStoreService/TaskModels"
StateStoreService_TaskInstructions_FullMethodName = "/state.v1.StateStoreService/TaskInstructions"
StateStoreService_CallerModels_FullMethodName = "/state.v1.StateStoreService/CallerModels"
StateStoreService_FinishStep_FullMethodName = "/state.v1.StateStoreService/FinishStep"
StateStoreService_CancelExecution_FullMethodName = "/state.v1.StateStoreService/CancelExecution"
@@ -274,6 +275,9 @@ type StateStoreServiceClient interface {
// org may use and the org's own providers. The org is the task's, never
// the caller's.
TaskModels(ctx context.Context, in *TaskModelsRequest, opts ...grpc.CallOption) (*TaskModelsResponse, error)
// TaskInstructions answers the instance and organisation instructions a
// task's agent runs follow. Organisation is empty for a system-org task.
TaskInstructions(ctx context.Context, in *TaskInstructionsRequest, opts ...grpc.CallOption) (*TaskInstructionsResponse, error)
// CallerModels answers the model aliases the caller's org may use. The org
// is the calling principal's; a call with none is the system org's.
CallerModels(ctx context.Context, in *CallerModelsRequest, opts ...grpc.CallOption) (*CallerModelsResponse, error)
@@ -1035,6 +1039,16 @@ func (c *stateStoreServiceClient) TaskModels(ctx context.Context, in *TaskModels
return out, nil
}
func (c *stateStoreServiceClient) TaskInstructions(ctx context.Context, in *TaskInstructionsRequest, opts ...grpc.CallOption) (*TaskInstructionsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(TaskInstructionsResponse)
err := c.cc.Invoke(ctx, StateStoreService_TaskInstructions_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *stateStoreServiceClient) CallerModels(ctx context.Context, in *CallerModelsRequest, opts ...grpc.CallOption) (*CallerModelsResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CallerModelsResponse)
@@ -2159,6 +2173,9 @@ type StateStoreServiceServer interface {
// org may use and the org's own providers. The org is the task's, never
// the caller's.
TaskModels(context.Context, *TaskModelsRequest) (*TaskModelsResponse, error)
// TaskInstructions answers the instance and organisation instructions a
// task's agent runs follow. Organisation is empty for a system-org task.
TaskInstructions(context.Context, *TaskInstructionsRequest) (*TaskInstructionsResponse, error)
// CallerModels answers the model aliases the caller's org may use. The org
// is the calling principal's; a call with none is the system org's.
CallerModels(context.Context, *CallerModelsRequest) (*CallerModelsResponse, error)
@@ -2528,6 +2545,9 @@ func (UnimplementedStateStoreServiceServer) RecordUsage(context.Context, *Record
func (UnimplementedStateStoreServiceServer) TaskModels(context.Context, *TaskModelsRequest) (*TaskModelsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TaskModels not implemented")
}
func (UnimplementedStateStoreServiceServer) TaskInstructions(context.Context, *TaskInstructionsRequest) (*TaskInstructionsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method TaskInstructions not implemented")
}
func (UnimplementedStateStoreServiceServer) CallerModels(context.Context, *CallerModelsRequest) (*CallerModelsResponse, error) {
return nil, status.Error(codes.Unimplemented, "method CallerModels not implemented")
}
@@ -3857,6 +3877,24 @@ func _StateStoreService_TaskModels_Handler(srv interface{}, ctx context.Context,
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_TaskInstructions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(TaskInstructionsRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(StateStoreServiceServer).TaskInstructions(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: StateStoreService_TaskInstructions_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(StateStoreServiceServer).TaskInstructions(ctx, req.(*TaskInstructionsRequest))
}
return interceptor(ctx, in, info, handler)
}
func _StateStoreService_CallerModels_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CallerModelsRequest)
if err := dec(in); err != nil {
@@ -5867,6 +5905,10 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
MethodName: "TaskModels",
Handler: _StateStoreService_TaskModels_Handler,
},
{
MethodName: "TaskInstructions",
Handler: _StateStoreService_TaskInstructions_Handler,
},
{
MethodName: "CallerModels",
Handler: _StateStoreService_CallerModels_Handler,
+12
View File
@@ -159,6 +159,9 @@ type Daemon struct {
// TaskModels answers the model aliases a task's org resolves against.
// Nil runs every task on the instance aliases.
TaskModels TaskModels
// TaskInstructions answers the instance and organisation instructions a
// task's agent runs follow. Nil runs without them.
TaskInstructions TaskInstructions
// TaskRunReadyTimeout bounds how long runViaAgent retries a taskrun request
// while the new container has not subscribed yet. Zero uses
// defaultTaskRunReadyTimeout.
@@ -1855,7 +1858,16 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
}
taskCfg := cfg.ForTask()
d.captureAttemptConfig(ctx, task, taskCfg)
var instructions workflow.Instructions
if d.TaskInstructions != nil {
instructions.Instance, instructions.Organisation, err = d.TaskInstructions.TaskInstructions(ctx, task.ID)
if err != nil {
d.parkRunningTask(ctx, task, "resolve the task's instructions: "+err.Error(), taskstate.ParkTransient)
return
}
}
req := taskrun.Request{
Instructions: instructions,
Task: task,
Repo: repo,
Cfg: taskCfg,
+6
View File
@@ -123,6 +123,12 @@ type ModelEgress interface {
Close(ctx context.Context, token string)
}
// TaskInstructions answers the instance and organisation instructions for a
// task's org.
type TaskInstructions interface {
TaskInstructions(ctx context.Context, taskID int64) (instance, organisation string, err error)
}
// TaskModels answers what a task's org resolves models against.
type TaskModels interface {
TaskModels(ctx context.Context, taskID int64) (config.OrgModels, error)
+1 -1
View File
@@ -128,7 +128,7 @@ func (a AgentStage) buildRequest(tc *TaskContext, modelRef string) (agentrun.Req
Model: modelRef,
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
Mission: missionWithInputs(tc.Task, missionWithSkill(tc, a.Mission(tc))),
ExtraRules: a.buildExtraRules(tc),
ExtraRules: tc.withInstructions(a.buildExtraRules(tc)),
ReadOnly: a.ReadOnly,
Budget: budget,
Gate: gate,
+1
View File
@@ -87,6 +87,7 @@ func runBaselineFix(ctx context.Context, tc *TaskContext, argv []string, out []b
Model: modelRef,
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
Mission: mission,
ExtraRules: tc.withInstructions(""),
Budget: agentrun.Budget{
MaxSteps: tc.Cfg.Budgets.MaxSteps,
WallClock: tc.Cfg.Budgets.WallClock.Std(),
+45
View File
@@ -0,0 +1,45 @@
package workflow
import "strings"
// Instructions are the layers resolved outside the run: the instance's, then
// the task's organisation's.
type Instructions struct {
Instance string `json:"instance,omitempty"`
Organisation string `json:"organisation,omitempty"`
}
// instructions renders every set layer, broadest first, so a narrower layer
// reads as refining the one above it.
func (tc *TaskContext) instructions() string {
layers := []struct{ name, text string }{
{"Instance", tc.Instructions.Instance},
{"Organisation", tc.Instructions.Organisation},
{"Workflow", tc.workflowInterface().Instructions},
{"Repository", tc.Repo.Instructions},
}
var b strings.Builder
for _, layer := range layers {
text := strings.TrimSpace(layer.text)
if text == "" {
continue
}
if b.Len() == 0 {
b.WriteString("## Instructions\n")
}
b.WriteString("\n### " + layer.name + "\n\n" + text + "\n")
}
return b.String()
}
// withInstructions puts the instructions ahead of a stage's own rules.
func (tc *TaskContext) withInstructions(rules string) string {
instructions := tc.instructions()
switch {
case instructions == "":
return rules
case rules == "":
return instructions
}
return instructions + "\n" + rules
}
@@ -0,0 +1,42 @@
package workflow
import (
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
func TestInstructionsLayerBroadestFirst(t *testing.T) {
tests := []struct {
name string
tc TaskContext
rules string
want string
}{
{name: "none leaves the rules", tc: TaskContext{runInterfaceSet: true}, rules: "R", want: "R"},
{
name: "every layer in order, then the rules",
tc: TaskContext{
Instructions: Instructions{Instance: "I", Organisation: "O"},
Repo: config.Repo{Instructions: "P"},
runInterface: task.WorkflowInterface{Instructions: "W"},
runInterfaceSet: true,
},
rules: "R",
want: "## Instructions\n\n### Instance\n\nI\n\n### Organisation\n\nO\n\n### Workflow\n\nW\n\n### Repository\n\nP\n\nR",
},
{
name: "blank layers are skipped",
tc: TaskContext{Instructions: Instructions{Organisation: " "}, Repo: config.Repo{Instructions: "P"}, runInterfaceSet: true},
want: "## Instructions\n\n### Repository\n\nP\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.tc.withInstructions(tt.rules); got != tt.want {
t.Errorf("got %q, want %q", got, tt.want)
}
})
}
}
+2 -2
View File
@@ -567,7 +567,7 @@ func runReviewerAgent(
Version: agentrun.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt,
Stage: name, Workflow: tc.Task.Workflow, Model: modelRef,
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
Mission: mission, ReadOnly: true,
Mission: mission, ExtraRules: tc.withInstructions(""), ReadOnly: true,
Budget: agentrun.Budget{MaxSteps: prReviewMaxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std()},
CaptureTools: captureTools,
}
@@ -755,7 +755,7 @@ func runPRReviewAgentRecorded(
Version: agentrun.ProtocolVersion, TaskID: tc.Task.ID, Attempt: tc.Task.Attempt,
Stage: name, Workflow: tc.Task.Workflow, Model: modelRef,
ContextWindow: modelContextBudget(tc.Cfg, modelRef),
Mission: mission, ReadOnly: true,
Mission: mission, ExtraRules: tc.withInstructions(""), ReadOnly: true,
Budget: agentrun.Budget{MaxSteps: maxSteps, WallClock: tc.Cfg.Budgets.WallClock.Std()},
CaptureTools: captureTools,
}
@@ -60,6 +60,9 @@ type WorkflowInterface struct {
// whatever started it. Both it and the starter need run on the workflow.
// A workflow that names none is refused when it runs.
Identity string `yaml:"identity,omitempty" json:"identity,omitempty"`
// Instructions are the workflow's layer of the instructions every agent
// stage of a run follows.
Instructions string `yaml:"instructions,omitempty" json:"instructions,omitempty"`
// DeclaredNeeds is what the definition's needs: block declares. Read
// Needs, not this, when deciding a harness requirement: a declared output
// forces the captures capability and Needs resolves it.
+4
View File
@@ -163,6 +163,10 @@ type TaskContext struct {
runInterfaceSet bool
ifaceParsed *task.WorkflowInterface
// Instructions are the instance and organisation layers; the workflow and
// repository layers come from the definition and Repo.
Instructions Instructions
// SystemPrompt, when non-nil, returns additional context to inject
// before the agent's mission in every agent stage request. Wired by
// the composition root (cmd/archied) from the MemoryManager.
@@ -155,6 +155,16 @@ func (c *Client) TaskModels(ctx context.Context, taskID int64) (config.OrgModels
return config.OrgModels{Org: r.OrgId, Aliases: r.Aliases, Providers: providers}, nil
}
// TaskInstructions returns the instance and organisation instructions for the
// task's org.
func (c *Client) TaskInstructions(ctx context.Context, taskID int64) (instance, organisation string, err error) {
r, err := c.client.TaskInstructions(ctx, &pb.TaskInstructionsRequest{TaskId: taskID})
if err != nil {
return "", "", unmapError(err)
}
return r.GetInstance(), r.GetOrganisation(), nil
}
// CallerModels returns the calling principal's org and the aliases it may
// use.
func (c *Client) CallerModels(ctx context.Context) (string, map[string]string, error) {
@@ -114,6 +114,8 @@ type Deps struct {
// OrgModels answers an org's effective model aliases and own providers.
// Optional: nil answers TaskModels with codes.Unavailable.
OrgModels func(ctx context.Context, orgID string) (map[string]string, map[string]config.Provider, error)
// OrgInstructions answers the instance instructions and orgID's own.
OrgInstructions func(ctx context.Context, orgID string) (instance, organisation string, err error)
// Canceller is the one cancel path:
// an operator action's guarded write over the execution and its steps.
// Optional: nil answers the RPC with codes.Unavailable.
@@ -323,6 +325,26 @@ func (s *server) TaskModels(ctx context.Context, r *pb.TaskModelsRequest) (*pb.T
return &pb.TaskModelsResponse{OrgId: orgID, Aliases: aliases, Providers: out}, nil
}
// TaskInstructions answers the instance and organisation instructions for the
// task's org.
func (s *server) TaskInstructions(ctx context.Context, r *pb.TaskInstructionsRequest) (*pb.TaskInstructionsResponse, error) {
if s.deps.OrgInstructions == nil {
return nil, status.Error(codes.Unavailable, "instructions unavailable")
}
t, err := s.deps.Tasks.TaskByID(ctx, r.TaskId)
if err != nil {
return nil, s.logErr("TaskInstructions", err)
}
if t == nil {
return nil, status.Error(codes.NotFound, "task not found")
}
instance, organisation, err := s.deps.OrgInstructions(ctx, t.OrgOrDefault())
if err != nil {
return nil, s.logErr("TaskInstructions", err)
}
return &pb.TaskInstructionsResponse{Instance: instance, Organisation: organisation}, nil
}
// CallerModels answers the aliases the calling principal's org may use.
func (s *server) CallerModels(ctx context.Context, _ *pb.CallerModelsRequest) (*pb.CallerModelsResponse, error) {
if s.deps.OrgModels == nil {
+3
View File
@@ -33,6 +33,9 @@ type Request struct {
// Harness, set for a Kit profile, runs every agent stage on the Kit's
// CLI instead of the built-in loop.
Harness *agentrun.HarnessSpec `json:"harness,omitempty"`
// Instructions are the instance and organisation layers every agent
// stage follows.
Instructions workflow.Instructions `json:"instructions"`
}
// Validate rejects a full-task request that cannot be correlated to a real