peppa/packages/core/src/steps.ts
Асель 9149c75840 PEP-19/54: project secrets for agents, secrets audit and two-key PEPPA_SECRET rotation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 07:19:57 +05:00

103 lines
4.6 KiB
TypeScript

import { actorColumns } from "./actor.ts";
import { projectSecretMasker } from "./secrets.ts";
// What the agent is doing now (PEP-33): every tool call of a Claude runner (PostToolUse hook)
// becomes a "step" event of its session. Only the last MAX_STEPS per session are kept, and
// steps stay out of the story journal (events of other types).
import { and, desc, eq, sql } from "drizzle-orm";
import { events, sessions, type Db } from "@peppa/db";
import { relative, isAbsolute } from "node:path";
import type { Session } from "./sessions.ts";
export const STEP_EVENT = "step";
export const MAX_STEPS = 200;
export type StepKind = "command" | "test" | "edit" | "read" | "search" | "web" | "agent" | "mcp" | "other";
export interface StepPayload {
tool: string;
kind: StepKind;
text: string;
ok: boolean;
}
export interface StepView extends StepPayload {
id: number;
sessionId: number;
at: string;
}
/** Tool calls that say nothing about the work (asking the PM, reading the story itself). */
const SKIP = new Set(["AskUserQuestion", "TodoWrite", "TodoRead", "ExitPlanMode", "mcp__peppa__get_task", "mcp__peppa__get_rules"]);
const TEST_RE = /(^|[\s/;&|(])(test|tests|e2e|jest|vitest|pytest|mocha|playwright|rspec|phpunit|ci\.sh|run ci|node --test|go test|cargo test|mix test)(\b|$)/i;
const oneLine = (s: string, n = 200) => {
const first = s.trim().split("\n")[0]!.trim();
return first.length > n ? `${first.slice(0, n)}…` : first;
};
function relPath(p: string, cwd?: string): string {
if (!cwd || !isAbsolute(p)) return p;
const r = relative(cwd, p);
return r && !r.startsWith("..") ? r : p;
}
/** Classifies one tool call; null = not worth a step. */
export function describeStep(tool: string, input: Record<string, unknown> = {}, cwd?: string): { kind: StepKind; text: string } | null {
if (!tool || SKIP.has(tool)) return null;
const s = (k: string) => (typeof input[k] === "string" ? (input[k] as string) : "");
switch (tool) {
case "Bash":
case "BashOutput": {
const cmd = s("command") || s("description") || tool;
return { kind: TEST_RE.test(cmd) ? "test" : "command", text: oneLine(cmd) };
}
case "Edit":
case "MultiEdit":
case "Write":
case "NotebookEdit":
return { kind: "edit", text: relPath(s("file_path") || s("notebook_path"), cwd) || tool };
case "Read":
return { kind: "read", text: relPath(s("file_path"), cwd) || tool };
case "Grep":
case "Glob":
return { kind: "search", text: oneLine(`${s("pattern")}${s("path") ? ` · ${relPath(s("path"), cwd)}` : ""}`) || tool };
case "WebFetch":
case "WebSearch":
return { kind: "web", text: oneLine(s("url") || s("query")) || tool };
case "Task":
case "Agent":
return { kind: "agent", text: oneLine(s("description") || s("prompt")) || tool };
}
if (tool.startsWith("mcp__")) return { kind: "mcp", text: tool.replace(/^mcp__/, "").replace("__", " · ") };
return { kind: "other", text: tool };
}
/** Stores a step and drops what is older than the last MAX_STEPS of the session. */
export async function recordStep(db: Db, s: Pick<Session, "id" | "projectId" | "taskId">, step: StepPayload, now = new Date()) {
// PEP-54: a command or output with a project secret never lands in the journal as is.
step = { ...step, text: (await projectSecretMasker(db, s.projectId))(step.text) };
const [row] = await db.insert(events).values({ projectId: s.projectId, taskId: s.taskId, sessionId: s.id, type: STEP_EVENT, payload: step, createdAt: now, ...actorColumns(s.id) }).returning();
// Activity time without notify(): a step is not a status change (the bot needn't wake).
await db.update(sessions).set({ lastActivityAt: now }).where(eq(sessions.id, s.id));
await db.run(sql`DELETE FROM events WHERE session_id = ${s.id} AND type = ${STEP_EVENT} AND id <= (
SELECT id FROM events WHERE session_id = ${s.id} AND type = ${STEP_EVENT} ORDER BY id DESC LIMIT 1 OFFSET ${MAX_STEPS})`);
return row!;
}
export function stepView(e: typeof events.$inferSelect): StepView {
const p = (e.payload ?? {}) as Partial<StepPayload>;
return { id: e.id, sessionId: e.sessionId ?? 0, at: e.createdAt.toISOString(), tool: p.tool ?? "?", kind: p.kind ?? "other", text: p.text ?? "", ok: p.ok !== false };
}
/** Latest steps of a session, newest first. */
export async function sessionSteps(db: Db, sessionId: number, limit = 30): Promise<StepView[]> {
const rows = await db
.select()
.from(events)
.where(and(eq(events.sessionId, sessionId), eq(events.type, STEP_EVENT)))
.orderBy(desc(events.id))
.limit(limit);
return rows.map(stepView);
}