Preserve manager skill bootstrap work
This commit is contained in:
@@ -24,6 +24,9 @@ func main() {
|
||||
if len(args) == 2 && args[1] == "install" {
|
||||
var dir string
|
||||
dir, err = author.InstallSkill()
|
||||
if err == nil {
|
||||
_, err = author.InstallManagerSkill()
|
||||
}
|
||||
if err == nil {
|
||||
fmt.Println("Installed skill:", dir)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Manager-skill bootstrap — 2026-10-18
|
||||
|
||||
New app-created operator chats explicitly activate the packaged `pipelines-manager` OpenCode skill before the session is recorded or returned. Existing/adopted sessions and pipeline-owned sessions are not bootstrapped. `internal/author/skill/SKILL.md` is intentionally unchanged because it is the separate author skill.
|
||||
|
||||
After landing, the operator must run `pipelines skill install` to install/update both packaged skills, then restart or reload the deployed Pipelines server and OpenCode service at the operator's normal deployment boundary. No manager chat is live until those steps are complete. Installation refuses an unmanaged or user-modified `pipelines-manager` skill; preserve or rename that skill before retrying. The server uses the configured authenticated OpenCode V2 endpoint and `POST /api/experimental/session/{sessionID}/skill` with `resume:false`; a missing skill or activation failure is returned explicitly from chat creation.
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"git.a-wan.net/alan/pipelines/internal/harness"
|
||||
)
|
||||
|
||||
//go:embed skill/SKILL.md skill/references/*.md
|
||||
//go:embed skill/SKILL.md skill/references/*.md manager/SKILL.md
|
||||
var content embed.FS
|
||||
|
||||
// Command launches the normal CLI directly. Skill loading and questions belong
|
||||
|
||||
@@ -163,3 +163,60 @@ func TestSkillUpgradeAddsSelfContainedNotificationReference(t *testing.T) {
|
||||
t.Fatal("user notes lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerSkillInstallsWithoutReplacingUnmanagedSkill(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
dir, err := InstallManagerSkill()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = InstallManagerSkill(); err != nil {
|
||||
t.Fatal("repeat manager install", err)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Join(dir, "SKILL.md"))
|
||||
if err != nil || !strings.Contains(string(data), "name: pipelines-manager") {
|
||||
t.Fatalf("manager skill = %q, %v", data, err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("operator customization"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := InstallManagerSkill(); err == nil {
|
||||
t.Fatal("overwrote modified manager skill")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerSkillInstallRefusesUnmanagedExistingSkill(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
dir, err := ManagerSkillDirectory()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
if err := os.WriteFile(path, []byte("operator skill"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := InstallManagerSkill(); err == nil {
|
||||
t.Fatal("replaced unmanaged manager skill")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerSkillInstallRestoresMissingManagedFile(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
dir, err := InstallManagerSkill()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "SKILL.md")
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := InstallManagerSkill(); err != nil {
|
||||
t.Fatal("restore manager skill", err)
|
||||
}
|
||||
if data, err := os.ReadFile(path); err != nil || !strings.Contains(string(data), "name: pipelines-manager") {
|
||||
t.Fatalf("restored manager skill = %q, %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,3 +143,82 @@ func writeSkillFile(path string, data []byte) error {
|
||||
}
|
||||
return os.Rename(f.Name(), path)
|
||||
}
|
||||
|
||||
// ManagerSkillDirectory is the source-controlled Pipelines manager skill location.
|
||||
func ManagerSkillDirectory() (string, error) {
|
||||
dir := os.Getenv("XDG_CONFIG_HOME")
|
||||
if dir == "" {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
dir = filepath.Join(home, ".config")
|
||||
}
|
||||
return filepath.Abs(filepath.Join(dir, "opencode", "skills", "pipelines-manager"))
|
||||
}
|
||||
|
||||
// InstallManagerSkill installs only the dedicated manager skill. It refuses an
|
||||
// unmanaged or modified same-name skill and uses the same ownership marker and
|
||||
// atomic write protection as InstallSkill.
|
||||
func InstallManagerSkill() (string, error) {
|
||||
dir, err := ManagerSkillDirectory()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
marker := filepath.Join(dir, ".pipelines-managed.json")
|
||||
if info, statErr := os.Lstat(marker); statErr == nil && !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("refusing non-regular manager skill ownership marker %s", marker)
|
||||
} else if statErr != nil && !os.IsNotExist(statErr) {
|
||||
return "", statErr
|
||||
}
|
||||
previous := map[string]string{}
|
||||
if data, readErr := os.ReadFile(marker); readErr == nil {
|
||||
if err := json.Unmarshal(data, &previous); err != nil {
|
||||
return "", fmt.Errorf("invalid manager skill ownership marker: %w", err)
|
||||
}
|
||||
} else if !os.IsNotExist(readErr) {
|
||||
return "", readErr
|
||||
}
|
||||
data, err := content.ReadFile("manager/SKILL.md")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
const file = "SKILL.md"
|
||||
next := digest(data)
|
||||
path := filepath.Join(dir, file)
|
||||
if info, statErr := os.Lstat(path); statErr == nil {
|
||||
if !info.Mode().IsRegular() {
|
||||
return "", fmt.Errorf("refusing to replace non-regular manager skill file %s", path)
|
||||
}
|
||||
existing, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if previous[file] == "" || (digest(existing) != previous[file] && digest(existing) != next) {
|
||||
return "", fmt.Errorf("manager skill file %s is user-managed or modified; preserve/rename it before installing the Pipelines manager skill", path)
|
||||
}
|
||||
} else if !os.IsNotExist(statErr) {
|
||||
return "", statErr
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// A managed file may have been deleted after the marker was written. The
|
||||
// marker proves ownership, but not that the target still exists; recreate a
|
||||
// missing file before leaving the marker unchanged.
|
||||
if previous[file] != next || !regularFile(path) {
|
||||
if err := writeSkillFile(path, data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
markerData, _ := json.MarshalIndent(map[string]string{file: next}, "", " ")
|
||||
if err := writeSkillFile(marker, markerData); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
func regularFile(path string) bool {
|
||||
info, err := os.Stat(path)
|
||||
return err == nil && info.Mode().IsRegular()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
---
|
||||
name: pipelines-manager
|
||||
description: Manage project work through Pipelines: clarify operator intent, route actionable work to the appropriate pipeline, monitor runs, and unblock evidence-based failures without acting as an additional developer or reviewer.
|
||||
---
|
||||
|
||||
# Pipelines manager
|
||||
|
||||
Clarify scope, consent and constraints with the operator. Inspect only enough project map, queue and history to write actionable tasks; prompts state the goal, acceptance checks and constraints, not an invented implementation. Work from a branch/worktree and select the pipeline by area.
|
||||
|
||||
Pipelines own implementation, testing, review, conflict resolution and landing. The manager assigns, monitors with `pipelines wait <ids>`, reconciles completion and unblocks exact evidenced failures; it does not hand-edit projects, rewrite deliverables, or add a second acceptance/review gate. For Pipelines itself, use observed failures to improve the product through its pipelines, never workaround scripts.
|
||||
|
||||
Keep durable queue records as intent; the server is run-state authority. Start independent work in bounded parallelism only where edits, provider capacity, machine pressure and capture resources permit. Hardware waits pause in the runner. Do not create polling loops, lane/queue drivers, sleeping model stages, or claim undeployed queue/timer support.
|
||||
|
||||
Preserve partial work and sessions on failure. Diagnose the failed operation from evidence; a timeout is not proof of a lost message. Do not blindly replay a whole implementer stage or raise limits to hide defects. Before cleanup require ancestry proof; never delete branches or discard unknown changes. Report failures and decisions briefly, not routine green completion. Do not install, deploy or restart while work is in flight; obtain explicit operator approval for system changes.
|
||||
|
||||
Use the configured strong manager model for operator chats. Developer pipeline model choices remain distinct and configurable; do not hardcode catalog IDs, pricing or temporary endpoints here. Keep project-specific commands and policy in project maps.
|
||||
@@ -139,6 +139,20 @@ func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) {
|
||||
// It deliberately sends no model or permission override here: the endpoint's own
|
||||
// defaults apply, exactly as the live check creates a session. The created
|
||||
// session is returned with its directory lifted from location.directory.
|
||||
// ActivateSkill uses the V2 experimental session skill endpoint. resume=false
|
||||
// records the skill without starting an artificial turn; the first operator prompt
|
||||
// is therefore the first model turn and receives the manager instructions.
|
||||
func (c *Chat) ActivateSkill(ctx context.Context, id, skill string) error {
|
||||
if !sessionID.MatchString(id) {
|
||||
return fmt.Errorf("invalid OpenCode session id")
|
||||
}
|
||||
if strings.TrimSpace(skill) == "" {
|
||||
return fmt.Errorf("empty OpenCode skill id")
|
||||
}
|
||||
_, err := c.call(ctx, "post", "/api/experimental/session/"+id+"/skill", map[string]any{"id": skill, "resume": false})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
body := struct {
|
||||
Title string `json:"title"`
|
||||
|
||||
@@ -395,3 +395,21 @@ func TestOpenChatRejectsUnrunnableCLI(t *testing.T) {
|
||||
t.Fatal("a missing CLI must fail detection, not open an endpoint")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatActivateSkillV2Shape(t *testing.T) {
|
||||
var path, body string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
data := make([]byte, r.ContentLength)
|
||||
_, _ = r.Body.Read(data)
|
||||
body = string(data)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer srv.Close()
|
||||
if err := NewChat(&Connection{Backend: "v2", URL: srv.URL}).ActivateSkill(context.Background(), "ses_1", "pipelines-manager"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if path != "/api/experimental/session/ses_1/skill" || body != `{"id":"pipelines-manager","resume":false}` {
|
||||
t.Fatalf("activate request = %s %s", path, body)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,17 @@ type OperatorSession struct {
|
||||
ClosedAt int64
|
||||
}
|
||||
|
||||
// ChatCreateBootstrap is the durable progress record for one chat_create
|
||||
// request. It lets a retried request resume after endpoint activation or a
|
||||
// registry write failed, without creating or activating another session.
|
||||
type ChatCreateBootstrap struct {
|
||||
RequestID string
|
||||
SessionID string
|
||||
Title string
|
||||
Directory string
|
||||
State string
|
||||
}
|
||||
|
||||
// initOperatorSessions creates the operator-session registry. It is a table of
|
||||
// its own rather than a kind column on run_steps so a pipeline run's session
|
||||
// ownership (run_session_owners, SessionOwner) is untouched and the two
|
||||
@@ -45,12 +56,49 @@ session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAUL
|
||||
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL,
|
||||
closed_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_create_bootstraps (
|
||||
request_id TEXT PRIMARY KEY, session_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL,
|
||||
directory TEXT NOT NULL, state TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateOperatorSessions()
|
||||
}
|
||||
|
||||
// BeginChatCreate reserves a request id or returns its prior progress. The
|
||||
// request id is the client retry key and is never reused for different input.
|
||||
func (s *Store) BeginChatCreate(ctx context.Context, requestID, title, directory string) (ChatCreateBootstrap, error) {
|
||||
now := time.Now().UnixMilli()
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_create_bootstraps(request_id,title,directory,state,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?) ON CONFLICT(request_id) DO NOTHING`, requestID, title, directory, "created", now, now)
|
||||
if err != nil {
|
||||
return ChatCreateBootstrap{}, err
|
||||
}
|
||||
var b ChatCreateBootstrap
|
||||
err = s.db.QueryRowContext(ctx, `SELECT request_id,session_id,title,directory,state FROM chat_create_bootstraps WHERE request_id=?`, requestID).
|
||||
Scan(&b.RequestID, &b.SessionID, &b.Title, &b.Directory, &b.State)
|
||||
if err != nil {
|
||||
return ChatCreateBootstrap{}, err
|
||||
}
|
||||
if b.Title != title || b.Directory != directory {
|
||||
return ChatCreateBootstrap{}, errors.New("chat_create request id was reused with different input")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (s *Store) SetChatCreateSession(ctx context.Context, requestID, sessionID string) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE chat_create_bootstraps SET session_id=?,updated_at=? WHERE request_id=? AND session_id=''`, sessionID, time.Now().UnixMilli(), requestID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, state string) error {
|
||||
_, err := s.db.ExecContext(ctx, `UPDATE chat_create_bootstraps SET state=?,updated_at=? WHERE request_id=?`, state, time.Now().UnixMilli(), requestID)
|
||||
return err
|
||||
}
|
||||
|
||||
// migrateOperatorSessions adds the closed_at column to a database created before
|
||||
// the closed state existed. Adding a column with a default leaves every existing
|
||||
// row valid and open (0), so an upgrade is idempotent across repeated Open calls
|
||||
|
||||
@@ -25,6 +25,8 @@ type chatBroker interface {
|
||||
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
|
||||
// Create creates one OpenCode session in the given directory and returns it.
|
||||
Create(ctx context.Context, title, directory string) (protocol.ChatSession, error)
|
||||
// ActivateSkill explicitly attaches a registered OpenCode skill before a chat can receive its first prompt.
|
||||
ActivateSkill(ctx context.Context, sessionID, skill string) error
|
||||
// Session returns the endpoint's own record of one existing session so an
|
||||
// adopted session carries the endpoint's directory and title; found is false
|
||||
// when the endpoint does not list sessionID.
|
||||
@@ -40,6 +42,9 @@ type chatBroker interface {
|
||||
// ownership (SessionOwner/run_session_owners) that settles a run: chat_sessions
|
||||
// lists operator sessions only and never consults stage ownership.
|
||||
type operatorRegistry interface {
|
||||
BeginChatCreate(ctx context.Context, requestID, title, directory string) (pipeline.ChatCreateBootstrap, error)
|
||||
SetChatCreateSession(ctx context.Context, requestID, sessionID string) error
|
||||
AdvanceChatCreate(ctx context.Context, requestID, state string) error
|
||||
RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error
|
||||
TouchOperatorSession(ctx context.Context, sessionID string) error
|
||||
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
@@ -74,6 +75,14 @@ func (c *channelChat) Messages(context.Context, string, int) ([]protocol.ChatMes
|
||||
|
||||
func (c *channelChat) Sessions(context.Context) ([]protocol.ChatSession, error) { return nil, nil }
|
||||
|
||||
func (c *channelChat) BeginChatCreate(context.Context, string, string, string) (pipeline.ChatCreateBootstrap, error) {
|
||||
return pipeline.ChatCreateBootstrap{State: "created"}, nil
|
||||
}
|
||||
func (c *channelChat) SetChatCreateSession(context.Context, string, string) error { return nil }
|
||||
func (c *channelChat) AdvanceChatCreate(context.Context, string, string) error { return nil }
|
||||
|
||||
func (c *channelChat) ActivateSkill(context.Context, string, string) error { return nil }
|
||||
|
||||
func (c *channelChat) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
return protocol.ChatSession{ID: "ses_created", Title: title, Directory: directory}, nil
|
||||
}
|
||||
|
||||
@@ -37,6 +37,10 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
|
||||
_ = write(response)
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(request.ID) == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat_create requires a non-empty request id for retry-safe creation"})
|
||||
return
|
||||
}
|
||||
operatorSessions, err := registry.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
@@ -114,15 +118,54 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
session, err := broker.Create(ctx, title, resolved)
|
||||
bootstrap, err := registry.BeginChatCreate(ctx, request.ID, title, resolved)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := registry.RecordOperatorSession(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
|
||||
session := protocol.ChatSession{ID: bootstrap.SessionID, Title: title, Directory: resolved}
|
||||
if session.ID == "" {
|
||||
session, err = broker.Create(ctx, title, resolved)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := registry.SetChatCreateSession(ctx, request.ID, session.ID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but durable bootstrap state could not be saved: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
if bootstrap.State == "created" {
|
||||
// Reserve the activation before calling the external service. If the
|
||||
// process dies after the call but before the success checkpoint, a retry
|
||||
// must report the ambiguous operation rather than append the skill twice.
|
||||
if err := registry.AdvanceChatCreate(ctx, request.ID, "activating"); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " could not reserve manager bootstrap: " + err.Error()})
|
||||
return
|
||||
}
|
||||
if err := broker.ActivateSkill(ctx, session.ID, "pipelines-manager"); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but manager bootstrap failed while activating pipelines-manager: " + err.Error()})
|
||||
return
|
||||
}
|
||||
if err := registry.AdvanceChatCreate(ctx, request.ID, "activated"); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " activated but durable bootstrap state could not be saved: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
if bootstrap.State == "activating" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " has an unfinished manager bootstrap; activation will not be repeated automatically"})
|
||||
return
|
||||
}
|
||||
if bootstrap.State != "recorded" {
|
||||
if err := registry.RecordOperatorSession(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
|
||||
return
|
||||
}
|
||||
if err := registry.AdvanceChatCreate(ctx, request.ID, "recorded"); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was recorded but durable bootstrap state could not be saved: " + err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
session.Directory = resolved
|
||||
session.Tag = protocol.ChatSessionTagOperator
|
||||
response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session}
|
||||
|
||||
@@ -3,6 +3,7 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -71,6 +72,10 @@ type fakeChat struct {
|
||||
createDirectory string
|
||||
created protocol.ChatSession
|
||||
createErr error
|
||||
activateCalls int
|
||||
activateSessionID string
|
||||
activateSkill string
|
||||
activateErr error
|
||||
sessionByIDCalls int
|
||||
sessionByID string
|
||||
sessionRecord protocol.ChatSession
|
||||
@@ -78,6 +83,12 @@ type fakeChat struct {
|
||||
sessionByIDErr error
|
||||
}
|
||||
|
||||
func (f *fakeChat) BeginChatCreate(context.Context, string, string, string) (pipeline.ChatCreateBootstrap, error) {
|
||||
return pipeline.ChatCreateBootstrap{State: "created"}, nil
|
||||
}
|
||||
func (f *fakeChat) SetChatCreateSession(context.Context, string, string) error { return nil }
|
||||
func (f *fakeChat) AdvanceChatCreate(context.Context, string, string) error { return nil }
|
||||
|
||||
func (f *fakeChat) Prompt(context.Context, string, string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
@@ -196,6 +207,14 @@ func (f *fakeChat) sessionQuery() int {
|
||||
// Create records the title and directory the handler forwarded and returns the
|
||||
// seeded created session. A blank created id defaults to "ses_created" so a test
|
||||
// only asserts what it cares about.
|
||||
func (f *fakeChat) ActivateSkill(_ context.Context, sessionID, skill string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.activateCalls++
|
||||
f.activateSessionID, f.activateSkill = sessionID, skill
|
||||
return f.activateErr
|
||||
}
|
||||
|
||||
func (f *fakeChat) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
@@ -1226,6 +1245,12 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
|
||||
if calls, title, directory := broker.createQuery(); calls != 1 || title != "demo" || directory != dir {
|
||||
t.Fatalf("broker.Create = %d/%q/%q, want 1/demo/%q", calls, title, directory, dir)
|
||||
}
|
||||
broker.mu.Lock()
|
||||
activateCalls, activateSession, activateSkill := broker.activateCalls, broker.activateSessionID, broker.activateSkill
|
||||
broker.mu.Unlock()
|
||||
if activateCalls != 1 || activateSession != "ses_new" || activateSkill != "pipelines-manager" {
|
||||
t.Fatalf("manager bootstrap = %d/%q/%q", activateCalls, activateSession, activateSkill)
|
||||
}
|
||||
recorded, err := store.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -1235,6 +1260,42 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCreateReportsManagerBootstrapFailure(t *testing.T) {
|
||||
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")}
|
||||
store := newOperatorStore(t)
|
||||
request := protocol.Message{ID: "create", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{}}
|
||||
var response protocol.Message
|
||||
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error {
|
||||
response = message
|
||||
return nil
|
||||
})
|
||||
if response.Type != protocol.Error || !strings.Contains(response.Error, "manager bootstrap failed") || !strings.Contains(response.Error, "skill not found") {
|
||||
t.Fatalf("response = %#v", response)
|
||||
}
|
||||
if _, err := store.OperatorSessions(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCreateRetryReusesDurableBootstrap(t *testing.T) {
|
||||
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_once"}}
|
||||
store := newOperatorStore(t)
|
||||
request := protocol.Message{ID: "create-once", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "demo"}}
|
||||
for i := 0; i < 2; i++ {
|
||||
var response protocol.Message
|
||||
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error { response = message; return nil })
|
||||
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.ID != "ses_once" {
|
||||
t.Fatalf("retry %d response = %#v", i, response)
|
||||
}
|
||||
}
|
||||
broker.mu.Lock()
|
||||
creates, activations := broker.createCalls, broker.activateCalls
|
||||
broker.mu.Unlock()
|
||||
if creates != 1 || activations != 1 {
|
||||
t.Fatalf("retry repeated external work: creates=%d activations=%d", creates, activations)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCreateDirectoryResolution pins directory defaulting and rejection: an
|
||||
// omitted/empty/"~"/"~/..." directory resolves to the operator's home (never the
|
||||
// server's working directory), an explicit existing directory is recorded
|
||||
|
||||
Reference in New Issue
Block a user