peppa/packages/core/src/memory.ts

322 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-30: project memory — `.peppa/memory.md` in the project repo, written by agents.
import { m as tr } from "@peppa/shared/i18n";
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, isNull } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
/** PEP-306: the memory lives in a directory — `common.md` plus one file per story. */
export const MEMORY_DIR = ".peppa/memory";
/** Pre-PEP-306 single file: still read as a source until it is split or compacted. */
export const MEMORY_FILE = ".peppa/memory.md";
export const MEMORY_COMMON = "common.md";
export const MEMORY_SECTIONS = ["Команды", "Соглашения", "Грабли", "Решения"] as const;
export type MemorySection = (typeof MEMORY_SECTIONS)[number];
const MAX_FACT = 500;
/** Limit of the assembled memory in the agent's prompt (and of a compacted `common.md`). */
export const memoryMaxChars = () => Number(process.env.PEPPA_MEMORY_MAX_CHARS ?? 12_000);
/** Limit of one story's memory file: one story does not bloat the memory (PEP-306). */
export const memoryTaskMaxChars = () => Number(process.env.PEPPA_MEMORY_TASK_MAX_CHARS ?? 2_000);
const HEADER = "# Память проекта\n\nПишет агент через MCP `remember` (PEP-30); файл на задачу — `.peppa/memory/<ключ>.md` (PEP-306).\n";
export interface MemoryStats {
chars: number;
max: number;
/** More than 80% of the limit. */
nearLimit: boolean;
}
export const memoryPath = (dir: string) => join(dir, MEMORY_FILE);
export const memoryDirPath = (dir: string) => join(dir, MEMORY_DIR);
/** File name of a story's memory: `PEP-42` → `pep-42.md`; no story → `common.md`. */
export function memoryFileName(taskKey: string | null | undefined): string {
const k = (taskKey ?? "").trim().toLowerCase();
return /^[a-z][a-z0-9]*-\d+$/.test(k) ? `${k}.md` : MEMORY_COMMON;
}
export interface MemorySource {
/** Repo-relative path. */
path: string;
/** Story key (`PEP-42`) or null for common/legacy. */
key: string | null;
text: string;
}
const taskNum = (name: string) => Number(/-(\d+)\.md$/.exec(name)?.[1] ?? 0);
/** Memory sources in assembly order: legacy file, `common.md`, story files by number. */
export function memorySources(dir: string): MemorySource[] {
const out: MemorySource[] = [];
const legacy = memoryPath(dir);
if (existsSync(legacy)) out.push({ path: MEMORY_FILE, key: null, text: readFileSync(legacy, "utf8") });
const d = memoryDirPath(dir);
if (!existsSync(d)) return out;
const names = readdirSync(d).filter((n) => n.endsWith(".md"));
if (names.includes(MEMORY_COMMON)) out.push({ path: `${MEMORY_DIR}/${MEMORY_COMMON}`, key: null, text: readFileSync(join(d, MEMORY_COMMON), "utf8") });
const stories = names.filter((n) => n !== MEMORY_COMMON).sort((a, b) => a.replace(/-\d+\.md$/, "").localeCompare(b.replace(/-\d+\.md$/, "")) || taskNum(a) - taskNum(b));
for (const n of stories) out.push({ path: `${MEMORY_DIR}/${n}`, key: n.slice(0, -3).toUpperCase(), text: readFileSync(join(d, n), "utf8") });
return out;
}
const norm = (s: string) => s.toLowerCase().replace(/[\s`*_.,;:—–-]+/g, " ").trim();
const BULLET = /^\s*[-*]\s+/;
/** Bullets of a memory text by section (lines outside sections and headers are dropped). */
export function parseMemory(text: string): Map<string, string[]> {
const out = new Map<string, string[]>();
let section: string | null = null;
let last: string[] | null = null;
for (const l of text.split("\n")) {
const h = /^##\s+(.+?)\s*$/.exec(l);
if (h) {
section = h[1]!;
if (!out.has(section)) out.set(section, []);
last = null;
continue;
}
if (!section) continue;
if (BULLET.test(l)) {
out.get(section)!.push(`- ${l.replace(BULLET, "").trim()}`);
last = out.get(section)!;
} else if (l.trim() && last?.length) {
// A wrapped bullet: continuation line.
last[last.length - 1] += ` ${l.trim()}`;
}
}
return out;
}
const sectionOrder = (names: Iterable<string>) => {
const all = [...names];
const known = MEMORY_SECTIONS.filter((s) => all.some((n) => n.toLowerCase() === s.toLowerCase()));
const rest = all.filter((n) => !MEMORY_SECTIONS.some((s) => s.toLowerCase() === n.toLowerCase()));
return [...known, ...rest];
};
/** Assembles memory texts into one document: sections in the usual order, repeats dropped. */
export function assembleMemory(texts: string[]): string {
const bySection = new Map<string, string[]>();
const seen = new Set<string>();
for (const t of texts) {
for (const [sec, items] of parseMemory(t)) {
const name = MEMORY_SECTIONS.find((s) => s.toLowerCase() === sec.toLowerCase()) ?? sec;
const list = bySection.get(name) ?? [];
for (const it of items) {
const k = norm(it.replace(BULLET, ""));
if (!k || seen.has(k)) continue;
seen.add(k);
list.push(it);
}
bySection.set(name, list);
}
}
const parts = [HEADER.trimEnd()];
for (const s of sectionOrder(bySection.keys())) {
const items = bySection.get(s)!;
if (items.length) parts.push("", `## ${s}`, ...items);
}
return parts.length > 1 ? `${parts.join("\n")}\n` : "";
}
/** The whole project memory, assembled from all files (empty when there is none). */
export function readMemory(dir: string): string {
return assembleMemory(memorySources(dir).map((s) => s.text));
}
export function memoryStats(text: string, max = memoryMaxChars()): MemoryStats {
return { chars: text.length, max, nearLimit: text.length > max * 0.8 };
}
/** Section aliases accepted from agents (English names, lower case). */
const SECTION_ALIASES: Record<string, MemorySection> = {
команды: "Команды",
commands: "Команды",
соглашения: "Соглашения",
conventions: "Соглашения",
грабли: "Грабли",
pitfalls: "Грабли",
gotchas: "Грабли",
решения: "Решения",
decisions: "Решения",
};
export function parseSection(s: string | undefined): MemorySection {
const v = SECTION_ALIASES[(s ?? "").trim().toLowerCase()];
if (!v) throw new PeppaError(tr("Раздел памяти: {v}", { v: MEMORY_SECTIONS.join(", ") }));
return v;
}
function writeFile(p: string, text: string) {
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, text.endsWith("\n") ? text : `${text}\n`);
}
/** Inserts a bullet into its section of a memory text (creates the section). */
function addBullet(text: string, section: MemorySection, line: string): string {
const lines = text.replace(/\n+$/, "").split("\n");
const head = lines.findIndex((l) => l.trim().toLowerCase() === `## ${section.toLowerCase()}`);
if (head < 0) {
lines.push("", `## ${section}`, `- ${line}`);
} else {
let end = head + 1;
while (end < lines.length && !/^##\s/.test(lines[end]!)) end++;
let at = end;
while (at > head + 1 && !lines[at - 1]!.trim()) at--;
lines.splice(at, 0, `- ${line}`);
}
return `${lines.join("\n")}\n`;
}
const fileHeader = (key: string | null) => (key ? `# Память: ${key}\n` : HEADER);
const hasBullet = (text: string, key: string) => [...parseMemory(text).values()].some((items) => items.some((it) => norm(it.replace(BULLET, "")) === key));
/**
* Adds one bullet to the memory file of the story (`taskKey`; none — `common.md`).
* A bullet already present in any memory file is not added ("exists").
*/
export function rememberFact(
dir: string,
sectionInput: string,
fact: string,
taskKey?: string | null,
): { result: "added" | "exists"; file: string; stats: MemoryStats } {
const section = parseSection(sectionInput);
const line = fact.replace(/\s+/g, " ").trim().replace(/^[-*]\s+/, "");
if (!line) throw new PeppaError(tr("Пустой пункт памяти"));
if (line.length > MAX_FACT) throw new PeppaError(tr("Пункт памяти длиннее {n} символов — сформулируй короче", { n: MAX_FACT }));
const name = memoryFileName(taskKey);
const file = `${MEMORY_DIR}/${name}`;
const key = norm(line);
const sources = memorySources(dir);
if (sources.some((s) => hasBullet(s.text, key))) return { result: "exists", file, stats: memoryStats(assembleMemory(sources.map((s) => s.text))) };
const p = join(dir, file);
const story = name !== MEMORY_COMMON;
const cur = existsSync(p) ? readFileSync(p, "utf8") : fileHeader(story ? name.slice(0, -3).toUpperCase() : null);
const next = addBullet(cur, section, line);
const max = story ? memoryTaskMaxChars() : memoryMaxChars();
if (next.length > max) {
throw new PeppaError(
story
? `Запись задачи в памяти (${file}) вышла бы за предел ${max} символов (было бы ${next.length}). Оставь в ней главное: объедини похожие пункты, убери то, что уже есть в спеках.`
: `Общая память (${file}) вышла бы за предел ${max} символов (было бы ${next.length}). Ужми её: get_memory, затем remember с replace: true и сокращённым текстом.`,
);
}
writeFile(p, next);
return { result: "added", file, stats: memoryStats(readMemory(dir)) };
}
/**
* Compaction: the text becomes `common.md`; story files and the legacy file are removed.
* Returns the removed repo-relative paths too (to commit the deletion).
*/
export function replaceMemory(dir: string, text: string): MemoryStats & { removed: string[] } {
const body = text.trim();
if (!body) throw new PeppaError(tr("Пустая память — чтобы ужать, передай сокращённый текст"));
const next = `${body}\n`;
if (next.length > memoryMaxChars()) {
throw new PeppaError(`Память проекта вышла бы за предел ${memoryMaxChars()} символов (было бы ${next.length}). Сократи текст: объедини похожие пункты, убери устаревшее.`);
}
const removed: string[] = [];
for (const s of memorySources(dir)) {
if (s.path === `${MEMORY_DIR}/${MEMORY_COMMON}`) continue;
rmSync(join(dir, s.path), { force: true });
removed.push(s.path);
}
writeFile(join(memoryDirPath(dir), MEMORY_COMMON), next);
return { ...memoryStats(next), removed };
}
/**
* PEP-306 migration: every bullet of the legacy `.peppa/memory.md` goes to the file of the
* story it mentions first (`PEP-42` → `pep-42.md`), the rest — to `common.md`; nothing is lost.
* The legacy file is removed. Returns the written files with their bullet counts.
*/
export function splitLegacyMemory(dir: string): { files: Record<string, number>; moved: number } {
const legacy = memoryPath(dir);
if (!existsSync(legacy)) return { files: {}, moved: 0 };
const parsed = parseMemory(readFileSync(legacy, "utf8"));
const files: Record<string, number> = {};
let moved = 0;
for (const [sec, items] of parsed) {
const section = MEMORY_SECTIONS.find((s) => s.toLowerCase() === sec.toLowerCase()) ?? (sec as MemorySection);
for (const it of items) {
const line = it.replace(BULLET, "");
const k = /\b([A-Z][A-Z0-9]*-\d+)\b/.exec(line)?.[1] ?? null;
const name = memoryFileName(k);
const p = join(memoryDirPath(dir), name);
const cur = existsSync(p) ? readFileSync(p, "utf8") : fileHeader(name === MEMORY_COMMON ? null : k);
if (hasBullet(cur, norm(line))) continue;
writeFile(p, addBullet(cur, section, line));
files[`${MEMORY_DIR}/${name}`] = (files[`${MEMORY_DIR}/${name}`] ?? 0) + 1;
moved++;
}
}
rmSync(legacy);
return { files, moved };
}
export interface DoneStory {
key: string;
title: string;
change: string | null;
updatedAt: Date;
}
/** The project's last finished stories (newest first, archived ones excluded). */
export async function recentDoneStories(db: Db, projectId: number, limit = 5): Promise<DoneStory[]> {
const rows = await db
.select({ key: projects.key, number: tasks.number, title: tasks.title, change: tasks.openspecChange, updatedAt: tasks.updatedAt })
.from(tasks)
.innerJoin(projects, eq(tasks.projectId, projects.id))
.where(and(eq(tasks.projectId, projectId), eq(tasks.status, "done"), isNull(tasks.archivedAt)))
.orderBy(desc(tasks.updatedAt), desc(tasks.id))
.limit(limit);
return rows.map((r) => ({ key: formatTaskKey(r.key, r.number), title: r.title, change: r.change, updatedAt: r.updatedAt }));
}
const day = (d: Date) => d.toISOString().slice(0, 10);
/**
* The "Память проекта" block appended to the agent's launch rules: the memory of the runner's
* working copy and a digest of the last finished stories. The memory part never exceeds
* `memoryMaxChars()` (PEP-306): common text first, then stories from the newest; the ones that
* did not fit are named so that an agent can compact them.
*/
export async function memoryContext(db: Db, projectId: number, dir: string): Promise<string> {
const stories = await recentDoneStories(db, projectId);
const max = memoryMaxChars();
const sources = memorySources(dir);
const own = sources.filter((s) => s.key).reverse(); // newest first
let taken = sources.filter((s) => !s.key).map((s) => s.text);
let mem = assembleMemory(taken);
if (mem.length > max) mem = `${mem.slice(0, max)}\n…(обрезано по пределу)`;
const left: string[] = [];
for (const s of own) {
const next = left.length ? "" : assembleMemory([...taken, s.text]);
if (left.length || next.length > max) {
left.push(s.key!);
continue;
}
taken = [...taken, s.text];
mem = next;
}
const parts = ["# Память проекта (PEP-30)", ""];
if (mem.trim()) {
const st = memoryStats(mem.trim(), max);
parts.push(`Из \`${MEMORY_DIR}/\` (${st.chars} из ${max} символов${st.nearLimit ? " — почти предел" : ""}; твоя запись — \`${MEMORY_DIR}/<ключ задачи>.md\`):`, "");
parts.push(mem.trim());
if (left.length) parts.push("", `Не вошли записи задач (вся память — ${readMemory(dir).length} символов): ${left.join(", ")} — сверни память через remember с replace: true.`);
} else {
parts.push(`Память пока пуста — записывай знания через MCP \`remember\`.`);
}
if (stories.length) {
parts.push("", "Последние завершённые стори:");
for (const s of stories) parts.push(`- ${s.key} «${s.title}»${s.change ? ` — change ${s.change}` : ""} (${day(s.updatedAt)})`);
}
return parts.join("\n");
}