27a2e52376
Use conditional durable phase transitions and affected-row checks so only the request that reserves each phase can create or activate a manager chat session. Record duplicate ownership conflicts without repeating external work, and cover the reservation and restart state in pipeline and server tests. Checked packaged templates and authoring skill references: the existing task commit already packages the dedicated manager skill and installer inventory; this transition-race fix requires no further template or reference update. Shared documentation remains untouched; the task note is docs/notes/manager-skill-bootstrap.md.
244 lines
11 KiB
Go
244 lines
11 KiB
Go
package pipeline
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"time"
|
|
)
|
|
|
|
// operatorSessionListLimit bounds one OperatorSessions read so a long-lived
|
|
// database with unbounded operator-session history cannot make one chat_sessions
|
|
// request scan it all. Rows are read most-recently-used first, so the bound only
|
|
// ever drops the oldest sessions, never one the operator just used. It mirrors
|
|
// the bounded newest-first convention of sessionOwnerScanLimit.
|
|
const operatorSessionListLimit = 128
|
|
|
|
// OperatorSession is one recorded operator chat session: a chat the person
|
|
// created through chat_create, tagged with its kind and carrying the directory
|
|
// it lives in. CreatedAt is when the row was first recorded; UpdatedAt is the
|
|
// last-used epoch-millisecond timestamp that drives most-recently-used ordering.
|
|
type OperatorSession struct {
|
|
ID string
|
|
Directory string
|
|
Title string
|
|
Tag string
|
|
CreatedAt int64
|
|
UpdatedAt int64
|
|
// ClosedAt is the epoch-millisecond time the operator finished with the
|
|
// session, or 0 while it is open. It records the closed state on the server
|
|
// so every client sees the same thing; the session and its history are never
|
|
// deleted, and reopening clears it back to 0.
|
|
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
|
|
// vocabularies cannot be confused. session_id is the primary key, so lookups and
|
|
// the upsert use the index; operator_sessions_recent serves the recency order.
|
|
// closed_at is added here for a fresh database and by migrateOperatorSessions for
|
|
// one created before the closed state existed.
|
|
func (s *Store) initOperatorSessions() error {
|
|
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions (
|
|
session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
|
|
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
|
|
// and no session is silently reported as closed.
|
|
func (s *Store) migrateOperatorSessions() error {
|
|
return s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0")
|
|
}
|
|
|
|
// RecordOperatorSession upserts one operator chat session in a single statement:
|
|
// a new id is inserted with its created_at and last_used_at set to now, and a
|
|
// repeated id updates directory/title/tag and moves last_used_at to now while
|
|
// preserving the original created_at. CreatedAt is therefore stable across
|
|
// re-records. Recording also clears any closed state: re-creating or adopting a
|
|
// session is use, so it is open again.
|
|
func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error {
|
|
now := time.Now().UnixMilli()
|
|
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at)
|
|
VALUES(?,?,?,?,?,?,0)
|
|
ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0`,
|
|
sessionID, directory, title, tag, now, now)
|
|
return err
|
|
}
|
|
|
|
// TouchOperatorSession records that an operator session was just used, in one
|
|
// UPDATE. It also clears the closed state, so simply prompting a closed session
|
|
// reopens it. A session id that is not an operator session updates no row and is
|
|
// not an error: the statement is itself the presence check, so no second read is
|
|
// needed.
|
|
func (s *Store) TouchOperatorSession(ctx context.Context, sessionID string) error {
|
|
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET last_used_at=?, closed_at=0 WHERE session_id=?", time.Now().UnixMilli(), sessionID)
|
|
return err
|
|
}
|
|
|
|
// CloseOperatorSession records that the operator finished with an operator
|
|
// session, in one UPDATE that sets closed_at to now. Nothing is deleted: the row,
|
|
// its history and the OpenCode session itself are untouched. A session id that is
|
|
// not an operator session (for example a pipeline-owned run session) updates no
|
|
// row and is not an error, so run sessions are never affected.
|
|
func (s *Store) CloseOperatorSession(ctx context.Context, sessionID string) error {
|
|
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET closed_at=? WHERE session_id=?", time.Now().UnixMilli(), sessionID)
|
|
return err
|
|
}
|
|
|
|
// ReopenOperatorSession clears the closed state of an operator session, in one
|
|
// UPDATE that sets closed_at back to 0. A session id that is not an operator
|
|
// session updates no row and is not an error.
|
|
func (s *Store) ReopenOperatorSession(ctx context.Context, sessionID string) error {
|
|
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET closed_at=0 WHERE session_id=?", sessionID)
|
|
return err
|
|
}
|
|
|
|
// OperatorSession returns one operator session by id. found is false when the id
|
|
// is not a recorded operator session (so a pipeline-owned run session is never
|
|
// returned). It is one indexed lookup and never mutates the row.
|
|
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
|
|
var session OperatorSession
|
|
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
|
|
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
|
|
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil {
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return OperatorSession{}, false, nil
|
|
}
|
|
return OperatorSession{}, false, err
|
|
}
|
|
return session, true, nil
|
|
}
|
|
|
|
// OperatorSessions reports the operator's chat sessions, most-recently-used
|
|
// first (ties broken by session id for a deterministic order), capped at
|
|
// operatorSessionListLimit. Rows with no tag are omitted: a session with no
|
|
// recorded tag is not an operator session and must never be listed. Closed
|
|
// sessions are included: the app groups or filters them as history, so the
|
|
// operator can still see and reopen what they finished. It is one bounded
|
|
// statement; recency is never mutated here.
|
|
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
|
|
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
|
|
FROM operator_sessions WHERE tag <> '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
sessions := []OperatorSession{}
|
|
for rows.Next() {
|
|
var session OperatorSession
|
|
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil {
|
|
return nil, err
|
|
}
|
|
sessions = append(sessions, session)
|
|
}
|
|
return sessions, rows.Err()
|
|
}
|
|
|
|
// OperatorDirectories reports the distinct directories of the operator's
|
|
// sessions, most-recently-used first, deduplicated in SQL and capped at limit.
|
|
// It is one bounded statement, newest use per directory wins the ordering, and
|
|
// it never mutates recency. A non-positive limit returns no directories.
|
|
func (s *Store) OperatorDirectories(ctx context.Context, limit int) ([]string, error) {
|
|
if limit <= 0 {
|
|
return nil, nil
|
|
}
|
|
rows, err := s.db.QueryContext(ctx, `SELECT directory FROM operator_sessions WHERE tag <> ''
|
|
GROUP BY directory ORDER BY MAX(last_used_at) DESC, directory LIMIT ?`, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
directories := []string{}
|
|
for rows.Next() {
|
|
var directory string
|
|
if err := rows.Scan(&directory); err != nil {
|
|
return nil, err
|
|
}
|
|
directories = append(directories, directory)
|
|
}
|
|
return directories, rows.Err()
|
|
}
|