Merge branch 'main' into pill-run-decision

This commit is contained in:
2026-10-18 15:53:29 +01:00
14 changed files with 557 additions and 5 deletions
+3
View File
@@ -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
+5
View File
@@ -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.
+1 -1
View File
@@ -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
+57
View File
@@ -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)
}
}
+79
View File
@@ -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()
}
+16
View File
@@ -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.
+14
View File
@@ -179,6 +179,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"`
+18
View File
@@ -437,3 +437,21 @@ func TestChatReleaseShellsBoundsDisconnectedState(t *testing.T) {
t.Fatal("released session shell state was retained")
}
}
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)
}
}
+74
View File
@@ -32,6 +32,21 @@ 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
}
// ErrChatCreateConflict reports that another request owns the durable bootstrap
// transition, or that its expected phase no longer matches.
var ErrChatCreateConflict = errors.New("chat_create bootstrap ownership/state conflict")
// 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 +60,71 @@ 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 {
result, err := s.db.ExecContext(ctx, `UPDATE chat_create_bootstraps SET session_id=?,updated_at=? WHERE request_id=? AND state='creating' AND session_id=''`, sessionID, time.Now().UnixMilli(), requestID)
if err != nil {
return err
}
changed, err := result.RowsAffected()
if err != nil {
return err
}
if changed != 1 {
return ErrChatCreateConflict
}
return nil
}
// AdvanceChatCreate moves a bootstrap exactly one expected phase. Callers must
// reserve external work through this conditional update before performing it.
func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, from, to string) error {
result, err := s.db.ExecContext(ctx, `UPDATE chat_create_bootstraps SET state=?,updated_at=? WHERE request_id=? AND state=?`, to, time.Now().UnixMilli(), requestID, from)
if err != nil {
return err
}
changed, err := result.RowsAffected()
if err != nil {
return err
}
if changed != 1 {
return ErrChatCreateConflict
}
return nil
}
// 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
@@ -2,11 +2,52 @@ package pipeline
import (
"context"
"errors"
"path/filepath"
"testing"
"time"
)
func TestChatCreateBootstrapTransitionsAreOwnedAndDurable(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "operator.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
bootstrap, err := store.BeginChatCreate(ctx, "request", "title", "/work")
if err != nil || bootstrap.State != "created" {
t.Fatalf("BeginChatCreate = %+v, %v", bootstrap, err)
}
if err := store.AdvanceChatCreate(ctx, "request", "created", "creating"); err != nil {
t.Fatal(err)
}
if err := store.AdvanceChatCreate(ctx, "request", "created", "creating"); !errors.Is(err, ErrChatCreateConflict) {
t.Fatalf("second reservation error = %v, want ownership conflict", err)
}
if err := store.SetChatCreateSession(ctx, "request", "ses_one"); err != nil {
t.Fatal(err)
}
if err := store.SetChatCreateSession(ctx, "request", "ses_two"); !errors.Is(err, ErrChatCreateConflict) {
t.Fatalf("second session owner error = %v, want ownership conflict", err)
}
if err := store.AdvanceChatCreate(ctx, "request", "creating", "activated"); err != nil {
t.Fatal(err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
reopened, err := Open(path)
if err != nil {
t.Fatal(err)
}
defer reopened.Close()
bootstrap, err = reopened.BeginChatCreate(ctx, "request", "title", "/work")
if err != nil || bootstrap.SessionID != "ses_one" || bootstrap.State != "activated" {
t.Fatalf("reopened bootstrap = %+v, %v", bootstrap, err)
}
}
// TestOperatorSessionsRecordListAndUpsert proves the operator-session registry
// contract: rows persist the id, directory, title and tag; the list is
// most-recently-used first; and a second RecordOperatorSession for the same id
+5
View File
@@ -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.
@@ -52,6 +54,9 @@ type chatShellReleaser 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, from, to 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)
+9
View File
@@ -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, string) (protocol.C
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, 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
}
+77 -3
View File
@@ -100,6 +100,10 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
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
}
title := ""
directory := ""
if request.ChatCreate != nil {
@@ -114,13 +118,75 @@ 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 == "" {
if bootstrap.State != "created" {
chatCreateBootstrapError(request, session.ID, bootstrap.State, write)
return
}
// The conditional transition is the durable reservation for the external
// Create call. A duplicate request that lost it must not create an orphan.
if err := registry.AdvanceChatCreate(ctx, request.ID, "created", "creating"); err != nil {
chatCreateConflictError(request, err, write)
return
}
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 err := registry.AdvanceChatCreate(ctx, request.ID, "creating", "created"); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but durable bootstrap state could not advance: " + err.Error()})
return
}
bootstrap.State = "created"
}
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, "created", "activating"); err != nil {
chatCreateConflictError(request, err, write)
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, "activating", "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
}
bootstrap.State = "activated"
}
if bootstrap.State == "creating" || bootstrap.State == "activating" || bootstrap.State == "recording" {
chatCreateBootstrapError(request, session.ID, bootstrap.State, write)
return
}
if bootstrap.State == "activated" {
if err := registry.AdvanceChatCreate(ctx, request.ID, "activated", "recording"); err != nil {
chatCreateConflictError(request, err, write)
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()})
return
}
if err := registry.AdvanceChatCreate(ctx, request.ID, "recording", "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
}
} else if bootstrap.State != "recorded" {
chatCreateBootstrapError(request, session.ID, bootstrap.State, write)
return
}
session.Directory = resolved
@@ -132,6 +198,14 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
_ = write(response)
}
func chatCreateConflictError(request protocol.Message, err error, write func(protocol.Message) error) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat_create bootstrap ownership/state conflict: " + err.Error()})
}
func chatCreateBootstrapError(request protocol.Message, sessionID, state string, write func(protocol.Message) error) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " has an unfinished manager bootstrap (" + state + "); it will not be repeated automatically"})
}
// handleChatAdopt records a session that already exists on the endpoint in the
// operator registry, using the endpoint's own directory and title verbatim, so
// it appears in chat_sessions and can be continued. It refuses a nil broker, a
+158 -1
View File
@@ -77,6 +77,13 @@ type fakeChat struct {
createDirectory string
created protocol.ChatSession
createErr error
createGate <-chan struct{}
createStarted chan struct{}
createOnce sync.Once
activateCalls int
activateSessionID string
activateSkill string
activateErr error
sessionByIDCalls int
sessionByID string
sessionRecord protocol.ChatSession
@@ -84,6 +91,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, string) error { return nil }
func (f *fakeChat) Prompt(context.Context, string, string) error {
f.mu.Lock()
defer f.mu.Unlock()
@@ -250,12 +263,29 @@ 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) Create(_ context.Context, title, directory string) (protocol.ChatSession, error) {
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()
f.createCalls++
f.createTitle = title
f.createDirectory = directory
gate, started := f.createGate, f.createStarted
f.mu.Unlock()
if started != nil {
f.createOnce.Do(func() { close(started) })
}
if gate != nil {
<-gate
}
f.mu.Lock()
defer f.mu.Unlock()
if f.createErr != nil {
return protocol.ChatSession{}, f.createErr
}
@@ -1308,6 +1338,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)
@@ -1317,6 +1353,127 @@ 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)
}
}
// TestChatCreateDuplicateRequestReservesExternalWork proves the conditional
// durable transition, rather than timing or the race detector, elects exactly
// one request to call the external Create and ActivateSkill operations.
func TestChatCreateDuplicateRequestReservesExternalWork(t *testing.T) {
store := newOperatorStore(t)
createGate := make(chan struct{})
broker := &fakeChat{
created: protocol.ChatSession{ID: "ses_once"},
createGate: createGate,
createStarted: make(chan struct{}),
}
request := protocol.Message{ID: "same-request", Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "demo"}}
responses := make(chan protocol.Message, 2)
run := func() {
handleChatCreate(context.Background(), request, broker, store, func(message protocol.Message) error {
responses <- message
return nil
})
}
go run()
select {
case <-broker.createStarted:
case <-time.After(2 * time.Second):
t.Fatal("first request did not reserve Create")
}
go run()
select {
case response := <-responses:
if response.Type != protocol.Error || !strings.Contains(response.Error, "unfinished manager bootstrap") {
t.Fatalf("losing request response = %+v", response)
}
case <-time.After(2 * time.Second):
t.Fatal("duplicate request did not finish at its durable reservation")
}
close(createGate)
select {
case response := <-responses:
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.ID != "ses_once" {
t.Fatalf("winning request response = %+v", response)
}
case <-time.After(2 * time.Second):
t.Fatal("winning request did not finish")
}
broker.mu.Lock()
creates, activations := broker.createCalls, broker.activateCalls
broker.mu.Unlock()
if creates != 1 || activations != 1 {
t.Fatalf("duplicate request repeated external work: creates=%d activations=%d", creates, activations)
}
}
func TestChatCreateRequiresRequestID(t *testing.T) {
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}}
var response protocol.Message
handleChatCreate(context.Background(), protocol.Message{Type: protocol.ChatCreate, ChatCreate: &protocol.ChatCreateRequest{Title: "demo"}}, broker, newOperatorStore(t), func(message protocol.Message) error {
response = message
return nil
})
if response.Type != protocol.Error || !strings.Contains(response.Error, "non-empty request id") {
t.Fatalf("empty chat_create response = %+v", response)
}
broker.mu.Lock()
creates := broker.createCalls
broker.mu.Unlock()
if creates != 0 {
t.Fatalf("empty chat_create called broker.Create %d times", creates)
}
}
func TestChatSessionsAllowsEmptyRequestID(t *testing.T) {
store := newOperatorStore(t)
if err := store.RecordOperatorSession(context.Background(), "ses_existing", "/work", "Existing", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
broker := &fakeChat{sessions: []protocol.ChatSession{{ID: "ses_existing"}}}
var response protocol.Message
handleChatSessions(context.Background(), protocol.Message{Type: protocol.ChatSessions}, broker, nil, store, func(message protocol.Message) error {
response = message
return nil
})
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_existing" {
t.Fatalf("empty-ID chat_sessions response = %+v", response)
}
}
// 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