peppa/packages/core/src/sessions.ts
Асель 00c8f79a36 PEP-7: autonomous mode — board moves start agents, PM only for stoppers
- web board (Backlog / In progress / Review / Done) with drag-and-drop and
  buttons; moveTask starts an agent on In progress, stops on Backlog/Done
- routine proposals go straight to apply; request_approval/ask_pm only for
  architectural stoppers (RULES.md, MCP hints, template pushed to Gitea)
- Stop hook keeps the agent going (decision: block, max 2 in a row,
  sessions.auto_nudges reset by a human answer) instead of pinging the PM
- review: ready-for-review message with Accept (acceptTask → done, session
  stopped) in Telegram and web; a text reply goes back to the agent
- mock-claude honours Stop-hook block; 6 new e2e tests (48 total, green)
- OpenSpec: pep-7 archived (task-autonomy, web-workspace board)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 21:21:11 +05:00

152 lines
5.3 KiB
TypeScript

import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, isNull, notInArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import type { Question, QuestionKind } from "./tasks.ts";
export type Session = typeof sessions.$inferSelect;
export type SessionStatus = (typeof sessionStatus.enumValues)[number];
export const FINISHED_SESSION_STATUSES: SessionStatus[] = ["done", "failed"];
export interface SessionView extends Session {
projectKey: string;
taskKey: string | null;
taskTitle: string | null;
}
export async function createSession(
db: Db,
s: { projectId: number; taskId?: number; provider?: Session["provider"] },
): Promise<Session> {
// tmux name needs the id, so insert with a unique placeholder first.
const [row] = await db
.insert(sessions)
.values({ ...s, tmuxName: `pending-${crypto.randomUUID()}` })
.returning();
return row!;
}
export async function getSession(db: Db, id: number): Promise<SessionView> {
const [row] = await sessionQuery(db).where(eq(sessions.id, id));
if (!row) throw new PeppaError(`Session #${id} not found`);
return toView(row);
}
export async function listSessions(db: Db, opts: { active?: boolean; taskId?: number } = {}): Promise<SessionView[]> {
const rows = await sessionQuery(db)
.where(
and(
opts.active ? notInArray(sessions.status, FINISHED_SESSION_STATUSES) : undefined,
opts.taskId != null ? eq(sessions.taskId, opts.taskId) : undefined,
),
)
.orderBy(desc(sessions.id));
return rows.map(toView);
}
export async function updateSession(
db: Db,
id: number,
patch: Partial<Pick<Session, "status" | "tmuxName" | "conversationId" | "generation" | "autoNudges" | "lastActivityAt" | "endedAt">>,
): Promise<Session> {
const [row] = await db.update(sessions).set(patch).where(eq(sessions.id, id)).returning();
if (!row) throw new PeppaError(`Session #${id} not found`);
if (patch.status) await notify(db, { type: "session_updated", sessionId: id });
return row;
}
export async function logSessionEvent(db: Db, s: Session, type: string, payload?: unknown) {
const [row] = await db
.insert(events)
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type, payload })
.returning();
return row!;
}
/** Unanswered questions raised by a session (ask_pm, approvals, hook/watchdog alerts). */
export async function pendingSessionQuestions(
db: Db,
sessionId: number,
opts: { excludeHook?: boolean } = {},
): Promise<Question[]> {
return db
.select()
.from(questions)
.where(
and(
eq(questions.sessionId, sessionId),
isNull(questions.answeredAt),
opts.excludeHook ? eq(questions.awaitingHook, false) : undefined,
),
);
}
export async function getQuestion(db: Db, id: number): Promise<Question> {
const [row] = await db.select().from(questions).where(eq(questions.id, id));
if (!row) throw new PeppaError(`Question #${id} not found`);
return row;
}
/**
* A blocking hook gives up waiting: from now on the answer goes to the terminal.
* Returns the question if it got answered in the meantime (the race is settled by
* Postgres row locking against answerQuestion).
*/
export async function releaseHookQuestion(db: Db, id: number): Promise<Question | null> {
const [released] = await db
.update(questions)
.set({ awaitingHook: false })
.where(and(eq(questions.id, id), isNull(questions.answeredAt)))
.returning();
return released ? null : getQuestion(db, id);
}
/** Raises a session-level alert for the PM (permission prompt, idle, stall, crash). */
export async function raiseSessionQuestion(
db: Db,
s: Session,
kind: QuestionKind,
text: string,
options?: string[],
awaitingHook = false,
): Promise<Question> {
const [row] = await db
.insert(questions)
.values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, kind, text, options, awaitingHook })
.returning();
await notify(db, { type: "question", questionId: row!.id });
return row!;
}
function sessionQuery(db: Db) {
return db
.select({ session: sessions, projectKey: projects.key, taskNumber: tasks.number, taskTitle: tasks.title })
.from(sessions)
.innerJoin(projects, eq(sessions.projectId, projects.id))
.leftJoin(tasks, eq(sessions.taskId, tasks.id));
}
function toView(r: { session: Session; projectKey: string; taskNumber: number | null; taskTitle: string | null }): SessionView {
return {
...r.session,
projectKey: r.projectKey,
taskKey: r.taskNumber != null ? formatTaskKey(r.projectKey, r.taskNumber) : null,
taskTitle: r.taskTitle,
};
}
/**
* Closes a session's open questions when it is stopped or relaunched: their answer could
* no longer reach the run that asked (a resumed run asks again if it still needs to).
*/
export async function expireSessionQuestions(db: Db, sessionId: number, reason: string): Promise<Question[]> {
const rows = await db
.update(questions)
.set({ answer: reason, answeredVia: "system", answeredAt: new Date(), awaitingHook: false })
.where(and(eq(questions.sessionId, sessionId), isNull(questions.answeredAt)))
.returning();
for (const q of rows) await notify(db, { type: "question_answered", questionId: q.id });
return rows;
}