feat(gateway): load SOUL into the chat prompt per turn

SOUL now owns the prompt identity slot via a per-turn source: a stored soul
resource wins once saved, otherwise the identity's SOUL file, then the
shipped default. The gateway watches the resource so a dashboard edit
reaches the next turn without a restart; a file read error degrades to the
default and logs once.

The persona prompt plumbing is replaced by the SOUL source; the persona
surface itself (registry, wire, page, commands) stays for archie-core-7ftt.
This commit is contained in:
sam committed 2026-10-05 17:14:20 +11:00
1 parent ee2c9cda97
commit 199f409275
17 files changed
+376 -81

No files matched your search

+2 -2
View File
@@ -41,7 +41,7 @@ type chatSetup struct {
LLM func() *runtime.Runtime
ChatModels gateway.ModelManager
ToolReg *tools.Registry
Personas *gateway.PersonaRegistry
Soul gateway.SoulSource
ChatTasks gateway.TaskCreator
ChatTaskLister gateway.ChatTaskLister
ChatTaskLogs gateway.ChatTaskLogReader
@@ -141,7 +141,7 @@ func newChatTurnRunner(
Router: router,
Sessions: sessionStore,
Models: s.ChatModels,
Personas: s.Personas,
Soul: s.Soul,
Model: newChatTurnModel(s.LLM, s.ToolReg, cfg.Chat.MaxSteps, s.ToolLimits, s.ProviderOutcomes),
TaskLister: s.ChatTaskLister,
Tasks: s.ChatTasks,
+40 -1
View File
@@ -51,6 +51,19 @@ func (b *server) setupChatRuntime(ctx context.Context, cfg config.Config, actor
}
}
// ── SOUL ─────────────────────────────────────────────────────────
if b.soul == nil {
soul, version, err := b.controlPlane.Soul(ctx)
if err != nil {
return fmt.Errorf("load soul: %w", err)
}
b.soul = newSoulSource(b.cfgPath, b.log)
b.applySoul(soul, version)
if err := b.watchSoul(ctx, version); err != nil {
return fmt.Errorf("watch soul: %w", err)
}
}
// ── Operator health surface ──────────────────────────────────────
// Built before the gateways because every turn runner and router built
// later carries both: the recorder is written by sendChatTurn, the source
@@ -120,6 +133,32 @@ func (b *server) applyPersonas(collection agent.PersonaCollection, version int64
b.log.Info("personas applied", "version", version)
}
// watchSoul keeps the soul stream established for the life of the process, so
// a dashboard edit reaches the next turn without a restart.
func (b *server) watchSoul(ctx context.Context, version int64) error {
updates, err := b.controlPlane.WatchSoul(ctx, version)
if err != nil {
return err
}
go servicekit.KeepWatch(ctx, b.log, controlplane.SoulKind, version, updates,
b.controlPlane.WatchSoul,
servicekit.WaitFor,
func(update controlplane.AppliedSoul) int64 { return update.Version },
func(update controlplane.AppliedSoul) {
if update.Err != nil {
b.log.Error("soul watch failed", "err", update.Err)
return
}
b.applySoul(update.Soul, update.Version)
})
return nil
}
func (b *server) applySoul(soul agent.Soul, version int64) {
b.soul.apply(soul.Text)
b.log.Info("soul applied", "version", version)
}
// setupGatewayChat is the sole production constructor of the local contract.
// Frontends use its gRPC representation; only this service owns the router.
func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskActor) (gateway.ChatContract, error) {
@@ -143,7 +182,7 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct
Cfg: config.NewHolder(cfg),
ToolLimits: func() modelloop.ToolLimits { return toolLimits(b.cfgHolder.Get()) },
LLM: b.chatLLM, ChatModels: b.chatModels, ToolReg: b.toolReg,
Personas: b.personas, ChatTasks: b.chatTasks,
Soul: b.soul, ChatTasks: b.chatTasks,
ChatTaskLister: chatTaskListerAdapter{tasks: b.stateStore.Tasks},
ChatTaskLogs: chatTaskLogReaderAdapter{tasks: b.stateStore.TaskByID, taskLogs: b.taskLogs},
ChatTaskActor: actor,
+3
View File
@@ -58,6 +58,7 @@ type Options struct {
type server struct {
cfg config.Config
cfgHolder *config.Holder
cfgPath string
log *slog.Logger
taskLogs *logging.TaskRegistry
@@ -82,6 +83,7 @@ type server struct {
mcpApplied map[string]appliedMCPServer
chatModels *chatModelManager
personas *gateway.PersonaRegistry
soul *soulSource
memEngines *domainmemory.Registry
curatorRegistry *curator.Registry
curatorRuntime *curator.Runtime
@@ -157,6 +159,7 @@ func (b *server) loadConfig(cfgPath, overlayPath string) error {
return err
}
b.cfg = doc.Config
b.cfgPath = cfgPath
b.catalog = modelcatalog.NewCatalog(cfgPath)
b.cfgHolder = config.NewHolder(b.cfg)
logs := servicekit.Logging(b.cfg, "gateway")
+80
View File
@@ -0,0 +1,80 @@
package archiegateway
import (
"log/slog"
"strings"
"sync"
"github.com/samcharles93/archie-core/internal/domain/agent"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
// soulSource resolves the SOUL text a chat turn renders. A stored SOUL owns
// identity once saved; until then the identity's file supplies it, and the
// shipped default is the fallback. It never fails a turn: a read error is
// logged once per failure episode and degrades to the default.
type soulSource struct {
path string
log *slog.Logger
mu sync.RWMutex
owned string
failing bool
}
func newSoulSource(configPath string, log *slog.Logger) *soulSource {
if configPath == "" {
configPath = configuration.DefaultConfigPath()
}
return &soulSource{path: configPath, log: log}
}
// apply stores the text the control plane's soul resource last carried. Empty
// text leaves the SOUL unowned, so the file and default still apply.
func (s *soulSource) apply(owned string) {
s.mu.Lock()
s.owned = owned
s.mu.Unlock()
}
// Soul returns the effective SOUL text for the next turn.
func (s *soulSource) Soul() string {
s.mu.RLock()
owned := s.owned
s.mu.RUnlock()
if strings.TrimSpace(owned) != "" {
return owned
}
text, err := configuration.ReadSoul(s.path)
switch {
case err != nil:
s.fail("soul file unreadable; using the shipped default", err)
case strings.TrimSpace(text) == "":
// No file content: fall through to the shipped default.
default:
if err := (agent.Soul{Text: text}).Validate(); err != nil {
s.fail("soul file invalid; using the shipped default", err)
break
}
s.recover()
return text
}
return agent.ShippedSoul()
}
// fail logs the first failure of an episode; repeats stay quiet until recover.
func (s *soulSource) fail(msg string, err error) {
s.mu.Lock()
first := !s.failing
s.failing = true
s.mu.Unlock()
if first && s.log != nil {
s.log.Warn(msg, "err", err)
}
}
func (s *soulSource) recover() {
s.mu.Lock()
s.failing = false
s.mu.Unlock()
}
+28
View File
@@ -168,6 +168,34 @@ func (c *Client) WatchPersonas(ctx context.Context, afterVersion int64) (<-chan
func(err error) AppliedPersonas { return AppliedPersonas{Err: err} }), nil
}
func (c *Client) Soul(ctx context.Context) (agent.Soul, int64, error) {
response, err := c.rpc.Query(ctx, &pb.QueryRequest{Kind: SoulKind})
if err != nil {
return agent.Soul{}, 0, controlplanerpc.ClientError(err)
}
soul, err := decodeSoul(response.Resource.ValueJson)
return soul, response.Resource.Version, err
}
type AppliedSoul struct {
Soul agent.Soul
Version int64
Err error
}
func (c *Client) WatchSoul(ctx context.Context, afterVersion int64) (<-chan AppliedSoul, error) {
stream, err := c.rpc.Watch(ctx, &pb.WatchRequest{Kind: SoulKind, AfterVersion: afterVersion})
if err != nil {
return nil, controlplanerpc.ClientError(err)
}
return watchUpdates(ctx, stream,
func(resource *pb.Resource) AppliedSoul {
soul, err := decodeSoul(resource.ValueJson)
return AppliedSoul{Soul: soul, Version: resource.Version, Err: err}
},
func(err error) AppliedSoul { return AppliedSoul{Err: err} }), nil
}
// watchUpdates turns one Watch stream into the channel a watch loop reads: every
// document the stream carries, decoded, and then a single update carrying the
// error that ended it -- unless the stream ended cleanly or the context did, in
+1 -1
View File
@@ -8,7 +8,7 @@ import (
// Schemas are not declared here: each Definition names its document type, and
// Definition.Descriptor derives the JSON Schema from it (internal/app/controlplane/schema.go).
func builtinDefinitions(steps workflow.StepRegistry, settings map[string]any) []Definition {
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps, settings), workflowEnablementDefinition(), personaDefinition(), scheduleDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), reviewSettingsDefinition()}
definitions := []Definition{workflowDefinition(), workflowDefinitionsDefinition(steps, settings), workflowEnablementDefinition(), personaDefinition(), soulDefinition(), scheduleDefinition(), agentProfileDefinition(), playbooksDefinition(), skillsDefinition(), credentialBindingsDefinition(), identityGrantsDefinition(), reviewSettingsDefinition()}
definitions = append(definitions, modelDefinitions()...)
definitions = append(definitions, operationalDefinitions()...)
return definitions
+32
View File
@@ -0,0 +1,32 @@
package controlplane
import (
"encoding/json"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/agent"
)
// SoulKind is the control-plane resource holding the agent's SOUL document.
const SoulKind = "soul"
func soulDefinition() Definition {
return Definition{
Kind: SoulKind,
Title: "SOUL",
Document: agent.Soul{},
ApplyMode: "live",
// Seeded empty. An unowned SOUL reads the identity's file and then the
// shipped default; the first dashboard save takes ownership.
Seed: func(config.Config) any { return agent.Soul{} },
Validate: func(input []byte) error {
return validateAs(input, func(s agent.Soul) error { return s.Validate() })
},
}
}
func decodeSoul(input []byte) (agent.Soul, error) {
var soul agent.Soul
err := json.Unmarshal(input, &soul)
return soul, err
}
+23 -1
View File
@@ -1,6 +1,28 @@
package agent
import "strings"
import (
"fmt"
"strings"
)
// MaxSoulBytes bounds a SOUL document. Its body renders into the prompt ahead
// of the rules, so an oversized one cannot crowd them out.
const MaxSoulBytes = 8 << 10
// Soul is the control-plane document holding an identity's SOUL text. Empty
// Text means no stored SOUL: the loader falls back to the identity's file and
// then the shipped default, and the first save takes ownership.
type Soul struct {
Text string `json:"text"`
}
// Validate bounds the SOUL document's size. Empty is valid: it means unowned.
func (s Soul) Validate() error {
if len(s.Text) > MaxSoulBytes {
return fmt.Errorf("soul: %d bytes exceeds the %d-byte limit", len(s.Text), MaxSoulBytes)
}
return nil
}
// DefaultSoul is the starter SOUL document: the agent's identity prose in the
// system prompt.
+3 -3
View File
@@ -31,8 +31,8 @@ type RepoEnv struct {
// SystemPromptConfig holds the inputs for one rendered system prompt.
type SystemPromptConfig struct {
// Persona is the active persona prompt.
Persona string
// Soul is the agent's SOUL identity text, rendered into the <soul> block.
Soul string
// Tools is the complete set of tools available for this turn.
Tools []ToolSummary
// Channel names the communication channel.
@@ -95,7 +95,7 @@ func BuildSystemPrompt(cfg SystemPromptConfig) string {
}
}
data := promptData{
Persona: cfg.Persona,
Soul: cfg.Soul,
Tools: tools,
Channel: cfg.Channel,
Model: cfg.Model,
+1 -1
View File
@@ -1,4 +1,4 @@
{{- with .Persona}}<soul purpose="identity_and_style" trust="data">
{{- with .Soul}}<soul purpose="identity_and_style" trust="data">
{{xml .}}
</soul>
+11 -9
View File
@@ -58,9 +58,9 @@ type TurnModelRequest struct {
MaxOutputTokens int
}
// PersonaPromptSource supplies the active persona prompt for a session.
type PersonaPromptSource interface {
GetActive(sessionID string) string
// SoulSource supplies the SOUL identity text a turn renders into its prompt.
type SoulSource interface {
Soul() string
}
// TurnEventPublisher receives completed primary chat-turn events.
@@ -87,8 +87,10 @@ type TurnRunnerConfig struct {
Router *Router
Sessions SessionStore
Models ModelManager
Personas PersonaPromptSource
Model TurnModel
// Soul supplies the identity text the system prompt renders. Nil renders
// no <soul> block.
Soul SoulSource
Model TurnModel
// Transcriber replaces an inbound voice attachment's note with its
// transcript. Nil keeps the note.
Transcriber messaging.Transcriber
@@ -324,13 +326,13 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, in Inbou
if prepared == nil {
return preparedTurn{}, fmt.Errorf("build chat model: empty preparation")
}
persona := ""
if r.Personas != nil {
persona = r.Personas.GetActive(sessionID)
soul := ""
if r.Soul != nil {
soul = r.Soul.Soul()
}
memoryBlock := renderMemory(ctx, r.MemoryEngine, subject, r.Log)
systemPrompt := BuildSystemPrompt(SystemPromptConfig{
Persona: persona,
Soul: soul,
Tools: prepared.ToolSummaries(),
Channel: r.Channel,
Model: modelName,
@@ -52,6 +52,24 @@ func SoulPath(configPath string) string {
return filepath.Join(ConfigDir(configPath), SoulFilename)
}
// ReadSoul reads the identity's SOUL file for a selected config path, bounded
// before decoding so an oversized file cannot crowd the prompt. A missing file
// returns "" and no error: the caller falls back to the shipped default.
func ReadSoul(configPath string) (string, error) {
path := SoulPath(configPath)
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return "", nil
}
if err != nil {
return "", fmt.Errorf("soul: read %s: %w", path, err)
}
if len(data) > maxSoulReadBytes {
return "", fmt.Errorf("soul: %s exceeds %d bytes", path, maxSoulReadBytes)
}
return string(data), nil
}
// SeedSoul writes the starter SOUL file when none exists. It never
// overwrites an existing file.
func SeedSoul(configPath, shipped string) (SoulSeedResult, error) {