peppa/packages/core/src/memory.ts
2026-11-15 14:47:50 +05:00

150 lines
6.7 KiB
TypeScript
Raw Permalink 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, readFileSync, 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";
export const MEMORY_FILE = ".peppa/memory.md";
export const MEMORY_SECTIONS = ["Команды", "Соглашения", "Грабли", "Решения"] as const;
export type MemorySection = (typeof MEMORY_SECTIONS)[number];
const MAX_FACT = 500;
export const memoryMaxChars = () => Number(process.env.PEPPA_MEMORY_MAX_CHARS ?? 12_000);
const HEADER = "# Память проекта\n\nПишет агент через MCP `remember` (PEP-30). Коротко: команды, соглашения, грабли, решения.\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 function readMemory(dir: string): string {
const p = memoryPath(dir);
return existsSync(p) ? readFileSync(p, "utf8") : "";
}
export function memoryStats(text: string): MemoryStats {
const max = memoryMaxChars();
return { chars: text.length, max, nearLimit: text.length > max * 0.8 };
}
const norm = (s: string) => s.toLowerCase().replace(/[\s`*_.,;:—–-]+/g, " ").trim();
/** 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 write(dir: string, text: string) {
const p = memoryPath(dir);
mkdirSync(dirname(p), { recursive: true });
writeFileSync(p, text.endsWith("\n") ? text : `${text}\n`);
}
function tooBig(chars: number): PeppaError {
return new PeppaError(
`Память проекта вышла бы за предел ${memoryMaxChars()} символов (было бы ${chars}). Ужми её: get_memory, затем remember с replace: true и сокращённым текстом (объедини похожие пункты, убери устаревшее).`,
);
}
/** Adds one bullet to a section; returns "exists" for a duplicate (nothing written). */
export function rememberFact(dir: string, sectionInput: string, fact: string): { result: "added" | "exists"; 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 cur = readMemory(dir) || HEADER;
const lines = cur.replace(/\n+$/, "").split("\n");
const key = norm(line);
if (lines.some((l) => /^\s*[-*]\s+/.test(l) && norm(l.replace(/^\s*[-*]\s+/, "")) === key)) return { result: "exists", stats: memoryStats(cur) };
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++;
// After the section's last non-empty line.
let at = end;
while (at > head + 1 && !lines[at - 1]!.trim()) at--;
lines.splice(at, 0, `- ${line}`);
}
const next = `${lines.join("\n")}\n`;
if (next.length > memoryMaxChars()) throw tooBig(next.length);
write(dir, next);
return { result: "added", stats: memoryStats(next) };
}
/** Rewrites the whole memory (compaction); still within the limit. */
export function replaceMemory(dir: string, text: string): MemoryStats {
const body = text.trim();
if (!body) throw new PeppaError(tr("Пустая память — чтобы ужать, передай сокращённый текст"));
const next = `${body}\n`;
if (next.length > memoryMaxChars()) throw tooBig(next.length);
write(dir, next);
return memoryStats(next);
}
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 file of the
* runner's working copy (capped) and a digest of the last finished stories.
*/
export async function memoryContext(db: Db, projectId: number, dir: string): Promise<string> {
const mem = readMemory(dir).trim();
const stories = await recentDoneStories(db, projectId);
const max = memoryMaxChars();
const parts = ["# Память проекта (PEP-30)", ""];
if (mem) {
const st = memoryStats(mem);
parts.push(`Из \`${MEMORY_FILE}\` (${st.chars} из ${max} символов${st.nearLimit ? " — почти предел, ужми через remember с replace" : ""}):`, "");
parts.push(mem.length > max ? `${mem.slice(0, max)}\n…(обрезано по пределу)` : mem);
} else {
parts.push(`\`${MEMORY_FILE}\` пока пуст — записывай знания через 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");
}