peppa/packages/core/src/product-needs.ts
peppa-bot f3d10a4c25 PEP-243: платформа называется FORGE — название во всех текстах для людей и подсказках агентам, адрес forge.telecom.quest
«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках
агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя».
Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-23 11:18:49 +05:00

144 lines
7.7 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-112: «чтобы заработало по-настоящему» — what the project's owner has to give before the
// product stops being a demo: a key, an account, a decision. The developer agent declares the
// items (MCP `declare_needs`), the product agent adds what it saw on the deployed product, the
// «Ваш продукт» card shows the open ones. An item that names a secret closes itself while that
// secret is stored in the project's secrets (Peppa hands them to the deploy); the rest the owner
// ticks off. One `settings` row per project — the list is short and always read whole.
import { projectSecrets, type Db } from "@peppa/db";
import { eq } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { secretNameError } from "./secrets.ts";
import { deleteSetting, getSetting, setSetting } from "./settings.ts";
import { asIs, m as tr } from "@peppa/shared/i18n";
export type NeedSource = "agent" | "product";
export interface ProductNeed {
id: string;
/** What to give, in the owner's words: «Ключ Claude API». */
title: string;
/** What does not work without it. */
why: string;
/** Where to get it, step by step. */
how: string;
/** Name of the project secret that closes the item. */
secret: string | null;
source: NeedSource;
/** Story key that declared it. */
story: string | null;
/** Ticked off by the owner (ISO). */
doneAt: string | null;
}
export interface ProductNeedView extends ProductNeed {
open: boolean;
}
export interface NeedInput {
title: string;
why?: string | null;
how?: string | null;
secret?: string | null;
}
export const MAX_NEEDS = 20;
const key = (projectId: number) => `product.needs:${projectId}`;
const clip = (s: string | null | undefined, n: number) => (s ?? "").replace(/\s+/g, " ").trim().slice(0, n);
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
const mergeKey = (n: Pick<ProductNeed, "title" | "secret">) => (n.secret ? `s:${n.secret}` : `t:${norm(n.title)}`);
async function stored(db: Db, projectId: number): Promise<ProductNeed[]> {
return (await getSetting<ProductNeed[]>(db, key(projectId))) ?? [];
}
/** The project's list with each item's state (open = the owner still has to act). */
export async function productNeeds(db: Db, projectId: number): Promise<ProductNeedView[]> {
const list = await stored(db, projectId);
if (!list.length) return [];
const have = new Set((await db.select({ name: projectSecrets.name }).from(projectSecrets).where(eq(projectSecrets.projectId, projectId))).map((r) => r.name));
return list.map((n) => ({ ...n, open: n.secret ? !have.has(n.secret) : !n.doneAt }));
}
export async function openNeeds(db: Db, projectId: number): Promise<ProductNeedView[]> {
return (await productNeeds(db, projectId)).filter((n) => n.open);
}
function clean(input: NeedInput): Pick<ProductNeed, "title" | "why" | "how" | "secret"> {
const title = clip(input.title, 120);
if (!title) throw new PeppaError("У пункта нет названия (title): что нужно дать, словами владельца");
const secret = input.secret?.trim() || null;
if (secret) {
const err = secretNameError(secret);
if (err) throw new PeppaError(err);
}
return { title, why: clip(input.why, 300), how: clip(input.how, 600), secret };
}
/**
* Adds items to the list (merging by secret name, else by title) and returns the ones that are
* new and still open — the caller tells the owner about those. With `replaceSource` the items
* of that source that have no secret and are not in `inputs` are dropped first: the product
* agent looks at the product afresh every time. Items the owner ticked off stay ticked.
*/
export async function declareNeeds(db: Db, projectId: number, inputs: NeedInput[], o: { source: NeedSource; story?: string | null; replaceSource?: boolean }): Promise<{ added: ProductNeedView[]; all: ProductNeedView[] }> {
const incoming = inputs.map(clean);
let list = await stored(db, projectId);
if (o.replaceSource) {
const keep = new Set(incoming.map(mergeKey));
list = list.filter((n) => n.source !== o.source || n.secret || n.doneAt || keep.has(mergeKey(n)));
}
const addedIds = new Set<string>();
for (const n of incoming) {
const cur = list.find((x) => mergeKey(x) === mergeKey(n));
if (cur) {
// The developer agent knows the exact wording and the secret's name: its text wins.
if (o.source === "agent" || cur.source === o.source) Object.assign(cur, { title: n.title, why: n.why || cur.why, how: n.how || cur.how });
continue;
}
if (list.length >= MAX_NEEDS) break;
const id = `n${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
list.push({ id, ...n, source: o.source, story: o.story ?? null, doneAt: null });
addedIds.add(id);
}
await setSetting(db, key(projectId), list);
const all = await productNeeds(db, projectId);
return { added: all.filter((n) => addedIds.has(n.id) && n.open), all };
}
/** The owner ticks an item without a secret off (or back on). */
export async function setNeedDone(db: Db, projectId: number, id: string, done: boolean, now = new Date()): Promise<void> {
const list = await stored(db, projectId);
const n = list.find((x) => x.id === id);
if (!n) throw new PeppaError(tr("Такого пункта нет"));
n.doneAt = done ? now.toISOString() : null;
await setSetting(db, key(projectId), list);
}
/** The owner removes an item that does not apply. */
export async function removeNeed(db: Db, projectId: number, id: string): Promise<void> {
const list = (await stored(db, projectId)).filter((x) => x.id !== id);
if (list.length) await setSetting(db, key(projectId), list);
else await deleteSetting(db, key(projectId));
}
/** «что дать и куда вставить» for a message to the owner, plain text. */
export function needsText(needs: ProductNeed[], webUrl: string, projectKey: string): string {
const lines = needs.map((n, i) => {
const parts = [`${i + 1}. ${n.title}${n.why ? ` — ${n.why}` : ""}`];
if (n.how) parts.push(` ${tr("Где взять: {how}", { how: n.how })}`);
parts.push(n.secret ? ` ${tr("Куда вставить: страница проекта → карточка «Ваш продукт» → поле рядом с этим пунктом.")}` : ` ${tr("Когда сделаете — отметьте «Сделано» в карточке «Ваш продукт».")}`);
return parts.join("\n");
});
return [...lines, "", tr("Карточка «Ваш продукт»: {url}", { url: `${webUrl}/p/${projectKey}` }), tr("Ключи хранятся зашифрованными, FORGE сама передаст их продукту и перезапустит его.")].join("\n");
}
/** One line for messages and the card: «нужно: Ключ Claude API, Аккаунт Stripe». */
/** `mark` — `asIs` when the line goes into a message that is translated later (PEP-140). */
export const needsLine = (needs: Pick<ProductNeed, "title">[], mark: (s: string) => string = (s) => s) => needs.map((n) => mark(n.title)).join(", ");
/** A line for «готово к ревью»: the story is done, but the product is not real yet ("" when it is). */
export async function demoNote(db: Db, projectId: number, projectKey: string, webUrl = process.env.PEPPA_WEB_URL ?? ""): Promise<string> {
const open = await openNeeds(db, projectId).catch(() => []);
return open.length ? `${tr("⚠️ Продукт пока работает в демо-режиме. Нужно от вас: {needs}", { needs: needsLine(open, asIs) })}\n${tr("Вставить можно в карточке «Ваш продукт»: {url}", { url: `${webUrl}/p/${projectKey}` })}` : "";
}