Compare commits
No commits in common. "main" and "task/pep-294" have entirely different histories.
main
...
task/pep-2
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-261
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Тесты с агентом-моком (access-requests, bot) в песочнице молча висят по 25 с на Node 22 — нужен Node 26 из tarball и tmux из .deb в PATH/LD_LIBRARY_PATH (PEP-261).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-284
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Стандарт стека в шаблоне (PEP-284): template/docs/standards/default-stack.md — побайтная копия docs/standards/default-stack.md (тест template-default-stack); правишь стандарт — копируй в template/.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-285
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
- Аудит стека (PEP-285): docs/standards/forge-stack-audit.md — основа FORGE (TS/Node 26, Next.js, SQLite, Drizzle, целые id) сохраняется как обоснованное отклонение; условия пересмотра PostgreSQL — там же. Новый слой в default-stack.md = строка и раздел в аудите (тест stack-audit-doc).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-298
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Конфликт PR с main: первая просьба — после второго наблюдения через 2 мин (PEP-298, в тестах `PEPPA_CONFLICT_SETTLE_MIN=0`).
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-304
|
|
||||||
|
|
||||||
## Соглашения
|
|
||||||
- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки».
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
# Память: PEP-315
|
|
||||||
|
|
||||||
## Грабли
|
|
||||||
- Строка `connection_grants` остаётся после конца срока и после снятия «без дела»: читая «прошлую выдачу», проверяй `grantState(row, now) === "active"`, иначе вернёшь права, которых уже нет (PEP-315: «Дать: чтение» возвращало запись).
|
|
||||||
@ -80,8 +80,8 @@ import {
|
|||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { projects, tasks, type Db } from "@peppa/db";
|
import { projects, tasks, type Db } from "@peppa/db";
|
||||||
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
import { formatTaskKey, voiceStoriesEnabled } from "@peppa/shared";
|
||||||
import { delayAction, denyAccessRequestAndTell, grantAccessRequestByButton, resolveTaskById } from "@peppa/runner";
|
import { delayAction, denyAccessRequestAndTell, resolveTaskById } from "@peppa/runner";
|
||||||
import { accessButtonTarget, accessRequestKeyboard, decideIdleGrant, GRANT_TERM_TEXT, NO_CONNECTION_TEXT, parseAccessCallback, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
import { decideIdleGrant, parseDelayCallback, parseIdleGrantCallback } from "@peppa/core";
|
||||||
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
import { acceptTask, answerAndDeliver, classifyMessage, decideIncident, decideProposals, moveTask, postToChat, REQUEST_SENT_TEXT, requestSubscription, resumeSession, stopSession } from "@peppa/runner";
|
||||||
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
import { INTENT_TEXT, statusAnswer } from "@peppa/core";
|
||||||
import { AsyncLocalStorage } from "node:async_hooks";
|
import { AsyncLocalStorage } from "node:async_hooks";
|
||||||
@ -978,39 +978,6 @@ export function createBot(o: BotOptions) {
|
|||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-261: «Дать: чтение / полные права» → term → grant; «Назад»; «Отказать». The owner only (core: accessRequestForUser). */
|
|
||||||
async function onAccessButton(user: User, c: TgCallbackQuery): Promise<string> {
|
|
||||||
const b = parseAccessCallback(c.data ?? "");
|
|
||||||
if (!b) return tr("Неизвестная кнопка");
|
|
||||||
const keyboard = (inline_keyboard: unknown[]) =>
|
|
||||||
c.message ? api.call("editMessageReplyMarkup", { chat_id: c.message.chat.id, message_id: c.message.message_id, reply_markup: { inline_keyboard } }).catch(() => {}) : Promise.resolve();
|
|
||||||
if (b.action === "no") {
|
|
||||||
await denyAccessRequestAndTell(db, user.id, b.id, null);
|
|
||||||
await keyboard([]);
|
|
||||||
return tr("Отказано. Агент узнает об этом.");
|
|
||||||
}
|
|
||||||
if (b.action === "back") {
|
|
||||||
const canGrant = await accessButtonTarget(db, user.id, b.id).then(
|
|
||||||
() => true,
|
|
||||||
(e) => {
|
|
||||||
if (e instanceof PeppaError && e.message === NO_CONNECTION_TEXT) return false;
|
|
||||||
throw e;
|
|
||||||
},
|
|
||||||
);
|
|
||||||
await keyboard(accessRequestKeyboard(b.id, { step: "rights", canGrant }));
|
|
||||||
return tr("Выберите, что дать агенту");
|
|
||||||
}
|
|
||||||
if (b.action === "rights") {
|
|
||||||
await accessButtonTarget(db, user.id, b.id); // not the owner, decided already or no connection → the refusal is the toast
|
|
||||||
await keyboard(accessRequestKeyboard(b.id, { step: "term", rights: b.rights }));
|
|
||||||
return tr("Выберите срок");
|
|
||||||
}
|
|
||||||
await grantAccessRequestByButton(db, user.id, b.id, { rights: b.rights, term: b.term });
|
|
||||||
await keyboard([]);
|
|
||||||
const what = b.rights === "full" ? tr("полные права") : tr("чтение");
|
|
||||||
return tr("Готово: {what}, {term}. Агент узнает об этом.", { what, term: GRANT_TERM_TEXT[b.term] });
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onDelayButton(user: User, data: string): Promise<string> {
|
async function onDelayButton(user: User, data: string): Promise<string> {
|
||||||
const b = parseDelayCallback(data);
|
const b = parseDelayCallback(data);
|
||||||
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
|
if (!b || !(await isSuperadmin(db, user))) return tr("Неизвестная кнопка");
|
||||||
@ -1052,10 +1019,12 @@ export function createBot(o: BotOptions) {
|
|||||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
// PEP-250/261: buttons under an agent's access request — `ar:<id>:no` (refuse), `ar:<id>:r|f` (rights →
|
// PEP-250: «Отказать» under an agent's access request: `ar:<id>:no` — only the project's owner (core checks).
|
||||||
// term buttons), `ar:<id>:r|f:<term>` (grant), `ar:<id>:back`. Only the project's owner (core checks).
|
|
||||||
if (parts[0] === "ar") {
|
if (parts[0] === "ar") {
|
||||||
const toast = await onAccessButton(user, c).catch((e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))));
|
const toast = await denyAccessRequestAndTell(db, user.id, Number(parts[1]), null).then(
|
||||||
|
() => tr("Отказано. Агент узнает об этом."),
|
||||||
|
(e) => (e instanceof PeppaError ? e.message : (log(`access request: ${(e as Error).stack ?? e}`), tr("Ошибка"))),
|
||||||
|
);
|
||||||
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
await api.answerCallbackQuery(c.id, toast.slice(0, 190)).catch((e) => log(`answerCallbackQuery: ${e.message}`));
|
||||||
return "done";
|
return "done";
|
||||||
}
|
}
|
||||||
|
|||||||
@ -71,7 +71,7 @@ import {
|
|||||||
} from "@peppa/core";
|
} from "@peppa/core";
|
||||||
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
import { checkConnection, createConnection, decideIdleGrant, deleteConnection, DEFAULT_GRANT_TERM, extendGrant, grantConnection, isGatewayProtocol, isGrantTerm, replaceConnectionSecret, resetHostKey, revokeConnection, revokeGrant, setConnectionIdleHours, type CatalogAuth, type ConnectionCheckResult, type GrantMode, type GrantTerm } from "@peppa/core";
|
||||||
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
import { attachmentLabel, fixFeedback, linkAttachments, linkFeedback, parseAttachmentIds, rejectFeedback, restoreProject } from "@peppa/core";
|
||||||
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestByButton, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
import { deleteProject, decideProposals, mergeProposals, connectAndGrantAccessRequest, denyAccessRequestAndTell, grantAccessRequestFromExisting, decideDeferred } from "@peppa/runner";
|
||||||
import { bugsinkFromEnv } from "@peppa/bugsink";
|
import { bugsinkFromEnv } from "@peppa/bugsink";
|
||||||
import { loadEnv } from "@peppa/shared";
|
import { loadEnv } from "@peppa/shared";
|
||||||
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
import { pauseProject, resumeProject, acceptAll, acceptStory, autoPublish, fixStory, confirmTaskDecision, changeTaskDecision, undoSplit, budgetChanged, resolveTaskById, deployProd, bugsinkWebhookBase, connectErrorTracking, decideIncident, resolveIncident, acceptTask, answerAndDeliver, grantRepoAccess, moveTask, provisionProjectOnce, projectNamespace, setProjectVisibility, shareProject, unshareProject, type BoardColumn, resumeSession, sendToSession, syncSessionAttachments, startSession, stopSession, type Provider, startFreeRunner, renameRunner, promoteRunner, queueTaskOnRunner, managesProject, saveAgentsMd, cancelOwnLogin, finishOwnClaudeLogin, connectOwnSubscription, removeOwnSubscription, type OwnSubscriptionKind, chooseSharedSubscription, requestSubscription } from "@peppa/runner";
|
||||||
@ -1141,12 +1141,6 @@ export async function setConnectionIdleAction(f: FormData) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// PEP-261: rights and term chosen by the owner («Дать: чтение / полные права», срок — 1 день по умолчанию).
|
|
||||||
function grantChoice(f: FormData): { rights?: "read" | "full"; term: GrantTerm } {
|
|
||||||
const rights = str(f, "rights");
|
|
||||||
return { rights: rights === "full" || rights === "read" ? rights : undefined, term: isGrantTerm(str(f, "term")) ? (str(f, "term") as GrantTerm) : DEFAULT_GRANT_TERM };
|
|
||||||
}
|
|
||||||
|
|
||||||
// PEP-250: an agent's access request — only its project's owner decides (core checks).
|
// PEP-250: an agent's access request — only its project's owner decides (core checks).
|
||||||
export async function connectAccessRequestAction(f: FormData) {
|
export async function connectAccessRequestAction(f: FormData) {
|
||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
@ -1159,7 +1153,7 @@ export async function connectAccessRequestAction(f: FormData) {
|
|||||||
secret: String(f.get("secret") ?? "").trim(),
|
secret: String(f.get("secret") ?? "").trim(),
|
||||||
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
authKind: AUTH_KINDS.includes(kind) ? kind : "bearer",
|
||||||
authHeader: str(f, "authHeader") || null,
|
authHeader: str(f, "authHeader") || null,
|
||||||
}, grantChoice(f));
|
});
|
||||||
const r = await checkConnection(db, user.id, connection.id).catch(() => null);
|
const r = await checkConnection(db, user.id, connection.id).catch(() => null);
|
||||||
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
|
return `/connections/requests/${id}?done=granted&check=${checkWord(r)}`;
|
||||||
});
|
});
|
||||||
@ -1169,17 +1163,7 @@ export async function grantAccessRequestAction(f: FormData) {
|
|||||||
const user = asWebActor(await requireUser());
|
const user = asWebActor(await requireUser());
|
||||||
await attempt(f, async () => {
|
await attempt(f, async () => {
|
||||||
const id = Number(str(f, "requestId"));
|
const id = Number(str(f, "requestId"));
|
||||||
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")), grantChoice(f));
|
await grantAccessRequestFromExisting(db, user.id, id, Number(str(f, "connectionId")));
|
||||||
return `/connections/requests/${id}?done=granted`;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-261: «Дать: чтение / полные права» with a term in «Агенты просят доступ». */
|
|
||||||
export async function grantAccessButtonAction(f: FormData) {
|
|
||||||
const user = asWebActor(await requireUser());
|
|
||||||
await attempt(f, async () => {
|
|
||||||
const id = Number(str(f, "requestId"));
|
|
||||||
await grantAccessRequestByButton(db, user.id, id, grantChoice(f));
|
|
||||||
return `/connections/requests/${id}?done=granted`;
|
return `/connections/requests/${id}?done=granted`;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,7 +18,6 @@ import {
|
|||||||
listConnections,
|
listConnections,
|
||||||
listUserProjects,
|
listUserProjects,
|
||||||
ownerAccessRequests,
|
ownerAccessRequests,
|
||||||
connectionsForRequest,
|
|
||||||
oauthOffer,
|
oauthOffer,
|
||||||
scopeLabel,
|
scopeLabel,
|
||||||
searchCatalog,
|
searchCatalog,
|
||||||
@ -653,8 +652,6 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
|||||||
const t = await getT();
|
const t = await getT();
|
||||||
const engineer = (await uiMode()) === "engineer";
|
const engineer = (await uiMode()) === "engineer";
|
||||||
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
|
const [list, journal, projects, agents, requests] = await Promise.all([listConnections(db, user.id), connectionJournal(db, user.id, { limit: 50 }), listUserProjects(db, user.id), grantableAgents(db), ownerAccessRequests(db, user.id)]);
|
||||||
// PEP-261: «Дать» right in the list — only where a fitting connection exists.
|
|
||||||
const grantable = new Set((await Promise.all(requests.map(async (r) => ((await connectionsForRequest(db, user.id, r)).fit.length ? r.id : 0)))).filter(Boolean));
|
|
||||||
const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
|
const proto = q.service?.startsWith("proto:") ? (GATEWAY_PROTOCOLS as string[]).find((p) => `proto:${p}` === q.service) as GatewayProtocol | undefined : undefined;
|
||||||
const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
|
const chosen = q.service === "custom" ? "custom" : catalogService(q.service);
|
||||||
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
const kind = q.kind && (CATALOG_KINDS as string[]).includes(q.kind) ? q.kind : null;
|
||||||
@ -671,7 +668,7 @@ export default async function ConnectionsPage({ searchParams }: { searchParams:
|
|||||||
|
|
||||||
{requests.length > 0 && (
|
{requests.length > 0 && (
|
||||||
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
|
<Section id="requests" title={t("Агенты просят доступ")} count={requests.length}>
|
||||||
<AccessRequestList list={requests} grantable={grantable} t={t} />
|
<AccessRequestList list={requests} t={t} />
|
||||||
</Section>
|
</Section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
|||||||
@ -1,9 +1,9 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { ExternalLink, KeyRound } from "lucide-react";
|
import { ExternalLink, KeyRound } from "lucide-react";
|
||||||
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
|
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
|
||||||
import type { Translator } from "@peppa/shared/i18n";
|
import type { Translator } from "@peppa/shared/i18n";
|
||||||
import { AccessStatus, accessModeText, GrantRightsSelect, GrantTermSelect } from "@/components/AccessRequests";
|
import { AccessStatus, accessModeText } from "@/components/AccessRequests";
|
||||||
import { Hidden } from "@/components/cards";
|
import { Hidden } from "@/components/cards";
|
||||||
import { Flash, Notice, PageHeader, Section } from "@/components/common";
|
import { Flash, Notice, PageHeader, Section } from "@/components/common";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@ -42,17 +42,6 @@ function DoneNotice({ done, check, t }: { done?: string; check?: string; t: Tran
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-261: rights and term of the grant (1 day by default). */
|
|
||||||
function GrantFields({ r, t }: { r: AccessRequestView; t: Translator }) {
|
|
||||||
return (
|
|
||||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
|
||||||
<GrantRightsSelect r={r} t={t} />
|
|
||||||
<span className="text-muted-foreground">{t("на срок")}</span>
|
|
||||||
<GrantTermSelect t={t} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogService | null; t: Translator }) {
|
||||||
const back = `/connections/requests/${r.id}`;
|
const back = `/connections/requests/${r.id}`;
|
||||||
return (
|
return (
|
||||||
@ -87,7 +76,6 @@ function ConnectForm({ r, card, t }: { r: AccessRequestView; card: CatalogServic
|
|||||||
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
<Input name="authHeader" placeholder="X-Api-Key" aria-label={t("Имя заголовка или параметра")} className="max-w-48 font-mono" spellCheck={false} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<GrantFields r={r} t={t} />
|
|
||||||
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
|
<Button size="sm" className="self-start">{t("Подключить и разрешить")}</Button>
|
||||||
</form>
|
</form>
|
||||||
</li>
|
</li>
|
||||||
@ -109,7 +97,6 @@ function ExistingForm({ r, fit, other, t }: { r: AccessRequestView; fit: Connect
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
<GrantFields r={r} t={t} />
|
|
||||||
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
<Button size="sm" variant="secondary">{t("Разрешить из уже подключённого")}</Button>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
@ -168,7 +155,9 @@ export default async function AccessRequestPage({ params, searchParams }: { para
|
|||||||
<Card className="p-4">
|
<Card className="p-4">
|
||||||
<ConnectForm r={r} card={card} t={t} />
|
<ConnectForm r={r} card={card} t={t} />
|
||||||
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
<p className="m-0 mt-3 text-xs text-muted-foreground">
|
||||||
{t("Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».")}
|
{r.mode === "write"
|
||||||
|
? t("Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")
|
||||||
|
: t("Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».")}
|
||||||
</p>
|
</p>
|
||||||
</Card>
|
</Card>
|
||||||
</Section>
|
</Section>
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { MessageCircleQuestion } from "lucide-react";
|
import { MessageCircleQuestion } from "lucide-react";
|
||||||
import { isSuperadmin } from "@peppa/core";
|
import { isSuperadmin } from "@peppa/core";
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// PEP-218: the card of one production error, read from Bugsink on the server. The superadmin
|
// PEP-218: the card of one production error, read from Bugsink on the server. The superadmin
|
||||||
// opens any error, a project's owner or member — errors of that project only (else 404).
|
// opens any error, a project's owner or member — errors of that project only (else 404).
|
||||||
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
|
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Bug, ExternalLink } from "lucide-react";
|
import { Bug, ExternalLink } from "lucide-react";
|
||||||
@ -47,8 +46,8 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
|
|||||||
<ErrorStateBadge state={r.state} t={t} />
|
<ErrorStateBadge state={r.state} t={t} />
|
||||||
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||||
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
|
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
|
||||||
<span className="text-muted-foreground" title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
<span className="text-muted-foreground" title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||||
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
<span className="text-muted-foreground" title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-sm">
|
<div className="text-sm">
|
||||||
{r.taskKey ? (
|
{r.taskKey ? (
|
||||||
@ -110,7 +109,7 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
|
|||||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
{d.events.map((e) => (
|
{d.events.map((e) => (
|
||||||
<li key={e.id} className="flex gap-3">
|
<li key={e.id} className="flex gap-3">
|
||||||
<span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium", timeZone: platformZone() })}</span>
|
<span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium" })}</span>
|
||||||
<span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span>
|
<span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// glossary-ignore-file: the section is for the superadmin only.
|
// glossary-ignore-file: the section is for the superadmin only.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
||||||
@ -27,7 +26,7 @@ export async function generateMetadata() {
|
|||||||
return pageTitle(t, t("Мониторинг"));
|
return pageTitle(t, t("Мониторинг"));
|
||||||
}
|
}
|
||||||
|
|
||||||
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZone: platformZone() });
|
const when = (iso: string) => new Date(iso).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||||
|
|
||||||
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
|
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
|
||||||
const user = await requireUser();
|
const user = await requireUser();
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// glossary-ignore-file: the section is for the superadmin only.
|
// glossary-ignore-file: the section is for the superadmin only.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
import { Activity, Pause, Play, Plus } from "lucide-react";
|
||||||
@ -84,7 +83,7 @@ async function SmokeSection({ t }: { t: Awaited<ReturnType<typeof getT>> }) {
|
|||||||
skipped: [t("не проверен"), "text-muted-foreground"],
|
skipped: [t("не проверен"), "text-muted-foreground"],
|
||||||
};
|
};
|
||||||
const TRIGGER = { deploy: t("после выкатки"), hourly: t("плановая"), manual: t("по запросу") } as const;
|
const TRIGGER = { deploy: t("после выкатки"), hourly: t("плановая"), manual: t("по запросу") } as const;
|
||||||
const when = (r: SmokeRun) => new Date(r.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
const when = (r: SmokeRun) => new Date(r.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
|
||||||
return (
|
return (
|
||||||
<Section
|
<Section
|
||||||
title={t("Запуск агентов")}
|
title={t("Запуск агентов")}
|
||||||
@ -288,7 +287,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
|||||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||||
{flog.map((e) => (
|
{flog.map((e) => (
|
||||||
<li key={e.id} className="flex flex-wrap gap-2">
|
<li key={e.id} className="flex flex-wrap gap-2">
|
||||||
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() })}</span>
|
<span className="text-muted-foreground">{new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
|
||||||
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
|
<span className={e.state === "unavailable" ? "text-destructive" : "text-ok"}>{e.state === "unavailable" ? t("отключена") : t("снова включена")}</span>
|
||||||
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
|
<span className="font-medium">{t(FEATURES[e.name].label)}</span>
|
||||||
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
|
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { Fragment } from "react";
|
import { Fragment } from "react";
|
||||||
import { ProductCard } from "@/components/ProductCard";
|
import { ProductCard } from "@/components/ProductCard";
|
||||||
@ -779,7 +778,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
|||||||
))}
|
))}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
<td className="px-3 py-2 text-right whitespace-nowrap text-muted-foreground">
|
||||||
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() })}
|
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" })}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
|
// PEP-42: plan an epic — the planner proposes stories with dependencies; the PM edits and approves.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
import { Sparkles } from "lucide-react";
|
import { Sparkles } from "lucide-react";
|
||||||
@ -110,7 +109,7 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
|
|||||||
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
||||||
</form>
|
</form>
|
||||||
<p className="m-0 text-xs text-muted-foreground">
|
<p className="m-0 text-xs text-muted-foreground">
|
||||||
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }), author: draft.createdBy })}
|
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }), author: draft.createdBy })}
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
// Project page tabs «Код», «Спеки», «PR» and the epics block of «⋯ Настройки проекта» (PEP-66).
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import type { Words } from "@peppa/shared/wording";
|
import type { Words } from "@peppa/shared/wording";
|
||||||
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
import { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
||||||
import type { Epic, SpecSummary } from "@peppa/core";
|
import type { Epic, SpecSummary } from "@peppa/core";
|
||||||
@ -14,7 +13,7 @@ import { Input, Textarea } from "@/components/ui/input";
|
|||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
import { intlLocale, type Translator } from "@peppa/shared/i18n";
|
||||||
|
|
||||||
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }) : "—");
|
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short" }) : "—");
|
||||||
|
|
||||||
export async function CodeTab({ code }: { code: RepoOverview }) {
|
export async function CodeTab({ code }: { code: RepoOverview }) {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
|
|||||||
@ -1,16 +1,11 @@
|
|||||||
import Link from "@/components/Link";
|
import Link from "next/link";
|
||||||
import { KeyRound } from "lucide-react";
|
import { KeyRound } from "lucide-react";
|
||||||
import { DEFAULT_GRANT_TERM, GRANT_TERM_TEXT, GRANT_TERMS, type AccessRequestView } from "@peppa/core";
|
import type { AccessRequestView } from "@peppa/core";
|
||||||
import type { Translator } from "@peppa/shared/i18n";
|
import type { Translator } from "@peppa/shared/i18n";
|
||||||
import { denyAccessRequestAction, grantAccessButtonAction } from "@/app/(app)/actions";
|
|
||||||
import { Hidden } from "@/components/cards";
|
|
||||||
import { ago } from "@/components/common";
|
import { ago } from "@/components/common";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Card } from "@/components/ui/card";
|
import { Card } from "@/components/ui/card";
|
||||||
|
|
||||||
const SELECT = "h-9 rounded-md border border-input bg-background px-2 text-sm";
|
|
||||||
|
|
||||||
/** «читать» / «читать и менять». */
|
/** «читать» / «читать и менять». */
|
||||||
export function accessModeText(mode: AccessRequestView["mode"], t: Translator): string {
|
export function accessModeText(mode: AccessRequestView["mode"], t: Translator): string {
|
||||||
return mode === "write" ? t("читать и менять") : t("только читать");
|
return mode === "write" ? t("читать и менять") : t("только читать");
|
||||||
@ -23,31 +18,8 @@ export function AccessStatus({ r, t }: { r: AccessRequestView; t: Translator })
|
|||||||
return <Badge variant="outline">{t("агент отменил запрос")}</Badge>;
|
return <Badge variant="outline">{t("агент отменил запрос")}</Badge>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-261: the term of a grant — 1 day by default. */
|
/** PEP-250: «Агенты просят доступ» on «Подключения» — the owner's open requests. */
|
||||||
export function GrantTermSelect({ t }: { t: Translator }) {
|
export function AccessRequestList({ list, t }: { list: AccessRequestView[]; t: Translator }) {
|
||||||
return (
|
|
||||||
<select name="term" defaultValue={DEFAULT_GRANT_TERM} aria-label={t("Срок")} className={SELECT}>
|
|
||||||
{GRANT_TERMS.map((term) => (
|
|
||||||
<option key={term} value={term}>
|
|
||||||
{t.text(GRANT_TERM_TEXT[term])}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-261: «чтение» / «полные права» — by default what the agent asked for. */
|
|
||||||
export function GrantRightsSelect({ r, t }: { r: AccessRequestView; t: Translator }) {
|
|
||||||
return (
|
|
||||||
<select name="rights" defaultValue={r.mode === "write" ? "full" : "read"} aria-label={t("Что можно")} className={SELECT}>
|
|
||||||
<option value="read">{t("Чтение")}</option>
|
|
||||||
<option value="full">{t("Полные права: чтение и изменения")}</option>
|
|
||||||
</select>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-250/261: «Агенты просят доступ» on «Подключения» — the owner's open requests with «Дать» buttons. `grantable` — requests with a fitting connection. */
|
|
||||||
export function AccessRequestList({ list, grantable, t }: { list: AccessRequestView[]; grantable: Set<number>; t: Translator }) {
|
|
||||||
return (
|
return (
|
||||||
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
<ul className="m-0 flex list-none flex-col gap-2 p-0">
|
||||||
{list.map((r) => (
|
{list.map((r) => (
|
||||||
@ -64,31 +36,6 @@ export function AccessRequestList({ list, grantable, t }: { list: AccessRequestV
|
|||||||
<Link href={`/connections/requests/${r.id}`} className="ml-auto text-primary underline-offset-2 hover:underline">
|
<Link href={`/connections/requests/${r.id}`} className="ml-auto text-primary underline-offset-2 hover:underline">
|
||||||
{t("Посмотреть и решить")}
|
{t("Посмотреть и решить")}
|
||||||
</Link>
|
</Link>
|
||||||
<div className="flex basis-full flex-wrap items-center gap-2 pt-1">
|
|
||||||
{grantable.has(r.id) ? (
|
|
||||||
<form action={grantAccessButtonAction} className="flex flex-wrap items-center gap-2">
|
|
||||||
<Hidden fields={{ back: "/connections#requests", requestId: r.id }} />
|
|
||||||
<Button size="sm" name="rights" value="read" data-access-grant="read">
|
|
||||||
{t("Дать: чтение")}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="secondary" name="rights" value="full" data-access-grant="full">
|
|
||||||
{t("Дать: полные права")}
|
|
||||||
</Button>
|
|
||||||
<span className="text-muted-foreground">{t("на срок")}</span>
|
|
||||||
<GrantTermSelect t={t} />
|
|
||||||
</form>
|
|
||||||
) : (
|
|
||||||
<Button asChild size="sm">
|
|
||||||
<Link href={`/connections/requests/${r.id}`}>{t("Подключить")}</Link>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<form action={denyAccessRequestAction}>
|
|
||||||
<Hidden fields={{ back: "/connections#requests", requestId: r.id }} />
|
|
||||||
<Button size="sm" variant="outline">
|
|
||||||
{t("Отказать")}
|
|
||||||
</Button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</Card>
|
</Card>
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
|
// Accounting blocks (PEP-5/43/47/48): the usage strip on top, story budget, project metrics, journal.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import { Gauge, Hourglass, Play } from "lucide-react";
|
import { Gauge, Hourglass, Play } from "lucide-react";
|
||||||
@ -75,7 +74,7 @@ function WindowCell({ label, w, t }: { label: string; w: WindowView | null; t: T
|
|||||||
function accountTitle(a: AccountUsage, t: Translator): string {
|
function accountTitle(a: AccountUsage, t: Translator): string {
|
||||||
const w = (l: string, v: WindowView | null) => (!v ? t("{label}: нет данных", { label: l }) : v.reset ? t("{label}: сброшено", { label: l }) : `${l}: ${Math.round(v.pct!)}%`);
|
const w = (l: string, v: WindowView | null) => (!v ? t("{label}: нет данных", { label: l }) : v.reset ? t("{label}: сброшено", { label: l }) : `${l}: ${Math.round(v.pct!)}%`);
|
||||||
const limited = a.limitedUntil ? ", " + t("в лимите") : "";
|
const limited = a.limitedUntil ? ", " + t("в лимите") : "";
|
||||||
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale), { timeZone: platformZone() }) }) : "";
|
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale)) }) : "";
|
||||||
return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated;
|
return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the
|
// PEP-218: production errors read from Bugsink on the server — summary, filters, rows and the
|
||||||
// error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases,
|
// error card blocks. «Инженер» and the superadmin (`tech`) also see code places, releases,
|
||||||
// stacks and tags; «Продакт» — the title, how often, when and the bug task.
|
// stacks and tags; «Продакт» — the title, how often, when and the bug task.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { Bug, TrendingUp } from "lucide-react";
|
import { Bug, TrendingUp } from "lucide-react";
|
||||||
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
|
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
|
||||||
@ -17,7 +16,7 @@ import { errorAction } from "@/app/(app)/errors/actions";
|
|||||||
const STATE_LABEL: Record<ErrorState, string> = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") };
|
const STATE_LABEL: Record<ErrorState, string> = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") };
|
||||||
const STATE_TONE: Record<ErrorState, "danger" | "ok" | "muted"> = { unresolved: "danger", resolved: "ok", muted: "muted" };
|
const STATE_TONE: Record<ErrorState, "danger" | "ok" | "muted"> = { unresolved: "danger", resolved: "ok", muted: "muted" };
|
||||||
|
|
||||||
const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||||
|
|
||||||
/** Bugsink failed: say so; the data below (if any) is from the cache. */
|
/** Bugsink failed: say so; the data below (if any) is from the cache. */
|
||||||
export function ErrorsDown({ down, at, tech, t }: { down: boolean; at: Date | null; tech: boolean; t: Translator }) {
|
export function ErrorsDown({ down, at, tech, t }: { down: boolean; at: Date | null; tech: boolean; t: Translator }) {
|
||||||
@ -92,8 +91,8 @@ export function ErrorRows({ rows, tech, from, t, showProject = true }: { rows: E
|
|||||||
{tech && r.culprit ? <span className="max-w-full truncate font-mono">{r.culprit}</span> : null}
|
{tech && r.culprit ? <span className="max-w-full truncate font-mono">{r.culprit}</span> : null}
|
||||||
{showProject ? <span>{r.bugsinkName}</span> : null}
|
{showProject ? <span>{r.bugsinkName}</span> : null}
|
||||||
<span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
<span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||||
<span title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
<span title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||||
<span title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
<span title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||||
{/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */}
|
{/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */}
|
||||||
{tech && r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null}
|
{tech && r.release ? <span className="font-mono" title={r.release}>{t("релиз {sha}", { sha: r.release.slice(0, 8) })}</span> : null}
|
||||||
{r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null}
|
{r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null}
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
|
// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
|
||||||
// glossary-ignore-file: the section is for the superadmin only.
|
// glossary-ignore-file: the section is for the superadmin only.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import { durationText, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
|
import { durationText, FEATURE_NAMES, FEATURES, type MonitorKind, type MonitorState, type MonitorView } from "@peppa/core";
|
||||||
import type { Translator } from "@peppa/shared/i18n";
|
import type { Translator } from "@peppa/shared/i18n";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
@ -27,7 +26,7 @@ export function CheckStrip({ recent, t }: { recent: MonitorView["recent"]; t: Tr
|
|||||||
<span key={`e${i}`} className="h-full w-1.5 rounded-sm bg-muted" />
|
<span key={`e${i}`} className="h-full w-1.5 rounded-sm bg-muted" />
|
||||||
))}
|
))}
|
||||||
{recent.map((c) => (
|
{recent.map((c) => (
|
||||||
<span key={c.at} title={new Date(c.at).toLocaleString("ru-RU", { timeZone: platformZone() })} className={cn("h-full w-1.5 rounded-sm", !c.ok ? "bg-destructive" : c.degraded ? "bg-warn" : "bg-ok")} />
|
<span key={c.at} title={new Date(c.at).toLocaleString("ru-RU")} className={cn("h-full w-1.5 rounded-sm", !c.ok ? "bg-destructive" : c.degraded ? "bg-warn" : "bg-ok")} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@ -126,4 +125,4 @@ export function OutageLine({ m, t, now = new Date() }: { m: MonitorView; t: Tran
|
|||||||
return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>;
|
return <span className={m.state === "down" ? "text-destructive" : "text-warn"}>{parts.join(" · ")}</span>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
|
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
|
||||||
import { delayActionForm } from "@/app/(app)/dashboard/actions";
|
import { delayActionForm } from "@/app/(app)/dashboard/actions";
|
||||||
@ -14,7 +13,7 @@ import { getT } from "@/lib/i18n";
|
|||||||
*/
|
*/
|
||||||
export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) {
|
export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) {
|
||||||
const t = await getT();
|
const t = await getT();
|
||||||
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
return (
|
return (
|
||||||
<ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays>
|
<ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays>
|
||||||
{delays.map((d) => (
|
{delays.map((d) => (
|
||||||
|
|||||||
@ -1,4 +1,3 @@
|
|||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import type { PoolOverview, PoolSubscriptionState } from "@peppa/core";
|
import type { PoolOverview, PoolSubscriptionState } from "@peppa/core";
|
||||||
@ -6,7 +5,7 @@ import { intlLocale, type Locale } from "@peppa/shared/i18n";
|
|||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
import { getT } from "@/lib/i18n";
|
import { getT } from "@/lib/i18n";
|
||||||
|
|
||||||
const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
const KIND: Record<PoolSubscriptionState["provider"], string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" };
|
const KIND: Record<PoolSubscriptionState["provider"], string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" };
|
||||||
|
|
||||||
function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "primary" {
|
function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "primary" {
|
||||||
@ -76,7 +75,7 @@ export async function PoolSwitches({ o }: { o: PoolOverview }) {
|
|||||||
<span className="font-medium text-foreground">{t("Переключения")}</span>
|
<span className="font-medium text-foreground">{t("Переключения")}</span>
|
||||||
{o.switches.map((x, i) => (
|
{o.switches.map((x, i) => (
|
||||||
<span key={i}>
|
<span key={i}>
|
||||||
{x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: platformZone() })}
|
{x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined })}
|
||||||
{" · "}
|
{" · "}
|
||||||
{x.taskKey ? <Link href={`/t/${x.taskKey}`}>{x.taskKey}</Link> : t("агент №{id}", { id: x.sessionId ?? "?" })}
|
{x.taskKey ? <Link href={`/t/${x.taskKey}`}>{x.taskKey}</Link> : t("агент №{id}", { id: x.sessionId ?? "?" })}
|
||||||
{": "}
|
{": "}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// Domain cards shared by pages: agent questions, runners, project list.
|
// Domain cards shared by pages: agent questions, runners, project list.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import Link from "@/components/Link";
|
import Link from "@/components/Link";
|
||||||
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
|
import { BellRing, CircleCheck, CircleHelp, FileCheck, Hourglass, Play, RotateCcw, Send, ShieldQuestion, Square, SquareTerminal } from "lucide-react";
|
||||||
import { pausedProjectIds, messageDetails, questionAuthor, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
import { pausedProjectIds, messageDetails, questionAuthor, questionDetails, questionIsFreeText, questionState, questionText, questionType, splitForDisplay, trashDaysLeft, type Project, type Question, type SessionView, type StepView } from "@peppa/core";
|
||||||
@ -359,4 +358,4 @@ export async function ProjectList({ projects, userId, engineer = false, analyst,
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const hhmm = (d: Date) => new Date(d).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
const hhmm = (d: Date) => new Date(d).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||||
|
|||||||
@ -10,8 +10,7 @@
|
|||||||
- **Ориентир для новых проектов.** Агент, который выбирает стек нового проекта или нового
|
- **Ориентир для новых проектов.** Агент, который выбирает стек нового проекта или нового
|
||||||
сервиса, берёт его отсюда, если у продукта нет причины поступить иначе.
|
сервиса, берёт его отсюда, если у продукта нет причины поступить иначе.
|
||||||
- **Не требование миграции.** Существующие проекты (и сама FORGE на TypeScript/Node.js/SQLite)
|
- **Не требование миграции.** Существующие проекты (и сама FORGE на TypeScript/Node.js/SQLite)
|
||||||
не переписываются под стандарт. Сравнение FORGE со стандартом —
|
не переписываются под стандарт. Сравнение FORGE со стандартом — отдельная задача (PEP-285).
|
||||||
`docs/standards/forge-stack-audit.md` в репозитории платформы (PEP-285).
|
|
||||||
- **Отклонения разрешены**, если они обоснованы и записаны (раздел «Правило отклонений»).
|
- **Отклонения разрешены**, если они обоснованы и записаны (раздел «Правило отклонений»).
|
||||||
- Стек проекта, уже записанный в его `AGENTS.md`, `design.md` или памяти проекта, важнее стандарта.
|
- Стек проекта, уже записанный в его `AGENTS.md`, `design.md` или памяти проекта, важнее стандарта.
|
||||||
|
|
||||||
|
|||||||
@ -1,328 +0,0 @@
|
|||||||
# Аудит стека FORGE относительно FORGE Default Stack
|
|
||||||
|
|
||||||
Задача: PEP-285 · снимок: `main` b664e6ad, 2026-11-27 · стандарт: [`default-stack.md`](default-stack.md) 1.0.0
|
|
||||||
|
|
||||||
Аудит **ничего не меняет** в коде, базе и выкатке платформы. Это разбор «как есть → как в стандарте»
|
|
||||||
с рекомендациями; решения — в конце, у владельца.
|
|
||||||
|
|
||||||
## Как читать
|
|
||||||
|
|
||||||
- **Статус**: соответствует · частично · отклонение · неприменимо.
|
|
||||||
- **Трудоёмкость** изменения: S — до 2 дней агента, M — до 2 недель, L — месяц и больше,
|
|
||||||
XL — переписывание значительной части платформы.
|
|
||||||
- **Приоритет**: P1 — взять в ближайшие задачи, P2 — сделать по поводу (когда трогаем слой),
|
|
||||||
P3 — не делать без нового повода, «сохранить» — осознанно оставить текущий стек.
|
|
||||||
- Цифры сняты командами в корне репозитория (команда указана рядом), их можно пересчитать.
|
|
||||||
|
|
||||||
Масштаб платформы: ~119 тыс. строк TypeScript (`find packages apps -name '*.ts' -o -name '*.tsx' | xargs wc -l`),
|
|
||||||
41 таблица (`grep -c 'sqliteTable(' packages/db/src/schema.ts`), 36 миграций, 176 файлов e2e-тестов
|
|
||||||
(`ls packages/testkit/test`), сервисы web · bot · watchdog · observer · tmux в одном образе.
|
|
||||||
|
|
||||||
**Про «Bun».** В стандарте Bun — Go ORM `uptrace/bun`. В PEP-36 рассматривался JavaScript-рантайм Bun
|
|
||||||
(`bun:sqlite`) и был отвергнут в пользу Node 26. Это разные вещи; в этом отчёте «Bun» = Go ORM.
|
|
||||||
|
|
||||||
## Сводка по слоям
|
|
||||||
|
|
||||||
| Слой | Сейчас в FORGE | Стандарт | Статус | Трудоёмкость | Приоритет |
|
|
||||||
|---|---|---|---|---|---|
|
|
||||||
| Бэкенд: Go | TypeScript на Node 26 (встроенное снятие типов, без сборки) | Go | отклонение | XL | сохранить |
|
|
||||||
| HTTP: Gin | Next.js Route Handlers + Server Actions, свой `apps/web/server.ts` (WebSocket) | Gin | отклонение | XL | сохранить |
|
|
||||||
| Доступ к данным: Bun | Drizzle ORM 0.45 поверх `node:sqlite` (своя прослойка) | Bun (`uptrace/bun`) | отклонение | XL | сохранить |
|
|
||||||
| Конфигурация: Viper | `process.env` по месту: 214 имён, из них 22 в `shared/env.ts` | Viper, конфиг читается один раз | частично | M | P2 |
|
|
||||||
| База данных: PostgreSQL | SQLite (WAL): `peppa.db`, `history.db`, `observe.db` | PostgreSQL | отклонение | L | сохранить |
|
|
||||||
| Идентификаторы: UUIDv7 | целые автоинкрементные ключи | UUIDv7 | отклонение | L | сохранить |
|
|
||||||
| Наблюдение за запросами: pg_stat_statements | нет PostgreSQL; медленные запросы — `core/request-timing.ts` + probe в `packages/db` | pg_stat_statements | неприменимо | — | — |
|
|
||||||
| Публичный сайт: Next.js App Router | Next.js 16 App Router: `/login`, `/mcp-guide` | Next.js App Router | соответствует | — | — |
|
|
||||||
| Аналитика: GA4 | нет | GA4 только у публичного сайта | неприменимо | — | — |
|
|
||||||
| CDN: Cloudflare CDN | весь трафик через Cloudflare (туннель, DNS — `core/edge-dns.ts`) | только публичный сайт и статика | частично | S | P3 |
|
|
||||||
| Защита форм: Cloudflare Turnstile | нет; публичных форм с вводом нет (вход — eGov QR / Google) | только публичные формы | неприменимо | — | — |
|
|
||||||
| Веб-приложение: React + TanStack + Vite | Next.js App Router за входом (серверные компоненты, свой живой канал) | React + TanStack + Vite | отклонение | XL | сохранить |
|
|
||||||
| Код и проверки: Gitea или Forgejo | Gitea 1.22 + Actions, `act_runner` 0.2.11 | Gitea или Forgejo | соответствует | M | P2 |
|
|
||||||
| Ошибки: Bugsink | Bugsink 2.6.3 (SQLite); отправка — свой отправитель конвертов Sentry без SDK | Bugsink, SDK Sentry | частично | S | P3 |
|
|
||||||
| Логи и метрики: Loki + Grafana | текстовые журналы сервисов в файлах, свой мониторинг (`observe.db`) | Loki + Grafana, JSON-логи | отклонение | M | P1 |
|
|
||||||
| Контейнеры: Docker | один образ `peppa/platform`, compose, агенты в контейнерах | Docker + Compose | соответствует | M | P2 |
|
|
||||||
|
|
||||||
Итого: соответствует — 3, частично — 3, отклонение — 7, неприменимо — 3.
|
|
||||||
Шесть из семи отклонений — одно решение (язык/рантайм/база платформы, PEP-36 и раньше); его
|
|
||||||
рекомендуем сохранить. Единственное отклонение, которое стоит закрывать, — логи и метрики.
|
|
||||||
|
|
||||||
## Слои
|
|
||||||
|
|
||||||
### Бэкенд: Go
|
|
||||||
|
|
||||||
- **Сейчас:** TypeScript, исполняется Node 26 из исходников (`erasableSyntaxOnly`, без tsx и сборки — PEP-36).
|
|
||||||
- **Источники:** `package.json` (TypeScript 6, `@types/node` 26), `scripts/lib/require-node.mjs`,
|
|
||||||
`infra/platform/Dockerfile` (`node:26-bookworm-slim`), `openspec/changes/pep-36-lightweight-stack/`.
|
|
||||||
- **Причина отклонения:** платформа старше стандарта; один язык на веб, бот, раннер, MCP и тесты;
|
|
||||||
SDK MCP (`@modelcontextprotocol/sdk`) и хуки Claude Code — экосистема TypeScript; код веба и
|
|
||||||
доменной логики разделяет типы без границы API.
|
|
||||||
- **Риски изменения:** переписывание ~119 тыс. строк и 176 тестов; месяцы без развития продукта;
|
|
||||||
потеря общего кода веба и ядра. **Выгоды:** единый стек с новыми проектами, статический бинарь.
|
|
||||||
- **Рекомендация:** сохранить. Новые *отдельные* сервисы платформы (если появятся без общего кода
|
|
||||||
с ядром) — можно писать на Go по стандарту.
|
|
||||||
|
|
||||||
### HTTP: Gin
|
|
||||||
|
|
||||||
- **Сейчас:** Next.js (Route Handlers `apps/web/app/api`, Server Actions `app/(app)/*actions.ts`),
|
|
||||||
свой сервер `apps/web/server.ts` для WebSocket `/api/ws`; health — `/api/health`.
|
|
||||||
- **Источники:** `apps/web/package.json` (`next` 16.4.6), `apps/web/server.ts`, `packages/runner/src/live-ws.ts`.
|
|
||||||
- **Причина:** следствие выбора языка. Обработчики уже тонкие (Server Actions — обёртки над core/runner),
|
|
||||||
как требует стандарт от обработчиков Gin.
|
|
||||||
- **Рекомендация:** сохранить.
|
|
||||||
|
|
||||||
### Доступ к данным: Bun
|
|
||||||
|
|
||||||
- **Сейчас:** Drizzle ORM 0.45.4 + drizzle-kit (миграции), драйвер — своя прослойка над `node:sqlite`
|
|
||||||
(`packages/db/src/client.ts`: `busy_timeout`, WAL, повторы при `SQLITE_BUSY`), транзакции только синхронные.
|
|
||||||
- **Источники:** `packages/db/package.json`, `packages/db/src/client.ts`, `packages/db/migrations/`.
|
|
||||||
- **Причина:** следствие языка и базы. Своя прослойка появилась, потому что в стабильном drizzle нет
|
|
||||||
драйвера `node:sqlite`, а better-sqlite3 под Node 26 собирается из исходников (PEP-36).
|
|
||||||
- **Риск текущего:** своя прослойка — наш код на критическом пути. **Рекомендация:** сохранить;
|
|
||||||
P3 — перейти на официальный драйвер `node:sqlite` в drizzle, когда он выйдет в стабильной версии.
|
|
||||||
|
|
||||||
### Конфигурация: Viper
|
|
||||||
|
|
||||||
- **Сейчас:** переменные окружения читаются по месту использования: 214 разных имён
|
|
||||||
(`grep -rhoE 'process\.env\.[A-Z0-9_]+' packages apps --include=*.ts | sort -u | wc -l`),
|
|
||||||
типизированы и проверены zod только 22 (`packages/shared/src/env.ts`). Настройки времени работы —
|
|
||||||
таблица `settings` (ключ → JSON), с наследованием платформа → проект → задача.
|
|
||||||
- **Соответствует:** секреты только из окружения (`.env` вне образа, секреты проектов шифруются),
|
|
||||||
`$PORT`, health-эндпоинт.
|
|
||||||
- **Не соответствует:** «конфиг читается один раз и передаётся явно» — нет; список настроек нельзя
|
|
||||||
увидеть в одном месте, опечатка в имени молча даёт значение по умолчанию.
|
|
||||||
- **Риски изменения:** правки в сотнях мест; легко сломать тесты, которые подменяют env на ходу.
|
|
||||||
**Выгоды:** один реестр с описанием и значениями по умолчанию, проверка при старте.
|
|
||||||
- **Рекомендация:** P2, M — реестр имён в `@peppa/shared/env` (zod, описание, умолчание) и тест,
|
|
||||||
что каждое `process.env.X` есть в реестре; перевод мест чтения — по касанию. Viper не нужен (не Go).
|
|
||||||
|
|
||||||
### База данных: PostgreSQL
|
|
||||||
|
|
||||||
- **Сейчас:** SQLite в режиме WAL, каждый процесс открывает файл сам; `peppa.db` (основная),
|
|
||||||
`history.db` (журнал, PEP-221), `observe.db` (мониторинг, PEP-202); живые обновления —
|
|
||||||
`PRAGMA data_version` + unix-сокеты вместо LISTEN/NOTIFY; ежедневная копия `VACUUM INTO`.
|
|
||||||
- **Источники:** `packages/db/src/client.ts`, `packages/core/src/history.ts`, `packages/core/src/observe.ts`,
|
|
||||||
`packages/core/src/backup.ts`, замер — `openspec/changes/pep-36-lightweight-stack/design.md`.
|
|
||||||
- **Причина (PEP-36, решение владельца 2026-11-13):** замер на нагрузке FORGE — запись p50
|
|
||||||
0,13–0,20 мс у `node:sqlite` против 7–10 мс у Postgres при 10–20 раннерах, `SQLITE_BUSY` — 0;
|
|
||||||
минус отдельный сервис базы на одной машине. Отклонение **обосновано** и записано.
|
|
||||||
- Подробно — раздел «PostgreSQL, UUIDv7 и pg_stat_statements».
|
|
||||||
- **Рекомендация:** сохранить, пересмотреть при условиях из того раздела.
|
|
||||||
|
|
||||||
### Идентификаторы: UUIDv7
|
|
||||||
|
|
||||||
- **Сейчас:** `integer("id").primaryKey({ autoIncrement: true })` во всех таблицах с суррогатным
|
|
||||||
ключом, связующие таблицы — составные ключи (`packages/db/src/schema.ts`).
|
|
||||||
- **Причина:** UUIDv7 в стандарте привязан к PostgreSQL; при одном файле SQLite нет генерации ключей
|
|
||||||
в нескольких местах — главной причины брать UUID. Номера сущностей видны в адресах (`/t/PEP-42`,
|
|
||||||
id вопросов, сессий) и в контрактах MCP.
|
|
||||||
- **Риск текущего:** номера перебираемы — защищает проверка доступа в каждом месте (`projectForUser`).
|
|
||||||
- **Рекомендация:** сохранить. Менять только вместе с переходом на PostgreSQL, и даже тогда —
|
|
||||||
только для новых таблиц.
|
|
||||||
|
|
||||||
### Наблюдение за запросами: pg_stat_statements
|
|
||||||
|
|
||||||
- **Сейчас:** PostgreSQL у платформы нет (Bugsink переведён на SQLite в PEP-63, `postgres` в
|
|
||||||
`infra/docker-compose.yml` — только профиль `legacy`). Аналог: медленные запросы веба и базы —
|
|
||||||
`core/request-timing.ts` + `packages/db/src/probe.ts` → предупреждение в Bugsink (PEP-213).
|
|
||||||
- **Рекомендация:** неприменимо. Если появится PostgreSQL — включить расширение в первой миграции.
|
|
||||||
|
|
||||||
### Публичный сайт: Next.js App Router
|
|
||||||
|
|
||||||
- **Сейчас:** публичные страницы без входа — `/login`, `/mcp-guide` — на Next.js 16 App Router
|
|
||||||
(`apps/web/app/login`, `apps/web/app/mcp-guide`), Pages Router не используется.
|
|
||||||
- **Статус:** соответствует.
|
|
||||||
|
|
||||||
### Аналитика: GA4
|
|
||||||
|
|
||||||
- **Сейчас:** нет. У платформы нет публичного сайта для привлечения: страница входа и памятка для
|
|
||||||
ИИ-клиентов. **Статус:** неприменимо (стандарт ограничивает GA4 публичным сайтом).
|
|
||||||
|
|
||||||
### CDN: Cloudflare CDN
|
|
||||||
|
|
||||||
- **Сейчас:** адреса `peppa.` / `forge.telecom.quest` идут через Cloudflare (туннель и DNS —
|
|
||||||
`core/edge-dns.ts`, PEP-231/245), то есть через CDN идёт и приложение за входом. Статика Next —
|
|
||||||
неизменяемые имена; известная грабля (Cloudflare превращает `no-cache` в кэш браузера) учтена
|
|
||||||
в `next.config.ts`.
|
|
||||||
- **Почему частично:** стандарт ставит CDN только перед публичным сайтом; у FORGE Cloudflare —
|
|
||||||
ещё и единственный вход снаружи (туннель). Это осознанно: сервер без публичного IP.
|
|
||||||
- **Рекомендация:** P3, S — проверить, что ответы за входом отдаются с `private, no-store`
|
|
||||||
(кэш Cloudflare их не держит). Менять схему входа не нужно.
|
|
||||||
|
|
||||||
### Защита форм: Cloudflare Turnstile
|
|
||||||
|
|
||||||
- **Сейчас:** нет. Пароль убран (PEP-71), вход — eGov QR и Google OAuth; без входа принимаются только
|
|
||||||
`/api/client-errors` (≤ 16 КБ, 20/мин на IP) и `/oauth/register` (регистрация клиента MCP —
|
|
||||||
API, не форма). **Статус:** неприменимо. Появится публичная форма с вводом — добавить Turnstile.
|
|
||||||
|
|
||||||
### Веб-приложение: React + TanStack + Vite
|
|
||||||
|
|
||||||
- **Сейчас:** приложение за входом — тоже Next.js App Router: серверные компоненты читают базу
|
|
||||||
напрямую, Server Actions вместо API, живые обновления — свой WebSocket (PEP-225), Tailwind v4 +
|
|
||||||
shadcn/ui. TanStack и Vite не используются.
|
|
||||||
- **Источники:** `apps/web/package.json`, `apps/web/lib/live.ts`, `apps/web/app/(app)/`.
|
|
||||||
- **Причина:** архитектура старше стандарта (PEP-38); отдельного HTTP API у платформы нет —
|
|
||||||
SPA на Vite потребовало бы написать его для всех экранов (их десятки), плюс TanStack Query вместо
|
|
||||||
своего живого канала.
|
|
||||||
- **Риски изменения:** XL; потеря серверного рендера и прямого доступа к данным. **Выгоды:**
|
|
||||||
единый с новыми проектами фронтенд, быстрый dev-сервер (у FORGE были петли перезагрузки `next dev`).
|
|
||||||
- **Рекомендация:** сохранить.
|
|
||||||
|
|
||||||
### Код и проверки: Gitea или Forgejo
|
|
||||||
|
|
||||||
- **Сейчас:** Gitea 1.22 (`git.vibe42.kz`), Gitea Actions, `gitea/act_runner:0.2.11`, проверки
|
|
||||||
`.gitea/workflows/ci.yml` + `checks` в `.peppa/project.json` — тот же конвейер, что у проектов.
|
|
||||||
- **Статус:** соответствует. Подробно — раздел «Gitea и Forgejo».
|
|
||||||
|
|
||||||
### Ошибки: Bugsink
|
|
||||||
|
|
||||||
- **Сейчас:** Bugsink 2.6.3 в контейнере, база SQLite (PEP-63); ошибки проектов → задачи
|
|
||||||
(PEP-58); собственные ошибки платформы шлёт `core/error-report.ts` — конверты Sentry без SDK
|
|
||||||
(PEP-91), браузер — `components/ErrorReporter.tsx` → `/api/client-errors`.
|
|
||||||
- **Почему частично:** стандарт велит SDK Sentry; у платформы — свой минимальный отправитель.
|
|
||||||
- Подробно — раздел «Bugsink».
|
|
||||||
|
|
||||||
### Логи и метрики: Loki + Grafana
|
|
||||||
|
|
||||||
- **Сейчас:** журналы сервисов — текстовые строки в `$PEPPA_HOME/logs/<сервис>.log` с ротацией
|
|
||||||
(`core/service-log.ts`, PEP-291), плюс `~/.peppa/hook.log`, `watchdog.log`; метрики и проверки
|
|
||||||
доступности — свой мониторинг (`core/observe.ts`, `/observability`, PEP-202); графиков нет;
|
|
||||||
поиск по логам — `grep` по SSH. Loki, Grafana, Promtail/Alloy в `infra/` нет.
|
|
||||||
- **Риски текущего:** разбор сбоя требует доступа к серверу (агент в контейнере его не видит —
|
|
||||||
память проекта, PEP-231); журналы не связаны с `release` и задачей; нет истории нагрузки.
|
|
||||||
- **Риски изменения:** ещё два сервиса на одной машине (память, диск — см. PEP-287);
|
|
||||||
объём логов агентов. **Выгоды:** поиск по всем сервисам из браузера, оповещения по логам,
|
|
||||||
тот же стек, что стандарт даёт продуктам.
|
|
||||||
- **Рекомендация:** P1. Шаг 1 (S) — JSON-строки в `service-log.ts` (уровень, сервис, коммит, задача).
|
|
||||||
Шаг 2 (M) — Loki + Grafana Alloy в `infra/docker-compose.yml`, Grafana за входом суперадмина;
|
|
||||||
свой мониторинг `observe.db` не заменять (он ведёт функции и сообщения), а дополнить.
|
|
||||||
|
|
||||||
### Контейнеры: Docker
|
|
||||||
|
|
||||||
- **Сейчас:** один образ `peppa/platform` (многоэтапный `infra/platform/Dockerfile`, Node 26
|
|
||||||
bookworm-slim) для web/bot/watchdog/observer/tmux; compose `infra/docker-compose.yml`; агенты —
|
|
||||||
в контейнерах образа `infra/runner/Dockerfile` (PEP-222); продукты — `deploy/compose.yml` шаблона.
|
|
||||||
- **Статус:** соответствует. Подробно — раздел «Docker».
|
|
||||||
|
|
||||||
## DDD-Lite
|
|
||||||
|
|
||||||
| Принцип | Как в FORGE | Оценка |
|
|
||||||
|---|---|---|
|
|
||||||
| Пакеты по контекстам | `packages/core/src` — 135 плоских файлов, `packages/runner/src` — 102; файл ≈ контекст (`tasks.ts`, `chats.ts`, `connections.ts`, `subscriptions.ts`), но без папок и границ; деление core/runner — по виду побочных эффектов (данные против процессов/tmux/Gitea), а не по контекстам | частично |
|
|
||||||
| Единый язык | сильная сторона: `docs/glossary.md` с проверкой `pnpm lint`, `@peppa/shared/wording`; но в коде «task» = «стори/задача», «goal» = «эпик» (MCP-алиасы) | частично |
|
|
||||||
| Сущности и объекты-значения | инварианты — в функциях ядра и в SQL, типов-сущностей с методами нет (данные — строки Drizzle) | отклонение |
|
|
||||||
| Use-case сервисы | соответствует по сути: Server Actions, MCP, бот и CLI зовут одни функции core/runner (`moveTask`, `acceptStory`, `askPm`) | соответствует |
|
|
||||||
| Репозиторий — интерфейс | нет: 86 файлов core импортируют `drizzle-orm` напрямую (`grep -rl 'from "drizzle-orm"' packages/core/src | wc -l`) | отклонение |
|
|
||||||
| Типизированные ошибки домена | `PeppaError` (`core/errors.ts`) — одна категория «понятный отказ человеку»; `NoCapacityError`, `HostUnreachable` — точечно | частично |
|
|
||||||
|
|
||||||
**Вывод.** FORGE — модульный монолит с хорошими «узкими местами» (единые функции на сценарий —
|
|
||||||
это и есть use-cases), но без границ контекстов и репозиториев. Полный перевод на DDD-Lite —
|
|
||||||
L–XL и мало что даёт при одной базе SQLite и синхронных транзакциях.
|
|
||||||
|
|
||||||
**Рекомендация:** P3, по касанию. Когда задача существенно трогает контекст из нескольких файлов —
|
|
||||||
собрать его в папку `core/src/<контекст>/` с `index.ts` (первые кандидаты, уже фактически
|
|
||||||
контексты: Access Hub — `connection*.ts`, `access-requests.ts`; подписки — `subscription*.ts`,
|
|
||||||
`capacity.ts`). Интерфейсы репозиториев не вводить: при одной базе это церемония, которую
|
|
||||||
стандарт сам запрещает («интерфейс на каждый тип на всякий случай»).
|
|
||||||
|
|
||||||
## PostgreSQL, UUIDv7 и pg_stat_statements
|
|
||||||
|
|
||||||
**Текущее решение и доказательства.** PEP-36 замерил запись на нагрузке FORGE (10–20 раннеров,
|
|
||||||
×1…×50): `node:sqlite` p50 0,13–0,20 мс, p99 ≤ 1,33 мс, `SQLITE_BUSY` 0; Postgres того же
|
|
||||||
сценария — p50 7–10 мс, p99 18–36 мс. Решение одобрено владельцем (approval #41). С тех пор
|
|
||||||
выросло число таблиц (41) и процессов, но все они на одной машине.
|
|
||||||
|
|
||||||
**Что дал бы переход на PostgreSQL:**
|
|
||||||
- несколько серверов веба и раннеров с одной базой (сейчас всё на одной машине, хосты раннеров
|
|
||||||
ходят через релей); реплики и резервирование без остановки;
|
|
||||||
- `pg_stat_statements`, `EXPLAIN`, JSONB-индексы, стандартные инструменты резервного копирования;
|
|
||||||
- единый стек с новыми проектами.
|
|
||||||
|
|
||||||
**Что стоит переход:** схема 41 таблицы на `pg-core` и новая базовая миграция; все транзакции
|
|
||||||
синхронные (`db.transaction((tx) => …)` без `await`) — их придётся переписать на асинхронные во
|
|
||||||
всём ядре; запросы `json_extract`/`json_each`; живые обновления через `PRAGMA data_version` —
|
|
||||||
обратно на LISTEN/NOTIFY; тесты — на временный файл SQLite у каждого файла теста (176), им нужна
|
|
||||||
своя база; перенос данных (обратная команда `migrate-to-sqlite` есть, прямой нет). Оценка — L,
|
|
||||||
с риском регрессий по всему ядру. Задержка записи вырастет на порядок.
|
|
||||||
|
|
||||||
**UUIDv7** без PostgreSQL и без генерации ключей в нескольких местах пользы не даёт; замена
|
|
||||||
целых ключей ломает адреса и контракты MCP. **pg_stat_statements** — неприменимо.
|
|
||||||
|
|
||||||
**Рекомендация:** сохранить SQLite. Пересмотреть, если выполнится хотя бы одно:
|
|
||||||
1. веб или служба запуска агентов должны работать больше чем на одном сервере одновременно;
|
|
||||||
2. p99 записи в проде > 50 мс или заметные `SQLITE_BUSY` (видно по `request-timing` / probe);
|
|
||||||
3. основная база > 10 ГБ или копия `VACUUM INTO` дольше минуты;
|
|
||||||
4. нужен доступ к данным платформы внешним инструментам (BI) без копии файла.
|
|
||||||
Задача-кандидат на сейчас (P3, S): записать в стандарте, что SQLite — допустимое исключение для
|
|
||||||
однохостовой платформы, со ссылкой на эти условия.
|
|
||||||
|
|
||||||
## Bugsink
|
|
||||||
|
|
||||||
- **Соответствует стандарту:** самостоятельно размещённый Bugsink 2.6.3 (`infra/docker-compose.yml`,
|
|
||||||
`bugsink.telecom.quest`), протокол Sentry, `release` = коммит, `environment`, без персональных
|
|
||||||
данных; ошибки проектов превращаются в задачи эпика «Стабильность» (PEP-58), свои ошибки
|
|
||||||
платформы — в проект `PEP` (PEP-91); правила агентов (`template/RULES.md`) требуют от проектов SDK Sentry.
|
|
||||||
- **Отличие:** платформа шлёт ошибки своим отправителем (`core/error-report.ts`, ≈ 230 строк):
|
|
||||||
нет хлебных крошек, контекста запроса, карт исходников для браузера, трассировки производительности.
|
|
||||||
Причина — запуск TypeScript без сборки и контроль частоты (≤ 30/мин, одна ошибка раз в минуту).
|
|
||||||
- **Риск:** ошибки браузера в Bugsink без карт исходников читаются хуже. **Выгода SDK:** крошки,
|
|
||||||
группировка по стеку исходников.
|
|
||||||
- **Рекомендация:** сохранить Bugsink; P3, S — попробовать `@sentry/browser` только во фронте
|
|
||||||
(через `ErrorReporter`), бэкенд оставить на своём отправителе. Хранилище SQLite (PEP-63) — сохранить.
|
|
||||||
|
|
||||||
## Gitea и Forgejo
|
|
||||||
|
|
||||||
- **Сейчас:** Gitea 1.22 — репозитории, PR, защита основной ветки (PEP-191), Actions с одним
|
|
||||||
`act_runner` (`capacity: 4`), вебхуки в FORGE. Соответствует стандарту.
|
|
||||||
- **Ограничения 1.22, вокруг которых написан код** (из `AGENTS.md`): нет API логов заданий —
|
|
||||||
хвост лога шлёт сам шаг; нет `workflow_dispatch` в API — прод выкатывается тегом `deploy-prod-*`;
|
|
||||||
ревью и комментарий приходят одним событием `pull_request_comment`; ложный «конфликт» сразу после
|
|
||||||
обновления ветки (PEP-298).
|
|
||||||
- **Варианты:** (а) обновить Gitea до актуальной стабильной версии — M, часть обходных путей можно
|
|
||||||
будет убрать после проверки changelog; (б) перейти на Forgejo — M–L: совместимый API и Actions,
|
|
||||||
но отдельная ветка развития, перенос данных сервера и проверка всех вызовов `GiteaClient` и
|
|
||||||
`mock-gitea`; выгода — управление сообществом, а не функции.
|
|
||||||
- **Рекомендация:** P2 — обновить Gitea (отдельная задача с репетицией на копии); Forgejo — P3,
|
|
||||||
только при причине лицензии или управления проектом.
|
|
||||||
|
|
||||||
## Docker
|
|
||||||
|
|
||||||
- **Соответствует:** один многоэтапный образ платформы, compose, закреплённые версии образов
|
|
||||||
(`bugsink:2.6.3`, `act_runner:0.2.11`, `cloudflared:2025.11.1`) и CLI агентов
|
|
||||||
(`infra/agent-versions.json`, PEP-267), песочницы агентов в контейнерах (PEP-17/222),
|
|
||||||
уборка диска (PEP-287), страж портов и доменов (PEP-189).
|
|
||||||
- **Риски:** сокет docker хоста смонтирован в `act-runner`, `watchdog` и `tmux` (`infra/docker-compose.yml`,
|
|
||||||
строки с `/var/run/docker.sock`) — это права root на сервере для всего, что там исполняется;
|
|
||||||
CI ограничен ветками своего репозитория, но сам раннер общий для проектов. Клиент docker в образе —
|
|
||||||
20.10 (старый, память проекта PEP-287). Рабочий образ не `distroless` (нужны git, tmux, ssh, docker CLI) —
|
|
||||||
это оправдано.
|
|
||||||
- **Рекомендация:** P2, M — прокси сокета docker с белым списком вызовов для `watchdog`/`tmux`
|
|
||||||
(запуск и остановка `peppa-s*`), отдельный раннер проверок для чужих проектов; обновить docker CLI
|
|
||||||
в образе (S).
|
|
||||||
|
|
||||||
## Roadmap
|
|
||||||
|
|
||||||
| Этап | Что | Слой | Трудоёмкость | Почему сейчас / почему не сейчас |
|
|
||||||
|---|---|---|---|---|
|
|
||||||
| 0 | Сохранить основу: TypeScript/Node 26, Next.js, SQLite, Drizzle, целые ключи; записать в стандарт исключение для однохостовой платформы с условиями пересмотра | бэкенд, база, веб | S | доказано замером PEP-36, переписывание — XL без пользы продукту |
|
|
||||||
| 1 | JSON-строки в журналах сервисов (уровень, сервис, коммит, задача) | логи | S | дешёво, без нового сервиса, готовит этап 2 |
|
|
||||||
| 1 | Реестр переменных окружения + тест на неизвестные имена | конфигурация | M | 214 имён без описания — источник тихих ошибок |
|
|
||||||
| 2 | Loki + Grafana Alloy на сервере, Grafana за входом суперадмина | логи и метрики | M | единственный слой без аналога; разбор сбоев без SSH |
|
|
||||||
| 2 | Прокси сокета docker, новый docker CLI в образе | контейнеры | M | снижает права всего, что запускается на сервере |
|
|
||||||
| 2 | Обновление Gitea с репетицией на копии | код и проверки | M | убирает часть обходных путей 1.22 |
|
|
||||||
| 3 | Контексты ядра по папкам — по касанию | DDD-Lite | L (растянуто) | только вместе с задачами в этих контекстах |
|
|
||||||
| 3 | `@sentry/browser` во фронте | ошибки | S | когда ошибок браузера станет много |
|
|
||||||
| 3 | `private, no-store` для ответов за входом — проверка | CDN | S | профилактика |
|
|
||||||
| — | Не делать: Go, Gin, Bun, Viper, React + TanStack + Vite, PostgreSQL, UUIDv7 для самой FORGE | — | XL | пересмотр — только по условиям раздела о PostgreSQL |
|
|
||||||
|
|
||||||
## На рассмотрение владельцу
|
|
||||||
|
|
||||||
Решения ниже — рекомендации агента; ни одно не начато. Каждое можно взять отдельной задачей.
|
|
||||||
|
|
||||||
1. **Оставить основу FORGE как есть** (язык, база, устройство экранов). Рекомендую: да.
|
|
||||||
Переписывание на стек новых проектов заняло бы месяцы и не дало бы пользователям ничего нового.
|
|
||||||
2. **Единый журнал работы платформы с поиском и графиками** (Loki + Grafana). Рекомендую: да, первым:
|
|
||||||
это единственное место, где у FORGE нет замены стандарту, и оно ускорит разбор сбоев.
|
|
||||||
3. **Порядок в настройках и доступе к Docker на сервере.** Рекомендую: да, по очереди после пункта 2.
|
|
||||||
4. **Обновить сервер кода (Gitea).** Рекомендую: да, отдельной задачей с репетицией; переход на Forgejo — не сейчас.
|
|
||||||
5. **Когда пересматривать базу данных** — условия в разделе «PostgreSQL, UUIDv7 и pg_stat_statements».
|
|
||||||
Рекомендую записать их в стандарт как исключение для платформы.
|
|
||||||
@ -1,42 +0,0 @@
|
|||||||
# Design: PEP-298
|
|
||||||
|
|
||||||
## Два наблюдения
|
|
||||||
`conflictStep` без шага больше не просит агента сразу: он пишет `conflict.seen:<taskId>`
|
|
||||||
`{sha, at}` и возвращает новый исход `settling`. Просьба уходит, когда та же голова конфликтует
|
|
||||||
спустя `CONFLICT_SETTLE_MIN`. Новая голова (push агента, обновление ветки платформой) начинает
|
|
||||||
ожидание заново — именно после них Gitea и врёт. Смена основной ветки ожидание не сбрасывает:
|
|
||||||
на занятом проекте main двигается часто, и настоящий конфликт ждал бы часами.
|
|
||||||
|
|
||||||
`conflictStepTick` (раз в минуту) обходит и отметки `conflict.seen`, поэтому второе наблюдение
|
|
||||||
делает он, а не вызвавший путь: почасовой сверке сирот и сторожу застрявших не нужно приходить
|
|
||||||
второй раз. Конфликт пропал — отметка снимается вместе с шагом (`clearConflictStep`).
|
|
||||||
|
|
||||||
Длительность — `PEPPA_CONFLICT_SETTLE_MIN` (по умолчанию `CONFLICT_SETTLE_MIN` = 2). В тестах
|
|
||||||
`helpers.ts` ставит 0: десятки сценариев PEP-269/301 пишут конфликт по шагам; пауза проверяется
|
|
||||||
в `conflict-settle.test.ts`.
|
|
||||||
|
|
||||||
## «Принять» человеком
|
|
||||||
Тоже ждёт второго наблюдения. Нажатие уже запоминается (`accept.pending`, PEP-127) и доводится
|
|
||||||
`pendingAcceptTick`; человек видит «принято, закроется само». Если конфликт настоящий, просьба
|
|
||||||
уйдёт через 2 минуты, если ложный — задача смержится без агента. Отдельный путь «сразу» дал бы
|
|
||||||
те же ложные просьбы, ради которых стори заведена.
|
|
||||||
|
|
||||||
## Остальные вызовы
|
|
||||||
- `stuckTaskTick`: `settling` — как `held`: попытка не засчитана, карточка не снимается.
|
|
||||||
- `wakeOnGreen`: возвращает `false` (агент не разбужен), просьбу отправит минутная сверка.
|
|
||||||
- `deferAccept`: `settling` — приёмка запомнена, как при `waiting`.
|
|
||||||
|
|
||||||
## Возврат на проверку
|
|
||||||
Шаг хранит `from` — статус задачи при первой просьбе. Когда минутная сверка видит, что конфликта
|
|
||||||
нет, а шаг есть, `from = review`, задача `in_progress`, голова та же, что при просьбе, и у задачи
|
|
||||||
нет ни одной активной сессии (агент ждёт места или очереди раннера) — очередь и ожидание места
|
|
||||||
снимаются, задача идёт на проверку через `platformToReview` (как у сторожа застрявших: ревьюер,
|
|
||||||
карточка «готово» через `sendReviewCard`). Проверки ещё идут — ждём следующую минуту. Агент уже
|
|
||||||
запущен или запушил — не трогаем: он сам вызовет `update_task(review)`.
|
|
||||||
|
|
||||||
## Один список проверок
|
|
||||||
`prGate` читает список из `.peppa/project.json` головы PR; `taskCiSummary` (без вызовов Gitea) —
|
|
||||||
из рабочей копии основной ветки. Теперь `recordCheck` при первом отчёте новой версии один раз
|
|
||||||
читает файл этой версии из Gitea и пишет `ci.checks:<taskId>` `{sha, checks}`; `taskCiSummary`
|
|
||||||
берёт его, если версия совпадает с последней, иначе — как раньше. Строка на задачу одна,
|
|
||||||
перезаписывается. Gitea не ответила — остаётся прежний список.
|
|
||||||
@ -1,23 +0,0 @@
|
|||||||
# PEP-298: ложный «конфликт» сразу после обновления ветки
|
|
||||||
|
|
||||||
## Почему
|
|
||||||
25.11.2026 после выкатки PEP-269 из 40 просьб «обнови изменения» 15 оказались ложными: Gitea
|
|
||||||
пересчитывает возможность слияния в фоне после push и после обновления ветки платформой и в это
|
|
||||||
время отвечает `mergeable: false`. Платформа верила первому ответу, переводила задачу с проверки
|
|
||||||
в работу и ставила агента в очередь (PEP-257: через 30 секунд конфликт снят, задача осталась в
|
|
||||||
работе без дела). Отдельно: `get_task` и допуск к проверке считали проверки по разным спискам
|
|
||||||
(PEP-217: «4 из 4 пройдены» против отказа «3 из 4»).
|
|
||||||
|
|
||||||
## Что меняется
|
|
||||||
- Первая просьба агенту по конфликту уходит, только если та же версия результата конфликтует и
|
|
||||||
через `CONFLICT_SETTLE_MIN` (2 мин): первое наблюдение запоминается, второе делает минутная
|
|
||||||
сверка шага конфликта — для всех путей (автомерж, придержанное «готово», «Принять», лечение
|
|
||||||
застрявшей, сверка сирот, пробуждение после зелёных проверок).
|
|
||||||
- Задача, которую перевели с проверки в работу ради конфликта, возвращается на проверку сама,
|
|
||||||
когда конфликт снят, агент так и не стартовал и версия результата не менялась.
|
|
||||||
- Карточка задачи (`taskCiSummary`, `get_task`) считает проверки по списку `.peppa/project.json`
|
|
||||||
той версии, на которой они шли, — как допуск (`prGate`).
|
|
||||||
|
|
||||||
## Влияние
|
|
||||||
- `runner/conflict-step.ts`, `runner/stuck-tasks.ts`, `runner/ci-feedback.ts`, `core/ci.ts`.
|
|
||||||
- Новые отметки в `settings`: `conflict.seen:<taskId>`, `ci.checks:<taskId>`. Без миграций.
|
|
||||||
@ -1,41 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
|
|
||||||
### Requirement: Ложный «конфликт» сразу после обновления не зовёт агента
|
|
||||||
FORGE SHALL отправлять первую просьбу обновить изменения, только если та же версия результата
|
|
||||||
конфликтует с основной веткой и спустя `CONFLICT_SETTLE_MIN` (2 минуты) после первого
|
|
||||||
наблюдения. Новая версия результата SHALL начинать ожидание заново. Задачу, которую перевели с
|
|
||||||
проверки в работу ради конфликта, FORGE SHALL вернуть на проверку сама, если конфликт снят,
|
|
||||||
агент не запускался и версия результата не менялась.
|
|
||||||
|
|
||||||
#### Scenario: Gitea две минуты после обновления ветки отвечает «конфликт»
|
|
||||||
- **GIVEN** задача PEP-257 на проверке, FORGE обновила ветку её результата
|
|
||||||
- **AND** Gitea первые две минуты отвечает, что изменения конфликтуют
|
|
||||||
- **WHEN** FORGE видит конфликт, а через минуту и через две смотрит снова
|
|
||||||
- **THEN** агент не получает просьбы и не запускается
|
|
||||||
- **AND** задача остаётся на проверке
|
|
||||||
|
|
||||||
#### Scenario: Настоящий конфликт
|
|
||||||
- **GIVEN** задача на проверке, её результат конфликтует с основной веткой
|
|
||||||
- **WHEN** конфликт держится 2 минуты на той же версии
|
|
||||||
- **THEN** агент получает одну просьбу обновить изменения
|
|
||||||
|
|
||||||
#### Scenario: Зря переведённая в работу задача возвращается сама
|
|
||||||
- **GIVEN** задачу перевели с проверки в работу ради конфликта, агент ждёт места и не запускался
|
|
||||||
- **WHEN** конфликт исчез, а версия результата прежняя
|
|
||||||
- **THEN** задача снова на проверке, место агента в очереди освобождено
|
|
||||||
|
|
||||||
#### Scenario: Агент уже обновил изменения
|
|
||||||
- **GIVEN** задачу перевели в работу ради конфликта, и в результате появилась новая версия
|
|
||||||
- **WHEN** конфликт исчез
|
|
||||||
- **THEN** задача остаётся в работе — агент передаст её сам
|
|
||||||
|
|
||||||
### Requirement: Карточка задачи и допуск считают проверки по одному списку
|
|
||||||
Сводка проверок на карточке задачи и в `get_task` SHALL считать проверки по списку из
|
|
||||||
`.peppa/project.json` той версии результата, на которой они шли, — тем же, что и допуск к
|
|
||||||
проверке и слиянию.
|
|
||||||
|
|
||||||
#### Scenario: В версии результата нужна проверка, которой нет в основной копии
|
|
||||||
- **GIVEN** в последней версии результата нужны lint, build, typecheck и test, а в основной копии — только первые три
|
|
||||||
- **AND** test на этой версии не отчитался
|
|
||||||
- **WHEN** агент смотрит задачу, а FORGE проверяет допуск
|
|
||||||
- **THEN** оба показывают «Проверки идут: 3 из 4»
|
|
||||||
@ -1,18 +0,0 @@
|
|||||||
## 1. Два наблюдения
|
|
||||||
- [x] 1.1 `conflict.seen:<taskId>`, исход `settling`, `PEPPA_CONFLICT_SETTLE_MIN`
|
|
||||||
- [x] 1.2 `conflictStepTick` обходит `conflict.seen`; `clearConflictStep` снимает отметку
|
|
||||||
- [x] 1.3 `stuckTaskTick`: `settling` как `held`
|
|
||||||
- [x] 1.4 Тест: «конфликт» первые две минуты после обновления — агент не вызывается, задача на проверке
|
|
||||||
- [x] 1.5 Тест: настоящий конфликт — просьба через `CONFLICT_SETTLE_MIN`; новая голова сбрасывает ожидание
|
|
||||||
|
|
||||||
## 2. Возврат на проверку
|
|
||||||
- [x] 2.1 `from` в шаге, `backToReview` в минутной сверке
|
|
||||||
- [x] 2.2 Тест: конфликт ушёл, агент не стартовал — задача на проверке; агент запушил — не трогаем
|
|
||||||
|
|
||||||
## 3. Один список проверок
|
|
||||||
- [x] 3.1 `rememberHeadChecks` в `recordCheck`, `taskCiSummary` по списку версии
|
|
||||||
- [x] 3.2 Тест: у версии четыре проверки, в основной копии три — карточка и допуск совпадают
|
|
||||||
|
|
||||||
## 4. Завершение
|
|
||||||
- [x] 4.1 Соседние наборы тестов, typecheck, lint
|
|
||||||
- [x] 4.2 AGENTS.md, память
|
|
||||||
@ -1,20 +0,0 @@
|
|||||||
# Design: PEP-304
|
|
||||||
|
|
||||||
## Причина отказа claudePrint
|
|
||||||
`ClaudePrintResult` при неудаче получает необязательное `limitedUntil?: Date` (и `limited: true`).
|
|
||||||
Ядро: `projectClaudeLimit(db, project, now)` — в наборе проекта есть подписки Claude с ключом,
|
|
||||||
ни одна не пригодна, хотя бы одна `limited` → ближайший `limitedUntil` (или `null`, если срок
|
|
||||||
неизвестен; тогда «в лимите» без времени). Подписки нет вовсе → `null` результата функции —
|
|
||||||
прежнее «нет подписки». Проверяется только когда вход машины проекту не положен (как раньше).
|
|
||||||
|
|
||||||
## Разбор задачи
|
|
||||||
В `IntakeState` — `retryAt?: number` (ms) и `limitNoted?: number` (сброс, о котором уже сказали).
|
|
||||||
`advance` пропускает состояние с `retryAt > now`. Лимит из `step` — `LimitedError`: попытки не
|
|
||||||
растут, `retryAt = until + 60 с` (неизвестен — через 30 мин), заметка — один раз на `until`.
|
|
||||||
Задача остаётся у аналитика (диспетчер её не берёт) — агенты всё равно не запустятся, пока все
|
|
||||||
подписки набора в лимите.
|
|
||||||
|
|
||||||
## Время
|
|
||||||
`@peppa/shared/time` — модуль без Node-зависимостей, годится и хуку (лёгкий `limit-delay.ts`).
|
|
||||||
`Intl.DateTimeFormat` с `timeZone: PEPPA_TZ`; неверное имя пояса → без пояса (не падать).
|
|
||||||
Ключи переводов не меняются: время подставляется в `{time}`.
|
|
||||||
@ -1,26 +0,0 @@
|
|||||||
# PEP-304: настоящая причина вместо «не подключена подписка», время в поясе платформы
|
|
||||||
|
|
||||||
## Зачем
|
|
||||||
25.11 23:35 (GARDEN-12) владелец получил «Аналитик не смог разобрать задачу: у проекта не
|
|
||||||
подключена подписка», хотя подписки у проекта есть — все были в лимите. `claudePrint` не
|
|
||||||
различал «подписок нет» и «все в лимите», а разбор после двух неудач отпускал задачу «как
|
|
||||||
написана». Время в сообщениях людям местами считалось в поясе сервера (в контейнерах — UTC).
|
|
||||||
|
|
||||||
## Что меняется
|
|
||||||
- `claudePrint` при отсутствии рабочей подписки Claude различает: подписок Claude в наборе
|
|
||||||
нет — прежняя ошибка; есть, но все в лимите — ошибка `limited` с ближайшим временем сброса
|
|
||||||
(`limitedUntil`).
|
|
||||||
- Разбор задачи (intake): лимит — не попытка. Заметка владельцу одна на окно лимита
|
|
||||||
«подписки проекта в лимите до ЧЧ:ММ, разберу после», повтор после сброса (`retryAt`).
|
|
||||||
- Уточнение постановки и чат с аналитиком называют лимит и время сброса вместо «не подключена».
|
|
||||||
- Один помощник времени для людей — `@peppa/shared/time` (`platformTime`, `platformDayTime`,
|
|
||||||
`platformZone`): пояс `PEPPA_TZ`, неверный пояс — пояс процесса. Им заменены копии `hhmm`
|
|
||||||
в core/runner, подпись версии в чатах, запасная ветка в observe и время в мониторинге.
|
|
||||||
|
|
||||||
## Влияние
|
|
||||||
- `packages/shared/src/time.ts` (новый), `packages/core/src/subscriptions.ts` (`projectClaudeLimit`).
|
|
||||||
- `packages/runner/src/claude-print.ts`, `intake.ts`, `story-refine.ts`, `analyst-chat.ts`.
|
|
||||||
- `core/monitor.ts`, `core/chats.ts`, `core/observe.ts`, `usage.ts`, `subscription-care.ts`,
|
|
||||||
`onboarding.ts`, runner `limits.ts`, `rotation.ts`, `subscription-request.ts`, `limit-delay.ts`,
|
|
||||||
`pause.ts`, `watchdog.ts`.
|
|
||||||
- Тексты — `i18n/en|kk`.
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
|
|
||||||
### Requirement: Подписки в лимите — не «нет подписки»
|
|
||||||
Когда у проекта есть подписки Claude, но все в лимите, Аналитик SHALL называть причину «подписки в лимите до ЧЧ:ММ» (время в поясе платформы) и повторять разбор задачи после сброса, не отпуская её «как написана». Когда подписок нет, причина SHALL оставаться «у проекта не подключена подписка».
|
|
||||||
|
|
||||||
#### Scenario: Все подписки в лимите
|
|
||||||
- **GIVEN** у проекта GARDEN одна подписка Claude в лимите до 23:50
|
|
||||||
- **AND** в бэклоге новая задача GARDEN-12 ждёт разбора
|
|
||||||
- **WHEN** аналитик берётся за разбор
|
|
||||||
- **THEN** в обсуждении задачи заметка «подписки проекта в лимите до 23:50»
|
|
||||||
- **AND** нет слов «не подключена подписка»
|
|
||||||
- **AND** после 23:51 разбор выполняется снова
|
|
||||||
|
|
||||||
#### Scenario: Подписки нет
|
|
||||||
- **GIVEN** у проекта нет ни одной подписки, владелец зарегистрировался сам
|
|
||||||
- **WHEN** аналитик дважды пытается разобрать задачу
|
|
||||||
- **THEN** заметка «у проекта не подключена подписка»
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
|
|
||||||
### Requirement: Время для людей — в поясе платформы
|
|
||||||
Время в сообщениях и подписях для людей SHALL показываться в поясе платформы `PEPPA_TZ`, а не в поясе процесса; неверное имя пояса SHALL не ломать сообщение.
|
|
||||||
|
|
||||||
#### Scenario: Пояс платформы отличается от пояса сервера
|
|
||||||
- **GIVEN** процесс работает в UTC, `PEPPA_TZ` = «Asia/Almaty»
|
|
||||||
- **WHEN** сообщение называет момент 2026-11-25 18:35 UTC
|
|
||||||
- **THEN** в тексте «23:35»
|
|
||||||
|
|
||||||
#### Scenario: Неверный пояс
|
|
||||||
- **GIVEN** `PEPPA_TZ` = «Not/AZone»
|
|
||||||
- **WHEN** сообщение называет время
|
|
||||||
- **THEN** сообщение отправляется со временем в поясе процесса
|
|
||||||
@ -1,13 +0,0 @@
|
|||||||
## 1. Время
|
|
||||||
- [x] 1.1 `@peppa/shared/time`: `platformZone`, `platformTime`, `platformDayTime`
|
|
||||||
- [x] 1.2 Заменить копии `hhmm` и `toLocale*` без пояса (monitor, chats, observe, usage, subscription-care, onboarding, limits, rotation, subscription-request, limit-delay, pause, watchdog)
|
|
||||||
|
|
||||||
## 2. Причина отказа
|
|
||||||
- [x] 2.1 `projectClaudeLimit` в core, `claudePrint` отдаёт `limited`/`limitedUntil`
|
|
||||||
- [x] 2.2 intake: лимит не тратит попытку, одна заметка на окно, повтор после сброса
|
|
||||||
- [x] 2.3 story-refine и чат с аналитиком называют лимит и время
|
|
||||||
|
|
||||||
## 3. Проверки
|
|
||||||
- [x] 3.1 Тест: все подписки в лимите → заметка «в лимите до …», повтор после сброса
|
|
||||||
- [x] 3.2 Тест: `PEPPA_TZ` ≠ пояс процесса — время в поясе платформы
|
|
||||||
- [x] 3.3 i18n en/kk, `pnpm lint`, typecheck, тесты
|
|
||||||
@ -1,10 +0,0 @@
|
|||||||
## Решения
|
|
||||||
|
|
||||||
- **Какое подключение выдаётся кнопкой.** Подходящие — активные подключения владельца с ключом той же карточки каталога или того же адреса (`connectionsForRequest().fit`). Кнопка берёт первое из них (последнее созданное идёт первым в `listConnections`). Выбрать другое можно на карточке запроса — там прежняя форма со списком.
|
|
||||||
- **Права.** «Дать: чтение» = `GRANT_RIGHTS.read`, «полные права» = `GRANT_RIGHTS.full`. Если у проекта уже было разрешение этого подключения, режимы только расширяются (как в PEP-250): кнопка «чтение» не отнимает у других агентов запись. Срок заменяется выбранным — это сознательное решение владельца.
|
|
||||||
- **Срок по умолчанию** — `DEFAULT_GRANT_TERM` (1 день): в вебе он выбран в списке, в Telegram — первая строка кнопок срока и подсказка в тексте.
|
|
||||||
- **Telegram, два шага.** `ar:<id>:r|f` — меняем клавиатуру сообщения (`editMessageReplyMarkup`) на сроки `ar:<id>:r|f:<1h|1d|7d|forever>` и «Назад» (`ar:<id>:back` возвращает исходные кнопки). `ar:<id>:no` — прежний отказ. Нажатие проверяет владельца в ядре (`ownOpen` → `accessRequestForUser`): чужой получает «Запрос не найден», клавиатура не меняется. Проверка подключения делается уже на первом шаге, чтобы владелец без подключения сразу получил подсказку. После выдачи клавиатура убирается.
|
|
||||||
- **Кнопки «Дать» в сообщении** показываются, только если подходящее подключение есть на момент сообщения; иначе — «Подключить» (ссылка на карточку) и «Отказать». Ссылка — только при https `PEPPA_WEB_URL` (как раньше).
|
|
||||||
- **Ночная тишина и пауза** — не трогаем: сообщение идёт через `deliverToUser`/outbox, ответ на нажатие — прямой ответ человеку; агента проекта на паузе `tellAgentAboutAccess` не будит.
|
|
||||||
- **Агенту** текст решения говорит срок: «чтение на 1 день».
|
|
||||||
- **Отказ по сроку** (`expired`, `idle_revoked`): подсказка `request_access(service: …, purpose: …)` вместо «через ask_pm»; запрос сам не создаётся — агент сам объясняет, зачем ему доступ снова.
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
## Why
|
|
||||||
Агент просит доступ к сервису (PEP-250), а у разрешения есть срок (PEP-259), но владелец пока решает только на карточке запроса и без выбора срока: разрешение из запроса выдаётся «до отзыва». Нужно, чтобы владелец ответил прямо под сообщением о запросе — в Telegram и в вебе — кнопками «Дать: чтение», «Дать: полные права», «Отказать» и выбрал срок.
|
|
||||||
|
|
||||||
## What Changes
|
|
||||||
- Сообщение о запросе доступа в Telegram: кнопки «Дать: чтение» · «Дать: полные права» (если у владельца уже есть подходящее подключение), «Отказать», ссылка на карточку. После выбора прав кнопки меняются на срок: «1 час» · «1 день» · «7 дней» · «до отзыва» и «Назад».
|
|
||||||
- Подключения ещё нет — вместо «Дать» ссылка «Подключить» на карточку запроса (шаги каталога PEP-249), там же выбираются права и срок; нажатие «Дать» без подключения отвечает подсказкой открыть запрос.
|
|
||||||
- Веб «Агенты просят доступ» (`/connections`): у запроса с подходящим подключением — «Дать: чтение» / «Дать: полные права» со сроком (по умолчанию 1 день) и «Отказать»; без подключения — «Подключить». Карточка запроса: в формах «Подключить и разрешить» и «Разрешить уже подключённое» — права и срок.
|
|
||||||
- Ядро: `grantAccessByButton(db, userId, id, { rights, term })` и `rights`/`term` в `grantAccessFromExisting`/`connectAndGrantAccess`; выдача — `grantConnection` с `term`, права — `GRANT_RIGHTS` (прежнее разрешение проекта только расширяется). По умолчанию срок — `DEFAULT_GRANT_TERM` (1 день).
|
|
||||||
- Решает только владелец проекта (и подключения — `grantConnection` проверяет); ночная тишина и пауза — как у прежнего сообщения (`deliverToUser`, агента на паузе не будим).
|
|
||||||
- Отказ шлюза `expired` / `idle_revoked` подсказывает агенту `request_access` с названием сервиса.
|
|
||||||
- «Полные права» = чтение и запись сразу; отдельный режим записи с согласованием — PEP-235, когда появится.
|
|
||||||
|
|
||||||
## Impact
|
|
||||||
- `packages/core/src/access-requests.ts`, `packages/runner/src/access-requests.ts`, `apps/bot/src/bot.ts`, веб `/connections` и `/connections/requests/[id]`, `components/AccessRequests.tsx`, действия, `packages/mcp/src/agent.ts`, переводы en/kk, тесты `access-request-buttons.test.ts`.
|
|
||||||
@ -1,36 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
|
|
||||||
### Requirement: Кнопки выдачи под запросом доступа
|
|
||||||
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, прежнее разрешение проекта SHALL только расширяться по правам. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
|
|
||||||
|
|
||||||
#### Scenario: Чтение на 1 день кнопкой в Telegram
|
|
||||||
- **GIVEN** у «anna» подключение «CRM» и открытый запрос агента проекта «SHOP» к нему
|
|
||||||
- **WHEN** «anna» нажимает «Дать: чтение», затем «1 день»
|
|
||||||
- **THEN** проекту «SHOP» выдано чтение «CRM» на 1 день
|
|
||||||
- **AND** запрос закрыт как выданный, агент получает «доступ выдан: чтение на 1 день»
|
|
||||||
- **AND** агент читает `GET /items`, а через 25 часов получает отказ «срок доступа истёк»
|
|
||||||
|
|
||||||
#### Scenario: Чужой не может нажать «Дать»
|
|
||||||
- **GIVEN** открытый запрос проекта «SHOP» владельца «anna»
|
|
||||||
- **WHEN** пользователь «boris» нажимает «Дать: полные права» и «до отзыва»
|
|
||||||
- **THEN** он получает «Запрос не найден»
|
|
||||||
- **AND** разрешение не выдано, запрос остаётся открытым
|
|
||||||
|
|
||||||
#### Scenario: Подключения ещё нет
|
|
||||||
- **GIVEN** открытый запрос «SHOP» к «stripe», у «anna» нет подключения Stripe
|
|
||||||
- **WHEN** приходит сообщение о запросе
|
|
||||||
- **THEN** в нём ссылка «Подключить» и «Отказать», без «Дать»
|
|
||||||
- **AND** нажатие «Дать: чтение» в старом сообщении отвечает «Подключения ещё нет — откройте запрос и подключите сервис»
|
|
||||||
|
|
||||||
#### Scenario: Срок на карточке запроса
|
|
||||||
- **GIVEN** открытый запрос «SHOP» к «stripe» без подключения
|
|
||||||
- **WHEN** «anna» вставляет ключ, выбирает «полные права» и «7 дней» и нажимает «Подключить и разрешить»
|
|
||||||
- **THEN** проекту выдано чтение и запись «Stripe» на 7 дней
|
|
||||||
|
|
||||||
### Requirement: Истёкший доступ — новый запрос
|
|
||||||
Отказ шлюза из-за истёкшего срока или снятого без дела разрешения SHALL подсказывать агенту попросить доступ снова через `request_access` с названием сервиса.
|
|
||||||
|
|
||||||
#### Scenario: Отказ после истечения
|
|
||||||
- **GIVEN** разрешение «CRM» на 1 час выдано 2 часа назад
|
|
||||||
- **WHEN** агент вызывает «crm»
|
|
||||||
- **THEN** отказ «срок доступа истёк» и подсказка `request_access`
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
## 1. Ядро
|
|
||||||
- [x] 1.1 `rights`/`term` в выдаче по запросу (`grantFor`, `grantAccessFromExisting`, `connectAndGrantAccess`), `grantAccessByButton`, кнопки в `announceAccessRequest` и `accessRequestKeyboard`
|
|
||||||
- [x] 1.2 Текст агенту о решении — со сроком; подсказка `request_access` при `expired`/`idle_revoked`
|
|
||||||
|
|
||||||
## 2. Каналы
|
|
||||||
- [x] 2.1 Бот: `ar:<id>:r|f`, `ar:<id>:r|f:<срок>`, `ar:<id>:back`
|
|
||||||
- [x] 2.2 Веб: кнопки в «Агенты просят доступ», права и срок на карточке запроса; переводы en/kk
|
|
||||||
|
|
||||||
## 3. Проверка
|
|
||||||
- [x] 3.1 Тест `access-request-buttons.test.ts` (Telegram: чтение на 1 день → вызов → истёк; чужой; нет подключения; веб-карточка)
|
|
||||||
- [x] 3.2 lint, typecheck, затронутые тесты
|
|
||||||
@ -1,31 +0,0 @@
|
|||||||
# Design: PEP-284
|
|
||||||
|
|
||||||
## Как стандарт доходит до агента проекта
|
|
||||||
- Агент проекта в контейнере видит только свою рабочую копию и системный промпт (`RULES.md` из
|
|
||||||
шаблона Gitea). Ссылка на `docs/standards/default-stack.md` платформы ему бесполезна.
|
|
||||||
- Решение: файл стандарта кладётся в шаблон (`template/docs/standards/default-stack.md`), новый
|
|
||||||
проект получает его при создании (`provisionProject` копирует недостающие записи шаблона).
|
|
||||||
- Источник правды остаётся один — `docs/standards/default-stack.md` платформы. Копия в шаблоне
|
|
||||||
обязана совпадать побайтно (тест). Почему копия, а не симлинк: `syncTemplate` коммитит
|
|
||||||
содержимое `template/` в отдельный репозиторий — симлинк наружу там был бы битым.
|
|
||||||
- `template/AGENTS.md` несёт короткую сводку (чтобы агент видел главное без открытия файла) и
|
|
||||||
ссылку на полный стандарт. `RULES.md` (идёт во все сессии, включая старые проекты) — 5 строк:
|
|
||||||
стек проекта важнее стандарта, стандарт — для нового, отклонение записывается, миграции нет.
|
|
||||||
|
|
||||||
## Существующие инструкции не перезаписываются
|
|
||||||
- `provisionProject` уже копирует только отсутствующие записи верхнего уровня шаблона —
|
|
||||||
`AGENTS.md`, `docs/` подключённого репозитория остаются как есть. Это закрепляется тестом.
|
|
||||||
- Уже созданные проекты новый `AGENTS.md` не получают автоматически (это и есть «без
|
|
||||||
согласования»): общие правила о стеке они получают через `RULES.md`, полный текст стандарта —
|
|
||||||
по желанию владельца отдельной задачей. Для проекта, у которого уже есть свой `docs/`, копия
|
|
||||||
стандарта не придёт — для старых проектов стандарт не обязателен.
|
|
||||||
- Агентам — правило в `RULES.md`: разделы `AGENTS.md`, написанные людьми, не переписывать;
|
|
||||||
только дописывать своё.
|
|
||||||
|
|
||||||
## Проверка «по-настоящему»
|
|
||||||
- e2e-тест на моке Gitea идёт той же дорогой, что и живая система: `syncTemplate({push})` из
|
|
||||||
настоящего `template/` в репозиторий шаблона → `provisionProject` клонирует шаблон из Gitea →
|
|
||||||
проверяется содержимое ветки `main` нового репозитория в Gitea, а не файл в `template/`.
|
|
||||||
- На живой системе шаблон уходит в Gitea с выкаткой (PEP-242); проверка после выкатки —
|
|
||||||
`peppa template check` («unchanged») и создание тестового проекта. Из песочницы агента живой
|
|
||||||
Gitea шаблона недоступен — это шаг для суперадмина после выкатки, описан в результате.
|
|
||||||
@ -1,22 +0,0 @@
|
|||||||
# PEP-284: AGENTS.md и шаблон новых проектов по FORGE Default Stack
|
|
||||||
|
|
||||||
## Why
|
|
||||||
Стандарт стека (PEP-283) лежит только в репозитории платформы — агент нового проекта его не видит:
|
|
||||||
в контейнере у него лишь рабочая копия проекта. Новые проекты должны получать предпочтительный
|
|
||||||
стек, DDD-Lite и правило отклонений прямо в своих инструкциях, а существующие — не мигрировать
|
|
||||||
и не терять свои инструкции.
|
|
||||||
|
|
||||||
## What Changes
|
|
||||||
- `template/docs/standards/default-stack.md` — копия стандарта в шаблоне (одна версия с
|
|
||||||
`docs/standards/default-stack.md`; тест сверяет файлы побайтно).
|
|
||||||
- `template/AGENTS.md` — раздел «Стек»: сводка предпочтительного стека, DDD-Lite, ссылка на
|
|
||||||
источник стандарта, правило отклонений, «существующий стек важнее, сам не мигрируй».
|
|
||||||
- `template/RULES.md` — короткий раздел «Стек проекта» для всех проектов (в том числе старых):
|
|
||||||
как выбирать стек, отклонения, не мигрировать, чужие разделы `AGENTS.md` не переписывать.
|
|
||||||
- Тест: шаблон уходит в Gitea (`syncTemplate`), затем создание проекта — в его репозитории
|
|
||||||
оказываются актуальные `AGENTS.md` и стандарт из шаблона Gitea; подключённый репозиторий со
|
|
||||||
своим `AGENTS.md` его сохраняет.
|
|
||||||
|
|
||||||
## Impact
|
|
||||||
- `template/` (уходит в Gitea с выкаткой, PEP-242), `packages/testkit/test/template-default-stack.test.ts`.
|
|
||||||
- Код создания проекта не меняется: он уже копирует только недостающие файлы шаблона.
|
|
||||||
@ -1,35 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
|
|
||||||
### Requirement: Новый проект получает стандарт стека в своих инструкциях
|
|
||||||
Шаблон проектов SHALL содержать `docs/standards/default-stack.md`, совпадающий с документом
|
|
||||||
стандарта платформы, и раздел «Стек» в `AGENTS.md` со сводкой предпочтительного стека, правилами
|
|
||||||
DDD-Lite, ссылкой на источник стандарта и правилом отклонений. Новый проект SHALL получать эти
|
|
||||||
файлы из репозитория шаблона в Gitea при создании.
|
|
||||||
|
|
||||||
#### Scenario: Создание нового проекта
|
|
||||||
- **GIVEN** шаблон из выкатываемого коммита отправлен в репозиторий шаблона Gitea
|
|
||||||
- **WHEN** пользователь создаёт новый проект «stack-demo»
|
|
||||||
- **THEN** в ветке `main` репозитория «stack-demo» `AGENTS.md` совпадает с `AGENTS.md` шаблона и содержит раздел «Стек»
|
|
||||||
- **AND** `docs/standards/default-stack.md` репозитория совпадает со стандартом платформы
|
|
||||||
|
|
||||||
#### Scenario: Копия стандарта в шаблоне отстала
|
|
||||||
- **GIVEN** в `docs/standards/default-stack.md` платформы поднята версия
|
|
||||||
- **AND** `template/docs/standards/default-stack.md` не обновлён
|
|
||||||
- **WHEN** запускаются проверки платформы
|
|
||||||
- **THEN** тест падает с сообщением, что копия стандарта в шаблоне отличается
|
|
||||||
|
|
||||||
### Requirement: Существующий стек и инструкции проекта важнее стандарта
|
|
||||||
Общие правила агентов (`RULES.md`) SHALL говорить, что стек, записанный в проекте, важнее
|
|
||||||
стандарта, что агент не мигрирует существующий проект на стандарт сам и что отклонение
|
|
||||||
записывается в `design.md` и память проекта. Подключение существующего репозитория SHALL NOT
|
|
||||||
перезаписывать его `AGENTS.md`.
|
|
||||||
|
|
||||||
#### Scenario: Подключение репозитория со своим AGENTS.md
|
|
||||||
- **GIVEN** у репозитория «legacy-app» есть свой `AGENTS.md` с текстом «Стек: Python + Django»
|
|
||||||
- **WHEN** владелец подключает его как существующий проект
|
|
||||||
- **THEN** `AGENTS.md` в ветке `main` по-прежнему содержит «Стек: Python + Django» и не содержит раздел «Стек» шаблона
|
|
||||||
|
|
||||||
#### Scenario: Агент в проекте на другом стеке
|
|
||||||
- **GIVEN** проект на Python, стек записан в его `AGENTS.md`
|
|
||||||
- **WHEN** агент читает общие правила FORGE
|
|
||||||
- **THEN** раздел «Стек проекта» велит оставить стек проекта и не переводить его на стандарт без задачи
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
## 1. Шаблон
|
|
||||||
- [x] 1.1 `template/docs/standards/default-stack.md` — копия стандарта
|
|
||||||
- [x] 1.2 `template/AGENTS.md` — раздел «Стек» (сводка, DDD-Lite, ссылка, отклонения, без миграции)
|
|
||||||
- [x] 1.3 `template/RULES.md` — раздел «Стек проекта»
|
|
||||||
|
|
||||||
## 2. Проверка
|
|
||||||
- [x] 2.1 Тест `template-default-stack.test.ts`: копия совпадает, разделы на месте, новый проект получает их из шаблона Gitea, свой `AGENTS.md` подключённого репозитория сохраняется
|
|
||||||
- [x] 2.2 Проверки проекта (lint, typecheck, тесты)
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
# Design: PEP-285 — аудит стека FORGE
|
|
||||||
|
|
||||||
## Подход
|
|
||||||
|
|
||||||
- Источник истины — сам репозиторий на `main` (b664e6ad, 2026-11-27): `package.json` пакетов,
|
|
||||||
`packages/db/src/schema.ts`, `infra/docker-compose.yml`, `infra/platform/Dockerfile`,
|
|
||||||
`.gitea/workflows/ci.yml`, `core/error-report.ts`, `core/service-log.ts`, архив change PEP-36
|
|
||||||
(замеры SQLite/Postgres/bun:sqlite). Каждое утверждение отчёта ссылается на файл.
|
|
||||||
- Цифры (строки кода, таблицы, число имён env) сняты командами, записаны в отчёте с командой,
|
|
||||||
чтобы их можно было пересчитать.
|
|
||||||
- Шкала статусов — из постановки: соответствует / частично / отклонение / неприменимо.
|
|
||||||
Трудоёмкость — S (≤ 2 дней агента), M (≤ 2 недель), L (месяц+), XL (переписывание).
|
|
||||||
Приоритет — P1 (сделать в ближайшие задачи), P2 (по поводу), P3 (не делать без нового повода),
|
|
||||||
«сохранить» — осознанно не менять.
|
|
||||||
|
|
||||||
## Решения
|
|
||||||
|
|
||||||
- **Отчёт — отдельный файл рядом со стандартом**, а не раздел стандарта: стандарт описывает «как надо»
|
|
||||||
для всех проектов, аудит — снимок одной платформы на дату; у них разные циклы обновления.
|
|
||||||
- **PEP-36 не считается ошибкой.** Решение принималось по замеру (SQLite быстрее Postgres на нагрузке
|
|
||||||
FORGE в 30–50 раз по p50, без отдельного сервиса) и одобрено владельцем; Bun-рантайм тогда
|
|
||||||
рассматривался и отвергнут в пользу Node 26. Отклонение от стандарта по базе фиксируется как
|
|
||||||
обоснованное, с условиями, при которых пересматривать.
|
|
||||||
- **«Bun» стандарта — Go ORM**, к JS-рантайму Bun из PEP-36 отношения не имеет; в отчёте это разведено явно.
|
|
||||||
- **Решения владельцу** оформлены в отчёте разделом «На рассмотрение владельцу» (простыми словами),
|
|
||||||
без `ask_pm`: правила FORGE запрещают выносить PM технический выбор, а предложения — это
|
|
||||||
рекомендации, которые владелец может взять задачами. Вопрос не нужен, чтобы закончить аудит.
|
|
||||||
- **Новых задач не завожу** (лимит предложений агентов; кандидаты перечислены в roadmap).
|
|
||||||
- **Тест** проверяет структуру отчёта (все слои стандарта, статус из шкалы, пять отдельных разделов,
|
|
||||||
roadmap, ссылка из стандарта) — чтобы при изменении стандарта отчёт не устаревал молча.
|
|
||||||
@ -1,29 +0,0 @@
|
|||||||
# Proposal: PEP-285 — аудит стека FORGE относительно Default Stack
|
|
||||||
|
|
||||||
Задача FORGE: **PEP-285** · Эпик #18 «Engineering Standards».
|
|
||||||
|
|
||||||
## Why
|
|
||||||
|
|
||||||
PEP-283 принял FORGE Default Stack (Go/Gin/Bun/Viper, PostgreSQL, React+TanStack+Vite, Loki+Grafana…)
|
|
||||||
как ориентир для новых проектов. Сама FORGE написана раньше и иначе (TypeScript на Node 26, Next.js,
|
|
||||||
SQLite — решение PEP-36). Владельцу нужен доказательный разбор: где FORGE совпадает со стандартом,
|
|
||||||
где отклоняется и почему, что стоит менять, а что сохранить, — без миграций в рамках аудита.
|
|
||||||
|
|
||||||
## What Changes
|
|
||||||
|
|
||||||
- Новый документ `docs/standards/forge-stack-audit.md`: по каждому слою стандарта — текущий стек FORGE
|
|
||||||
с источниками в репозитории, желаемый стандарт, статус (соответствует / частично / отклонение /
|
|
||||||
неприменимо), причина, риски и выгоды изменения, трудоёмкость, приоритет.
|
|
||||||
- Отдельные разделы: DDD-Lite; PostgreSQL + UUIDv7 + pg_stat_statements; Bugsink; Gitea/Forgejo; Docker.
|
|
||||||
- Поэтапный roadmap и список решений на рассмотрение владельцу; где стек сохраняем — с обоснованием.
|
|
||||||
- Ссылка на аудит из `docs/standards/default-stack.md`; тест структуры отчёта.
|
|
||||||
- Код платформы, база, миграции и выкатка **не меняются**.
|
|
||||||
|
|
||||||
## Capabilities
|
|
||||||
|
|
||||||
### Modified Capabilities
|
|
||||||
- `engineering-standards`: добавлено требование об аудите платформы относительно стандарта.
|
|
||||||
|
|
||||||
## Impact
|
|
||||||
|
|
||||||
- Только документация и один тест (`packages/testkit/test/stack-audit-doc.test.ts`).
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
|
|
||||||
### Requirement: Аудит платформы относительно стандарта
|
|
||||||
FORGE SHALL хранить отчёт `docs/standards/forge-stack-audit.md` со сравнением стека самой платформы
|
|
||||||
с FORGE Default Stack. Для каждого слоя стандарта отчёт SHALL указывать текущий стек с источниками
|
|
||||||
в репозитории, статус из шкалы «соответствует / частично / отклонение / неприменимо», трудоёмкость
|
|
||||||
и приоритет изменения. Отчёт SHALL содержать отдельные разделы о DDD-Lite, PostgreSQL/UUIDv7/
|
|
||||||
pg_stat_statements, Bugsink, Gitea/Forgejo и Docker, поэтапный roadmap и решения на рассмотрение
|
|
||||||
владельцу. Стандарт SHALL ссылаться на отчёт. Аудит SHALL NOT менять код, базу и выкатку платформы.
|
|
||||||
|
|
||||||
#### Scenario: Владелец смотрит, где FORGE отличается от стандарта
|
|
||||||
- **GIVEN** репозиторий платформы с документом `docs/standards/forge-stack-audit.md`
|
|
||||||
- **WHEN** владелец открывает таблицу слоёв
|
|
||||||
- **THEN** у слоя «База данных: PostgreSQL» он видит текущий выбор «SQLite», статус «отклонение» и ссылку на решение PEP-36
|
|
||||||
- **AND** у слоя «Аналитика: GA4» видит статус «неприменимо»
|
|
||||||
|
|
||||||
#### Scenario: В стандарт добавили слой, а отчёт не обновили
|
|
||||||
- **GIVEN** в `docs/standards/default-stack.md` появился новый раздел слоя «### Очереди: NATS»
|
|
||||||
- **WHEN** выполняются тесты платформы
|
|
||||||
- **THEN** тест отчёта падает с сообщением, что в аудите нет слоя «Очереди: NATS»
|
|
||||||
|
|
||||||
#### Scenario: Статус вне шкалы
|
|
||||||
- **GIVEN** в таблице отчёта у слоя записан статус «почти»
|
|
||||||
- **WHEN** выполняются тесты платформы
|
|
||||||
- **THEN** тест падает и называет слой с неверным статусом
|
|
||||||
@ -1,12 +0,0 @@
|
|||||||
## 1. Аудит
|
|
||||||
- [x] 1.1 Собрать факты по слоям (зависимости, схема, infra, CI, ошибки, логи) с источниками
|
|
||||||
- [x] 1.2 `docs/standards/forge-stack-audit.md`: таблица слоёв, разбор по слоям
|
|
||||||
- [x] 1.3 Отдельно: DDD-Lite, PostgreSQL/UUIDv7/pg_stat_statements, Bugsink, Gitea/Forgejo, Docker
|
|
||||||
- [x] 1.4 Roadmap и решения на рассмотрение владельцу
|
|
||||||
|
|
||||||
## 2. Ссылки и проверка
|
|
||||||
- [x] 2.1 Ссылка из `docs/standards/default-stack.md`
|
|
||||||
- [x] 2.2 Тест `stack-audit-doc.test.ts`
|
|
||||||
|
|
||||||
## 3. Завершение
|
|
||||||
- [x] 3.1 Проверки локально, память, archive, PR
|
|
||||||
@ -313,7 +313,6 @@ SHALL отправить владельцу одно сообщение.
|
|||||||
- **WHEN** агент «SHOP» делает запись через «stripe»
|
- **WHEN** агент «SHOP» делает запись через «stripe»
|
||||||
- **THEN** вызов отклонён
|
- **THEN** вызов отклонён
|
||||||
- **AND** создан запрос доступа «SHOP» к «stripe» на запись, агенту сказано, что доступ запрошен
|
- **AND** создан запрос доступа «SHOP» к «stripe» на запись, агенту сказано, что доступ запрошен
|
||||||
|
|
||||||
### Requirement: Базы данных, серверы, хранилища и почта через FORGE
|
### Requirement: Базы данных, серверы, хранилища и почта через FORGE
|
||||||
Пользователь SHALL подключать базу данных PostgreSQL или MySQL, сервер по SSH, хранилище S3 и почтовый ящик: адрес, пользователь и пароль (или ключ). Агент SHALL работать с ними только операциями FORGE и никогда не получать пароль или ключ. Каждая операция SHALL быть чтением или записью и разрешаться режимами владельца («сразу», «спрашивать меня», «нет»).
|
Пользователь SHALL подключать базу данных PostgreSQL или MySQL, сервер по SSH, хранилище S3 и почтовый ящик: адрес, пользователь и пароль (или ключ). Агент SHALL работать с ними только операциями FORGE и никогда не получать пароль или ключ. Каждая операция SHALL быть чтением или записью и разрешаться режимами владельца («сразу», «спрашивать меня», «нет»).
|
||||||
|
|
||||||
@ -578,44 +577,3 @@ FORGE SHALL закреплять ключ SSH-сервера: отпечаток
|
|||||||
- **GIVEN** сервис отзыва недоступен
|
- **GIVEN** сервис отзыва недоступен
|
||||||
- **WHEN** владелец отзывает подключение
|
- **WHEN** владелец отзывает подключение
|
||||||
- **THEN** подключение в FORGE отозвано и токены стёрты
|
- **THEN** подключение в FORGE отозвано и токены стёрты
|
||||||
|
|
||||||
### Requirement: Кнопки выдачи под запросом доступа
|
|
||||||
Под сообщением о запросе доступа агента (Telegram и «Агенты просят доступ» в вебе) владелец проекта SHALL видеть «Дать: чтение», «Дать: полные права» и «Отказать». После выбора прав SHALL выбираться срок: 1 час, 1 день, 7 дней или до отзыва; по умолчанию — 1 день. Разрешение SHALL выдаваться проекту запроса на выбранный срок, действующее разрешение проекта SHALL только расширяться по правам; разрешение, срок которого вышел или которое снято без дела, SHALL NOT добавлять новому ни прав, ни операций. Если подходящего подключения нет, владелец SHALL получать ссылку на карточку запроса с шагами подключения, где тоже выбираются права и срок. Нажимать кнопки SHALL только владелец; решение SHALL доходить до агента.
|
|
||||||
|
|
||||||
#### Scenario: Чтение на 1 день кнопкой в Telegram
|
|
||||||
- **GIVEN** у «anna» подключение «CRM» и открытый запрос агента проекта «SHOP» к нему
|
|
||||||
- **WHEN** «anna» нажимает «Дать: чтение», затем «1 день»
|
|
||||||
- **THEN** проекту «SHOP» выдано чтение «CRM» на 1 день
|
|
||||||
- **AND** запрос закрыт как выданный, агент получает «доступ выдан: чтение на 1 день»
|
|
||||||
- **AND** агент читает `GET /items`, а через 25 часов получает отказ «срок доступа истёк»
|
|
||||||
|
|
||||||
#### Scenario: Чужой не может нажать «Дать»
|
|
||||||
- **GIVEN** открытый запрос проекта «SHOP» владельца «anna»
|
|
||||||
- **WHEN** пользователь «boris» нажимает «Дать: полные права» и «до отзыва»
|
|
||||||
- **THEN** он получает «Запрос не найден»
|
|
||||||
- **AND** разрешение не выдано, запрос остаётся открытым
|
|
||||||
|
|
||||||
#### Scenario: Подключения ещё нет
|
|
||||||
- **GIVEN** открытый запрос «SHOP» к «stripe», у «anna» нет подключения Stripe
|
|
||||||
- **WHEN** приходит сообщение о запросе
|
|
||||||
- **THEN** в нём ссылка «Подключить» и «Отказать», без «Дать»
|
|
||||||
- **AND** нажатие «Дать: чтение» в старом сообщении отвечает «Подключения ещё нет — откройте запрос и подключите сервис»
|
|
||||||
|
|
||||||
#### Scenario: Срок на карточке запроса
|
|
||||||
- **GIVEN** открытый запрос «SHOP» к «stripe» без подключения
|
|
||||||
- **WHEN** «anna» вставляет ключ, выбирает «полные права» и «7 дней» и нажимает «Подключить и разрешить»
|
|
||||||
- **THEN** проекту выдано чтение и запись «Stripe» на 7 дней
|
|
||||||
|
|
||||||
#### Scenario: Чтение после истёкших полных прав
|
|
||||||
- **GIVEN** проекту «SHOP» были выданы полные права «CRM» на 1 час, срок вышел
|
|
||||||
- **WHEN** агент просит доступ снова, и «anna» нажимает «Дать: чтение», затем «1 день»
|
|
||||||
- **THEN** проекту выдано только чтение «CRM» на 1 день
|
|
||||||
- **AND** запрос агента на изменение данных получает отказ
|
|
||||||
|
|
||||||
### Requirement: Истёкший доступ — новый запрос
|
|
||||||
Отказ шлюза из-за истёкшего срока или снятого без дела разрешения SHALL подсказывать агенту попросить доступ снова через `request_access` с названием сервиса.
|
|
||||||
|
|
||||||
#### Scenario: Отказ после истечения
|
|
||||||
- **GIVEN** разрешение «CRM» на 1 час выдано 2 часа назад
|
|
||||||
- **WHEN** агент вызывает «crm»
|
|
||||||
- **THEN** отказ «срок доступа истёк» и подсказка `request_access`
|
|
||||||
|
|||||||
@ -103,19 +103,3 @@ TBD - created by archiving change pep-198-one-analyst. Update Purpose after arch
|
|||||||
- **WHEN** вачдог проверяет задачи
|
- **WHEN** вачдог проверяет задачи
|
||||||
- **THEN** суперадмин получает сообщение о PEP-7
|
- **THEN** суперадмин получает сообщение о PEP-7
|
||||||
- **AND** владелец получает одну строку «Задача PEP-7 задерживается на нашей стороне»
|
- **AND** владелец получает одну строку «Задача PEP-7 задерживается на нашей стороне»
|
||||||
|
|
||||||
### Requirement: Подписки в лимите — не «нет подписки»
|
|
||||||
Когда у проекта есть подписки Claude, но все в лимите, Аналитик SHALL называть причину «подписки в лимите до ЧЧ:ММ» (время в поясе платформы) и повторять разбор задачи после сброса, не отпуская её «как написана». Когда подписок нет, причина SHALL оставаться «у проекта не подключена подписка».
|
|
||||||
|
|
||||||
#### Scenario: Все подписки в лимите
|
|
||||||
- **GIVEN** у проекта GARDEN одна подписка Claude в лимите до 23:50
|
|
||||||
- **AND** в бэклоге новая задача GARDEN-12 ждёт разбора
|
|
||||||
- **WHEN** аналитик берётся за разбор
|
|
||||||
- **THEN** в обсуждении задачи заметка «подписки проекта в лимите до 23:50»
|
|
||||||
- **AND** нет слов «не подключена подписка»
|
|
||||||
- **AND** после 23:51 разбор выполняется снова
|
|
||||||
|
|
||||||
#### Scenario: Подписки нет
|
|
||||||
- **GIVEN** у проекта нет ни одной подписки, владелец зарегистрировался сам
|
|
||||||
- **WHEN** аналитик дважды пытается разобрать задачу
|
|
||||||
- **THEN** заметка «у проекта не подключена подписка»
|
|
||||||
|
|||||||
@ -61,61 +61,3 @@ SHALL падать, если документ пропал, потерял сл
|
|||||||
- **GIVEN** из документа удалён раздел «PostgreSQL»
|
- **GIVEN** из документа удалён раздел «PostgreSQL»
|
||||||
- **WHEN** выполняются тесты платформы
|
- **WHEN** выполняются тесты платформы
|
||||||
- **THEN** тест падает с названием пропавшего слоя
|
- **THEN** тест падает с названием пропавшего слоя
|
||||||
|
|
||||||
### Requirement: Новый проект получает стандарт стека в своих инструкциях
|
|
||||||
Шаблон проектов SHALL содержать `docs/standards/default-stack.md`, совпадающий с документом
|
|
||||||
стандарта платформы, и раздел «Стек» в `AGENTS.md` со сводкой предпочтительного стека, правилами
|
|
||||||
DDD-Lite, ссылкой на источник стандарта и правилом отклонений. Новый проект SHALL получать эти
|
|
||||||
файлы из репозитория шаблона в Gitea при создании.
|
|
||||||
|
|
||||||
#### Scenario: Создание нового проекта
|
|
||||||
- **GIVEN** шаблон из выкатываемого коммита отправлен в репозиторий шаблона Gitea
|
|
||||||
- **WHEN** пользователь создаёт новый проект «stack-demo»
|
|
||||||
- **THEN** в ветке `main` репозитория «stack-demo» `AGENTS.md` совпадает с `AGENTS.md` шаблона и содержит раздел «Стек»
|
|
||||||
- **AND** `docs/standards/default-stack.md` репозитория совпадает со стандартом платформы
|
|
||||||
|
|
||||||
#### Scenario: Копия стандарта в шаблоне отстала
|
|
||||||
- **GIVEN** в `docs/standards/default-stack.md` платформы поднята версия
|
|
||||||
- **AND** `template/docs/standards/default-stack.md` не обновлён
|
|
||||||
- **WHEN** запускаются проверки платформы
|
|
||||||
- **THEN** тест падает с сообщением, что копия стандарта в шаблоне отличается
|
|
||||||
|
|
||||||
### Requirement: Существующий стек и инструкции проекта важнее стандарта
|
|
||||||
Общие правила агентов (`RULES.md`) SHALL говорить, что стек, записанный в проекте, важнее
|
|
||||||
стандарта, что агент не мигрирует существующий проект на стандарт сам и что отклонение
|
|
||||||
записывается в `design.md` и память проекта. Подключение существующего репозитория SHALL NOT
|
|
||||||
перезаписывать его `AGENTS.md`.
|
|
||||||
|
|
||||||
#### Scenario: Подключение репозитория со своим AGENTS.md
|
|
||||||
- **GIVEN** у репозитория «legacy-app» есть свой `AGENTS.md` с текстом «Стек: Python + Django»
|
|
||||||
- **WHEN** владелец подключает его как существующий проект
|
|
||||||
- **THEN** `AGENTS.md` в ветке `main` по-прежнему содержит «Стек: Python + Django» и не содержит раздел «Стек» шаблона
|
|
||||||
|
|
||||||
#### Scenario: Агент в проекте на другом стеке
|
|
||||||
- **GIVEN** проект на Python, стек записан в его `AGENTS.md`
|
|
||||||
- **WHEN** агент читает общие правила FORGE
|
|
||||||
- **THEN** раздел «Стек проекта» велит оставить стек проекта и не переводить его на стандарт без задачи
|
|
||||||
|
|
||||||
### Requirement: Аудит платформы относительно стандарта
|
|
||||||
FORGE SHALL хранить отчёт `docs/standards/forge-stack-audit.md` со сравнением стека самой платформы
|
|
||||||
с FORGE Default Stack. Для каждого слоя стандарта отчёт SHALL указывать текущий стек с источниками
|
|
||||||
в репозитории, статус из шкалы «соответствует / частично / отклонение / неприменимо», трудоёмкость
|
|
||||||
и приоритет изменения. Отчёт SHALL содержать отдельные разделы о DDD-Lite, PostgreSQL/UUIDv7/
|
|
||||||
pg_stat_statements, Bugsink, Gitea/Forgejo и Docker, поэтапный roadmap и решения на рассмотрение
|
|
||||||
владельцу. Стандарт SHALL ссылаться на отчёт. Аудит SHALL NOT менять код, базу и выкатку платформы.
|
|
||||||
|
|
||||||
#### Scenario: Владелец смотрит, где FORGE отличается от стандарта
|
|
||||||
- **GIVEN** репозиторий платформы с документом `docs/standards/forge-stack-audit.md`
|
|
||||||
- **WHEN** владелец открывает таблицу слоёв
|
|
||||||
- **THEN** у слоя «База данных: PostgreSQL» он видит текущий выбор «SQLite», статус «отклонение» и ссылку на решение PEP-36
|
|
||||||
- **AND** у слоя «Аналитика: GA4» видит статус «неприменимо»
|
|
||||||
|
|
||||||
#### Scenario: В стандарт добавили слой, а отчёт не обновили
|
|
||||||
- **GIVEN** в `docs/standards/default-stack.md` появился новый раздел слоя «### Очереди: NATS»
|
|
||||||
- **WHEN** выполняются тесты платформы
|
|
||||||
- **THEN** тест отчёта падает с сообщением, что в аудите нет слоя «Очереди: NATS»
|
|
||||||
|
|
||||||
#### Scenario: Статус вне шкалы
|
|
||||||
- **GIVEN** в таблице отчёта у слоя записан статус «почти»
|
|
||||||
- **WHEN** выполняются тесты платформы
|
|
||||||
- **THEN** тест падает и называет слой с неверным статусом
|
|
||||||
|
|||||||
@ -84,44 +84,35 @@
|
|||||||
- **GIVEN** `bob` не суперадмин
|
- **GIVEN** `bob` не суперадмин
|
||||||
- **WHEN** он пытается закрыть репозиторий `alice/demo` этим действием
|
- **WHEN** он пытается закрыть репозиторий `alice/demo` этим действием
|
||||||
- **THEN** получает отказ, видимость в Gitea не меняется
|
- **THEN** получает отказ, видимость в Gitea не меняется
|
||||||
|
|
||||||
### Requirement: Платформа не ссылается на старый Git
|
### Requirement: Платформа не ссылается на старый Git
|
||||||
|
|
||||||
Код, документы, примеры настроек и тестовые данные платформы SHALL не содержать адрес старой Gitea
|
Код, документы, примеры настроек и тестовые данные платформы SHALL не содержать адрес старой Gitea
|
||||||
`git.telecom.quest` и переменную `GITEA_OLD_TOKEN`; значение по умолчанию и запасной адрес Gitea —
|
`git.telecom.quest` и переменную `GITEA_OLD_TOKEN`; значение по умолчанию и запасной адрес Gitea —
|
||||||
`https://git.vibe42.kz`. История изменений (`openspec/changes/archive/`) не проверяется.
|
`https://git.vibe42.kz`. История изменений (`openspec/changes/archive/`) не проверяется.
|
||||||
|
|
||||||
#### Scenario: В репозитории нет старого адреса
|
#### Scenario: В репозитории нет старого адреса
|
||||||
- **GIVEN** отслеживаемые файлы репозитория, кроме архива OpenSpec
|
- **GIVEN** отслеживаемые файлы репозитория, кроме архива OpenSpec
|
||||||
- **WHEN** запускается тест-сторож
|
- **WHEN** запускается тест-сторож
|
||||||
- **THEN** ни в одном файле нет строк «git.telecom.quest» и «GITEA_OLD_TOKEN»
|
- **THEN** ни в одном файле нет строк «git.telecom.quest» и «GITEA_OLD_TOKEN»
|
||||||
|
|
||||||
#### Scenario: GITEA_URL не задан
|
#### Scenario: GITEA_URL не задан
|
||||||
- **GIVEN** окружение без `GITEA_URL`
|
- **GIVEN** окружение без `GITEA_URL`
|
||||||
- **WHEN** платформа читает настройки
|
- **WHEN** платформа читает настройки
|
||||||
- **THEN** адрес Gitea — `https://git.vibe42.kz`
|
- **THEN** адрес Gitea — `https://git.vibe42.kz`
|
||||||
|
|
||||||
#### Scenario: Мониторинг «Интернет», созданный до переезда
|
#### Scenario: Мониторинг «Интернет», созданный до переезда
|
||||||
- **GIVEN** в базе мониторинга есть монитор «Интернет» с адресами «registry.npmjs.org, git.telecom.quest»
|
- **GIVEN** в базе мониторинга есть монитор «Интернет» с адресами «registry.npmjs.org, git.telecom.quest»
|
||||||
- **WHEN** сервис мониторинга открывает базу новой версии
|
- **WHEN** сервис мониторинга открывает базу новой версии
|
||||||
- **THEN** адреса монитора — «registry.npmjs.org, git.vibe42.kz»
|
- **THEN** адреса монитора — «registry.npmjs.org, git.vibe42.kz»
|
||||||
|
|
||||||
#### Scenario: Новый адрес уже был в списке
|
#### Scenario: Новый адрес уже был в списке
|
||||||
- **GIVEN** монитор «Интернет» с адресами «git.vibe42.kz, git.telecom.quest»
|
- **GIVEN** монитор «Интернет» с адресами «git.vibe42.kz, git.telecom.quest»
|
||||||
- **WHEN** сервис мониторинга открывает базу новой версии
|
- **WHEN** сервис мониторинга открывает базу новой версии
|
||||||
- **THEN** адреса монитора — «git.vibe42.kz», без повтора
|
- **THEN** адреса монитора — «git.vibe42.kz», без повтора
|
||||||
|
|
||||||
### Requirement: Таймаут запроса к Gitea не съедает пауза процесса
|
### Requirement: Таймаут запроса к Gitea не съедает пауза процесса
|
||||||
Запрос FORGE к Gitea SHALL обрываться по таймауту (15 с, `PEPPA_GITEA_TIMEOUT_MS`), считая
|
Запрос FORGE к Gitea SHALL обрываться по таймауту (15 с, `PEPPA_GITEA_TIMEOUT_MS`), считая
|
||||||
только время, когда процесс отзывчив: синхронная пауза процесса засчитывается не больше
|
только время, когда процесс отзывчив: синхронная пауза процесса засчитывается не больше
|
||||||
чем на секунду, и ответ, пришедший во время паузы, SHALL быть принят.
|
чем на секунду, и ответ, пришедший во время паузы, SHALL быть принят.
|
||||||
|
|
||||||
#### Scenario: Процесс занят, ответ уже пришёл
|
#### Scenario: Процесс занят, ответ уже пришёл
|
||||||
- **GIVEN** таймаут запроса к Gitea 300 мс
|
- **GIVEN** таймаут запроса к Gitea 300 мс
|
||||||
- **AND** Gitea отвечает сразу
|
- **AND** Gitea отвечает сразу
|
||||||
- **WHEN** процесс FORGE после отправки запроса 800 мс занят синхронной работой
|
- **WHEN** процесс FORGE после отправки запроса 800 мс занят синхронной работой
|
||||||
- **THEN** запрос возвращает ответ Gitea, а не ошибку таймаута
|
- **THEN** запрос возвращает ответ Gitea, а не ошибку таймаута
|
||||||
|
|
||||||
#### Scenario: Gitea не отвечает
|
#### Scenario: Gitea не отвечает
|
||||||
- **GIVEN** таймаут запроса к Gitea 300 мс
|
- **GIVEN** таймаут запроса к Gitea 300 мс
|
||||||
- **AND** Gitea принимает соединение и не отвечает
|
- **AND** Gitea принимает соединение и не отвечает
|
||||||
|
|||||||
@ -521,43 +521,3 @@ SHALL считаться потерянной. Потерянная провер
|
|||||||
- **WHEN** владелец отвечает «Закрыть»
|
- **WHEN** владелец отвечает «Закрыть»
|
||||||
- **THEN** задачи уходят в архив
|
- **THEN** задачи уходят в архив
|
||||||
- **AND** следующая сверка не спрашивает о них снова
|
- **AND** следующая сверка не спрашивает о них снова
|
||||||
|
|
||||||
### Requirement: Ложный «конфликт» сразу после обновления не зовёт агента
|
|
||||||
FORGE SHALL отправлять первую просьбу обновить изменения, только если та же версия результата
|
|
||||||
конфликтует с основной веткой и спустя `CONFLICT_SETTLE_MIN` (2 минуты) после первого
|
|
||||||
наблюдения. Новая версия результата SHALL начинать ожидание заново. Задачу, которую перевели с
|
|
||||||
проверки в работу ради конфликта, FORGE SHALL вернуть на проверку сама, если конфликт снят,
|
|
||||||
агент не запускался и версия результата не менялась.
|
|
||||||
|
|
||||||
#### Scenario: Gitea две минуты после обновления ветки отвечает «конфликт»
|
|
||||||
- **GIVEN** задача PEP-257 на проверке, FORGE обновила ветку её результата
|
|
||||||
- **AND** Gitea первые две минуты отвечает, что изменения конфликтуют
|
|
||||||
- **WHEN** FORGE видит конфликт, а через минуту и через две смотрит снова
|
|
||||||
- **THEN** агент не получает просьбы и не запускается
|
|
||||||
- **AND** задача остаётся на проверке
|
|
||||||
|
|
||||||
#### Scenario: Настоящий конфликт
|
|
||||||
- **GIVEN** задача на проверке, её результат конфликтует с основной веткой
|
|
||||||
- **WHEN** конфликт держится 2 минуты на той же версии
|
|
||||||
- **THEN** агент получает одну просьбу обновить изменения
|
|
||||||
|
|
||||||
#### Scenario: Зря переведённая в работу задача возвращается сама
|
|
||||||
- **GIVEN** задачу перевели с проверки в работу ради конфликта, агент ждёт места и не запускался
|
|
||||||
- **WHEN** конфликт исчез, а версия результата прежняя
|
|
||||||
- **THEN** задача снова на проверке, место агента в очереди освобождено
|
|
||||||
|
|
||||||
#### Scenario: Агент уже обновил изменения
|
|
||||||
- **GIVEN** задачу перевели в работу ради конфликта, и в результате появилась новая версия
|
|
||||||
- **WHEN** конфликт исчез
|
|
||||||
- **THEN** задача остаётся в работе — агент передаст её сам
|
|
||||||
|
|
||||||
### Requirement: Карточка задачи и допуск считают проверки по одному списку
|
|
||||||
Сводка проверок на карточке задачи и в `get_task` SHALL считать проверки по списку из
|
|
||||||
`.peppa/project.json` той версии результата, на которой они шли, — тем же, что и допуск к
|
|
||||||
проверке и слиянию.
|
|
||||||
|
|
||||||
#### Scenario: В версии результата нужна проверка, которой нет в основной копии
|
|
||||||
- **GIVEN** в последней версии результата нужны lint, build, typecheck и test, а в основной копии — только первые три
|
|
||||||
- **AND** test на этой версии не отчитался
|
|
||||||
- **WHEN** агент смотрит задачу, а FORGE проверяет допуск
|
|
||||||
- **THEN** оба показывают «Проверки идут: 3 из 4»
|
|
||||||
|
|||||||
@ -1,19 +0,0 @@
|
|||||||
# platform-time Specification
|
|
||||||
|
|
||||||
## Purpose
|
|
||||||
TBD - created by archiving change pep-304-limit-reason-platform-time. Update Purpose after archive.
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
### Requirement: Время для людей — в поясе платформы
|
|
||||||
Время в сообщениях и подписях для людей SHALL показываться в поясе платформы `PEPPA_TZ`, а не в поясе процесса; неверное имя пояса SHALL не ломать сообщение.
|
|
||||||
|
|
||||||
#### Scenario: Пояс платформы отличается от пояса сервера
|
|
||||||
- **GIVEN** процесс работает в UTC, `PEPPA_TZ` = «Asia/Almaty»
|
|
||||||
- **WHEN** сообщение называет момент 2026-11-25 18:35 UTC
|
|
||||||
- **THEN** в тексте «23:35»
|
|
||||||
|
|
||||||
#### Scenario: Неверный пояс
|
|
||||||
- **GIVEN** `PEPPA_TZ` = «Not/AZone»
|
|
||||||
- **WHEN** сообщение называет время
|
|
||||||
- **THEN** сообщение отправляется со временем в поясе процесса
|
|
||||||
@ -287,6 +287,6 @@ nonce, созданные сервером для этого потока; по
|
|||||||
|
|
||||||
| адрес | показ |
|
| адрес | показ |
|
||||||
|---|---|
|
|---|---|
|
||||||
| http://git.vibe42.kz/avatars/1 | https://git.vibe42.kz/avatars/1 |
|
| http://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 |
|
||||||
| https://git.vibe42.kz/avatars/1 | https://git.vibe42.kz/avatars/1 |
|
| https://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 |
|
||||||
| javascript:alert(1) | нет картинки |
|
| javascript:alert(1) | нет картинки |
|
||||||
|
|||||||
@ -10,7 +10,7 @@ import { lookup as dnsLookup } from "node:dns/promises";
|
|||||||
import { logEvent } from "./audit.ts";
|
import { logEvent } from "./audit.ts";
|
||||||
import { addMasterMessage } from "./chats.ts";
|
import { addMasterMessage } from "./chats.ts";
|
||||||
import { catalogService, CONNECTION_CATALOG, type CatalogService } from "./connection-catalog.ts";
|
import { catalogService, CONNECTION_CATALOG, type CatalogService } from "./connection-catalog.ts";
|
||||||
import { agentConnections, createConnection, DEFAULT_GRANT_TERM, GRANT_RIGHTS, GRANT_TERM_TEXT, GRANT_TERMS, grantConnection, grantState, isBlockedAddress, isGrantTerm, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode, type GrantRights, type GrantTerm } from "./connections.ts";
|
import { agentConnections, createConnection, grantConnection, isBlockedAddress, listConnections, parseBaseUrl, type ConnectionInput, type ConnectionView, type GrantMode } from "./connections.ts";
|
||||||
import { PeppaError } from "./errors.ts";
|
import { PeppaError } from "./errors.ts";
|
||||||
import { deliverToUser } from "./notifications.ts";
|
import { deliverToUser } from "./notifications.ts";
|
||||||
import { guardUntrusted } from "./untrusted.ts";
|
import { guardUntrusted } from "./untrusted.ts";
|
||||||
@ -46,9 +46,6 @@ export interface AccessRequestView {
|
|||||||
decidedAt: Date | null;
|
decidedAt: Date | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
/** PEP-261: what was given, right after a grant (not stored on the request; the event has it). */
|
|
||||||
rights?: GrantRights;
|
|
||||||
term?: GrantTerm;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type HostLookup = (host: string) => Promise<string[]>;
|
export type HostLookup = (host: string) => Promise<string[]>;
|
||||||
@ -233,71 +230,23 @@ export async function requestAccess(db: Db, i: AccessRequestInput, o: { lookup?:
|
|||||||
|
|
||||||
export const accessRequestUrl = (id: number) => `/connections/requests/${id}`;
|
export const accessRequestUrl = (id: number) => `/connections/requests/${id}`;
|
||||||
|
|
||||||
/** The text of the owner's message (master chat, Telegram, push). `canGrant` — the owner already has a fitting connection (PEP-261 buttons). */
|
/** The text of the owner's message (master chat, Telegram, push). */
|
||||||
export function accessRequestText(r: AccessRequestView, o: { canGrant?: boolean } = {}): string {
|
export function accessRequestText(r: AccessRequestView): string {
|
||||||
const who = r.agentName ? tr("Агент {name}", { name: asIs(r.agentName) }) : tr("Агент");
|
const who = r.agentName ? tr("Агент {name}", { name: asIs(r.agentName) }) : tr("Агент");
|
||||||
const where = r.taskKey ? tr("{project}, задача {task}", { project: asIs(r.projectName), task: r.taskKey }) : asIs(r.projectName);
|
const where = r.taskKey ? tr("{project}, задача {task}", { project: asIs(r.projectName), task: r.taskKey }) : asIs(r.projectName);
|
||||||
const what = r.mode === "write" ? tr("{service} — читать и менять", { service: asIs(r.service) }) : tr("{service} — только читать", { service: asIs(r.service) });
|
const what = r.mode === "write" ? tr("{service} — читать и менять", { service: asIs(r.service) }) : tr("{service} — только читать", { service: asIs(r.service) });
|
||||||
return [tr("{who} просит доступ: {what}.", { who, what }), tr("Зачем: {purpose}", { purpose: asIs(r.purpose) }), tr("Проект: {where}", { where }), o.canGrant ? tr("Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.") : tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
|
return [tr("{who} просит доступ: {what}.", { who, what }), tr("Зачем: {purpose}", { purpose: asIs(r.purpose) }), tr("Проект: {where}", { where }), tr("Откройте запрос, чтобы подключить сервис или отказать.")].join("\n");
|
||||||
}
|
|
||||||
|
|
||||||
type InlineButton = { text: string; url?: string; callback_data?: string };
|
|
||||||
|
|
||||||
/** PEP-261: the step of the Telegram keyboard under an access request. */
|
|
||||||
export type AccessKeyboardStep = { step: "rights"; canGrant: boolean } | { step: "term"; rights: GrantRights };
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Buttons under the owner's message: «Дать: чтение» · «Дать: полные права» (only with a fitting
|
|
||||||
* connection, otherwise «Подключить» — the request's card with the catalog's steps) · «Отказать»;
|
|
||||||
* after rights — the term (1 day first, the default) and «Назад».
|
|
||||||
* Callback data: `ar:<id>:r|f`, `ar:<id>:r|f:<term>`, `ar:<id>:back`, `ar:<id>:no`.
|
|
||||||
*/
|
|
||||||
export function accessRequestKeyboard(id: number, k: AccessKeyboardStep, o: { webUrl?: string } = {}): InlineButton[][] {
|
|
||||||
const base = (o.webUrl ?? process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
|
|
||||||
const link = base.startsWith("https://") ? `${base}${accessRequestUrl(id)}` : null;
|
|
||||||
if (k.step === "term") {
|
|
||||||
const code = k.rights === "full" ? "f" : "r";
|
|
||||||
const terms = [DEFAULT_GRANT_TERM, ...GRANT_TERMS.filter((t) => t !== DEFAULT_GRANT_TERM)];
|
|
||||||
const label = k.rights === "full" ? tr("Полные права — на какой срок?") : tr("Чтение — на какой срок?");
|
|
||||||
return [
|
|
||||||
[{ text: label, callback_data: `ar:${id}:${code}:${DEFAULT_GRANT_TERM}` }],
|
|
||||||
terms.map((t) => ({ text: GRANT_TERM_TEXT[t], callback_data: `ar:${id}:${code}:${t}` })),
|
|
||||||
[{ text: tr("Назад"), callback_data: `ar:${id}:back` }],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
return [
|
|
||||||
...(k.canGrant
|
|
||||||
? [[{ text: tr("Дать: чтение"), callback_data: `ar:${id}:r` }, { text: tr("Дать: полные права"), callback_data: `ar:${id}:f` }]]
|
|
||||||
: link
|
|
||||||
? [[{ text: tr("Подключить"), url: link }]]
|
|
||||||
: []),
|
|
||||||
[{ text: tr("Отказать"), callback_data: `ar:${id}:no` }],
|
|
||||||
...(k.canGrant && link ? [[{ text: tr("Посмотреть и решить"), url: link }]] : []),
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type AccessCallback = { id: number } & ({ action: "no" } | { action: "back" } | { action: "rights"; rights: GrantRights } | { action: "grant"; rights: GrantRights; term: GrantTerm });
|
|
||||||
|
|
||||||
/** `ar:…` → what was pressed; null — not ours or malformed. */
|
|
||||||
export function parseAccessCallback(data: string): AccessCallback | null {
|
|
||||||
const m = /^ar:(\d+):(no|back|r|f)(?::([a-z0-9]+))?$/.exec(String(data ?? ""));
|
|
||||||
if (!m) return null;
|
|
||||||
const id = Number(m[1]);
|
|
||||||
if (m[2] === "no" || m[2] === "back") return m[3] ? null : { id, action: m[2] };
|
|
||||||
const rights: GrantRights = m[2] === "f" ? "full" : "read";
|
|
||||||
if (!m[3]) return { id, action: "rights", rights };
|
|
||||||
return isGrantTerm(m[3]) ? { id, action: "grant", rights, term: m[3] } : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One message to the project's owner. Night quiet and the project's pause apply (outbox, deliverToUser). */
|
/** One message to the project's owner. Night quiet and the project's pause apply (outbox, deliverToUser). */
|
||||||
export async function announceAccessRequest(db: Db, r: AccessRequestView): Promise<void> {
|
export async function announceAccessRequest(db: Db, r: AccessRequestView): Promise<void> {
|
||||||
const canGrant = (await connectionsForRequest(db, r.ownerId, r).catch(() => ({ fit: [] }))).fit.length > 0;
|
const text = accessRequestText(r);
|
||||||
const text = accessRequestText(r, { canGrant });
|
|
||||||
const url = accessRequestUrl(r.id);
|
const url = accessRequestUrl(r.id);
|
||||||
await addMasterMessage(db, r.ownerId, { kind: "event", important: true, text, dedupeKey: `master:access-request:${r.id}`, url }).catch(() => null);
|
await addMasterMessage(db, r.ownerId, { kind: "event", important: true, text, dedupeKey: `master:access-request:${r.id}`, url }).catch(() => null);
|
||||||
const [u] = await db.select().from(users).where(eq(users.id, r.ownerId));
|
const [u] = await db.select().from(users).where(eq(users.id, r.ownerId));
|
||||||
if (!u) return;
|
if (!u) return;
|
||||||
const buttons = accessRequestKeyboard(r.id, { step: "rights", canGrant });
|
const base = (process.env.PEPPA_WEB_URL ?? "").replace(/\/+$/, "");
|
||||||
|
const buttons = [...(base.startsWith("https://") ? [[{ text: tr("Посмотреть и решить"), url: `${base}${url}` }]] : []), [{ text: tr("Отказать"), callback_data: `ar:${r.id}:no` }]];
|
||||||
await deliverToUser(db, u, {
|
await deliverToUser(db, u, {
|
||||||
event: "questions",
|
event: "questions",
|
||||||
projectId: r.projectId,
|
projectId: r.projectId,
|
||||||
@ -364,67 +313,35 @@ export async function connectionsForRequest(db: Db, userId: number, r: AccessReq
|
|||||||
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
|
const RANK: Record<GrantMode, number> = { off: 0, ask: 1, auto: 2 };
|
||||||
const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
|
const widest = (a: GrantMode, b: GrantMode): GrantMode => (RANK[b] > RANK[a] ? b : a);
|
||||||
|
|
||||||
/** PEP-261: what the owner gives — rights (default: what the agent asked for) and a term (default 1 day). */
|
/** Grant to the request's project (any of its agents): read at once, write at once only if asked. An existing grant only widens. */
|
||||||
export interface AccessGrantChoice {
|
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise<void> {
|
||||||
rights?: GrantRights;
|
const [prev] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((g) => g.agentId == null);
|
||||||
term?: GrantTerm;
|
|
||||||
}
|
|
||||||
type Given = { rights: GrantRights; term: GrantTerm };
|
|
||||||
const given = (r: AccessRequestView, c: AccessGrantChoice = {}): Given => ({ rights: c.rights === "full" || c.rights === "read" ? c.rights : r.mode === "write" ? "full" : "read", term: isGrantTerm(c.term) ? c.term : DEFAULT_GRANT_TERM });
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Grant to the request's project (any of its agents) on the chosen term. A grant that works now only
|
|
||||||
* widens its modes. PEP-315: a grant whose term is over or that was revoked for no use gives nothing
|
|
||||||
* to the new one — «Дать: чтение» after expired full rights is reading only.
|
|
||||||
*/
|
|
||||||
async function grantFor(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<void> {
|
|
||||||
const [row] = (await db.select().from(connectionGrants).where(and(eq(connectionGrants.connectionId, connectionId), eq(connectionGrants.projectId, r.projectId)))).filter((x) => x.agentId == null);
|
|
||||||
const prev = row && grantState(row, new Date()) === "active" ? row : undefined;
|
|
||||||
await grantConnection(db, userId, connectionId, {
|
await grantConnection(db, userId, connectionId, {
|
||||||
projectId: r.projectId,
|
projectId: r.projectId,
|
||||||
agentId: null,
|
agentId: null,
|
||||||
operations: prev?.operations ?? [],
|
operations: prev?.operations ?? [],
|
||||||
readMode: widest(prev?.readMode ?? "off", GRANT_RIGHTS[g.rights].readMode),
|
readMode: widest(prev?.readMode ?? "off", "auto"),
|
||||||
writeMode: widest(prev?.writeMode ?? "off", GRANT_RIGHTS[g.rights].writeMode),
|
writeMode: widest(prev?.writeMode ?? "off", r.mode === "write" ? "auto" : "off"),
|
||||||
term: g.term,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number, g: Given): Promise<AccessRequestView> {
|
async function closeGranted(db: Db, userId: number, r: AccessRequestView, connectionId: number): Promise<AccessRequestView> {
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
await db.update(accessRequests).set({ status: "granted", connectionId, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, r.id));
|
await db.update(accessRequests).set({ status: "granted", connectionId, decidedBy: userId, decidedAt: now, updatedAt: now }).where(eq(accessRequests.id, r.id));
|
||||||
await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_granted", payload: { requestId: r.id, connectionId, rights: g.rights, term: g.term } });
|
await logEvent(db, { projectId: r.projectId, taskId: r.taskId, type: "access_granted", payload: { requestId: r.id, connectionId } });
|
||||||
return { ...(await getAccessRequest(db, r.id))!, ...g };
|
return (await getAccessRequest(db, r.id))!;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** «Разрешить из уже подключённого». */
|
/** «Разрешить из уже подключённого». */
|
||||||
export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number, choice: AccessGrantChoice = {}): Promise<AccessRequestView> {
|
export async function grantAccessFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise<AccessRequestView> {
|
||||||
const r = await ownOpen(db, userId, id);
|
const r = await ownOpen(db, userId, id);
|
||||||
const g = given(r, choice);
|
await grantFor(db, userId, r, connectionId); // grantConnection checks that the connection is the user's and active
|
||||||
await grantFor(db, userId, r, connectionId, g); // grantConnection checks that the connection is the user's and active
|
return closeGranted(db, userId, r, connectionId);
|
||||||
return closeGranted(db, userId, r, connectionId, g);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const NO_CONNECTION_TEXT = tr("Подключения ещё нет — откройте запрос и подключите сервис");
|
|
||||||
|
|
||||||
/** PEP-261: the owner's open request and the connection a button would give (the first fitting one). */
|
|
||||||
export async function accessButtonTarget(db: Db, userId: number, id: number): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
|
||||||
const r = await ownOpen(db, userId, id);
|
|
||||||
const [connection] = (await connectionsForRequest(db, userId, r)).fit;
|
|
||||||
if (!connection) throw new PeppaError(NO_CONNECTION_TEXT);
|
|
||||||
return { request: r, connection };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** PEP-261 «Дать: чтение / полные права» + term — under the message (Telegram) or in «Агенты просят доступ». */
|
|
||||||
export async function grantAccessByButton(db: Db, userId: number, id: number, choice: AccessGrantChoice): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
|
||||||
const { connection } = await accessButtonTarget(db, userId, id);
|
|
||||||
return { request: await grantAccessFromExisting(db, userId, id, connection.id, choice), connection };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** «Подключить и разрешить»: the key is entered once — a new connection by the catalog card (or the requested address) and the grant. */
|
/** «Подключить и разрешить»: the key is entered once — a new connection by the catalog card (or the requested address) and the grant. */
|
||||||
export async function connectAndGrantAccess(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }, choice: AccessGrantChoice = {}): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
export async function connectAndGrantAccess(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }): Promise<{ request: AccessRequestView; connection: ConnectionView }> {
|
||||||
const r = await ownOpen(db, userId, id);
|
const r = await ownOpen(db, userId, id);
|
||||||
const g = given(r, choice);
|
|
||||||
const card = catalogService(r.catalogId);
|
const card = catalogService(r.catalogId);
|
||||||
const input: ConnectionInput = card
|
const input: ConnectionInput = card
|
||||||
? { name: i.name, secret: i.secret, catalogId: card.id, baseUrl: card.baseEditable ? i.baseUrl : undefined }
|
? { name: i.name, secret: i.secret, catalogId: card.id, baseUrl: card.baseEditable ? i.baseUrl : undefined }
|
||||||
@ -435,8 +352,8 @@ export async function connectAndGrantAccess(db: Db, userId: number, id: number,
|
|||||||
let name = base;
|
let name = base;
|
||||||
for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
|
for (let n = 2; taken.has(name); n++) name = `${base} ${n}`;
|
||||||
const connection = await createConnection(db, userId, { ...input, name });
|
const connection = await createConnection(db, userId, { ...input, name });
|
||||||
await grantFor(db, userId, r, connection.id, g);
|
await grantFor(db, userId, r, connection.id);
|
||||||
return { request: await closeGranted(db, userId, r, connection.id, g), connection };
|
return { request: await closeGranted(db, userId, r, connection.id), connection };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** «Отказать»: the reason (optional) reaches the agent. */
|
/** «Отказать»: the reason (optional) reaches the agent. */
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
// chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events,
|
// chat per user. Messages are a short-lived projection (PEPPA_CHAT_TTL_DAYS) of events,
|
||||||
// questions, releases and incidents, which stay in their own tables; people's messages are
|
// questions, releases and incidents, which stay in their own tables; people's messages are
|
||||||
// stored here too. Telegram groups linked to chats are the bot's business (apps/bot).
|
// stored here too. Telegram groups linked to chats are the bot's business (apps/bot).
|
||||||
import { platformDayTime } from "@peppa/shared/time";
|
|
||||||
import { asIs, hasAsIs, m as tr, PRODUCT_NAME } from "@peppa/shared/i18n";
|
import { asIs, hasAsIs, m as tr, PRODUCT_NAME } from "@peppa/shared/i18n";
|
||||||
import { createHmac, randomBytes } from "node:crypto";
|
import { createHmac, randomBytes } from "node:crypto";
|
||||||
import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
|
import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
|
||||||
@ -153,7 +152,7 @@ export async function threadTitle(db: Db, key: string): Promise<string | null> {
|
|||||||
if (kind === "release") {
|
if (kind === "release") {
|
||||||
const [r] = await db.select({ env: releases.env, createdAt: releases.createdAt }).from(releases).where(eq(releases.id, id));
|
const [r] = await db.select({ env: releases.env, createdAt: releases.createdAt }).from(releases).where(eq(releases.id, id));
|
||||||
// PEP-123: in the words of a product manager — which version and when, not the environment and the commit.
|
// PEP-123: in the words of a product manager — which version and when, not the environment and the commit.
|
||||||
return r ? `${ENV_RU[r.env] ?? r.env} · ${platformDayTime(r.createdAt)}` : null;
|
return r ? `${ENV_RU[r.env] ?? r.env} · ${r.createdAt.toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}` : null;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -8,7 +8,7 @@ import { CHECK_NAMES, formatTaskKey, loadEnv, type CheckName, type PeppaProjectF
|
|||||||
import { and, desc, eq } from "drizzle-orm";
|
import { and, desc, eq } from "drizzle-orm";
|
||||||
import type { GiteaClient, GiteaCommitStatus, GiteaPull } from "./gitea.ts";
|
import type { GiteaClient, GiteaCommitStatus, GiteaPull } from "./gitea.ts";
|
||||||
import { giteaForBot } from "./users.ts";
|
import { giteaForBot } from "./users.ts";
|
||||||
import { getSetting, setSetting } from "./settings.ts";
|
import { getSetting } from "./settings.ts";
|
||||||
import type { Project } from "./projects.ts";
|
import type { Project } from "./projects.ts";
|
||||||
import type { TaskRef } from "./tasks.ts";
|
import type { TaskRef } from "./tasks.ts";
|
||||||
|
|
||||||
@ -72,32 +72,25 @@ export function summarizeChecks(configured: string[], runs: RunLike[], sha: stri
|
|||||||
|
|
||||||
/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
|
/** Stores a CI result (one row per project/commit/check). `changed` — the state is new. */
|
||||||
export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> {
|
export async function upsertCheckRun(db: Db, project: Project, taskId: number | null, r: CheckReport): Promise<{ run: CheckRun; changed: boolean }> {
|
||||||
// PEP-313: one transaction (the write lock is taken first). The CI step's report (web) and the
|
const [prev] = await db
|
||||||
// watchdog's poll write the same check of the same commit at the same moment: read apart from the
|
.select()
|
||||||
// write, both saw no row, the second insert failed on the unique index, and the report with the
|
.from(checkRuns)
|
||||||
// log was lost with a 500 (27.11.2026). In turn each sees what the other stored.
|
.where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), eq(checkRuns.check, r.check)));
|
||||||
return db.transaction((tx) => {
|
const values = {
|
||||||
const prev = tx
|
taskId: taskId ?? prev?.taskId ?? null,
|
||||||
.select()
|
branch: r.branch ?? prev?.branch ?? null,
|
||||||
.from(checkRuns)
|
prNumber: r.prNumber ?? prev?.prNumber ?? null,
|
||||||
.where(and(eq(checkRuns.projectId, project.id), eq(checkRuns.sha, r.sha), eq(checkRuns.check, r.check)))
|
state: r.state,
|
||||||
.get();
|
runUrl: r.runUrl ?? prev?.runUrl ?? null,
|
||||||
const values = {
|
// A poll carries no log: keep the one the CI step sent.
|
||||||
taskId: taskId ?? prev?.taskId ?? null,
|
logTail: r.logTail ?? prev?.logTail ?? null,
|
||||||
branch: r.branch ?? prev?.branch ?? null,
|
durationSec: r.durationSec ?? prev?.durationSec ?? null,
|
||||||
prNumber: r.prNumber ?? prev?.prNumber ?? null,
|
source: r.source ?? "report",
|
||||||
state: r.state,
|
};
|
||||||
runUrl: r.runUrl ?? prev?.runUrl ?? null,
|
const [run] = prev
|
||||||
// A poll carries no log: keep the one the CI step sent.
|
? await db.update(checkRuns).set(values).where(eq(checkRuns.id, prev.id)).returning()
|
||||||
logTail: r.logTail ?? prev?.logTail ?? null,
|
: await db.insert(checkRuns).values({ projectId: project.id, sha: r.sha, check: r.check, ...values }).returning();
|
||||||
durationSec: r.durationSec ?? prev?.durationSec ?? null,
|
return { run: run!, changed: prev?.state !== r.state };
|
||||||
source: r.source ?? "report",
|
|
||||||
};
|
|
||||||
const run = prev
|
|
||||||
? tx.update(checkRuns).set(values).where(eq(checkRuns.id, prev.id)).returning().get()
|
|
||||||
: tx.insert(checkRuns).values({ projectId: project.id, sha: r.sha, check: r.check, ...values }).returning().get();
|
|
||||||
return { run: run!, changed: prev?.state !== r.state };
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PR number of a task's pr_url when it points at the project's repo. */
|
/** PR number of a task's pr_url when it points at the project's repo. */
|
||||||
@ -179,32 +172,11 @@ export async function standingChecksLanes(db: Db): Promise<string[] | null> {
|
|||||||
return [...(q.lanes ?? []).map((l) => `lane ${l}`), ...q.projects.map((id) => `project #${id}`)];
|
return [...(q.lanes ?? []).map((l) => `lane ${l}`), ...q.projects.map((id) => `project #${id}`)];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** For the task card and MCP (no Gitea calls): checks of the task's latest commit. */
|
||||||
* PEP-298: the checks a commit of the story needs — from `.peppa/project.json` of that commit, the
|
|
||||||
* same file the gate (`prGate`) reads. PEP-217's agent saw «4 из 4 пройдены» in `get_task` (the
|
|
||||||
* list of the main working copy) while the gate refused it with «3 из 4» (the list of its head).
|
|
||||||
*/
|
|
||||||
interface HeadChecks {
|
|
||||||
sha: string;
|
|
||||||
checks: string[];
|
|
||||||
}
|
|
||||||
const headChecksKey = (taskId: number) => `ci.checks:${taskId}`;
|
|
||||||
|
|
||||||
/** Remembers the list of `sha` for the story's card (one Gitea call per new head; a failure leaves the old one). */
|
|
||||||
export async function rememberHeadChecks(db: Db, ref: TaskRef, sha: string, client?: GiteaClient): Promise<void> {
|
|
||||||
if ((await getSetting<HeadChecks>(db, headChecksKey(ref.task.id)))?.sha === sha) return;
|
|
||||||
const text = await (client ?? giteaForBot()).fileText(ref.project.giteaOwner, ref.project.giteaRepo, ".peppa/project.json", sha).catch(() => undefined);
|
|
||||||
if (text === undefined) return;
|
|
||||||
await setSetting(db, headChecksKey(ref.task.id), { sha, checks: configuredChecks(text) } satisfies HeadChecks);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** For the task card and MCP (no Gitea calls): checks of the task's latest commit, by that commit's list when known. */
|
|
||||||
export async function taskCiSummary(db: Db, ref: TaskRef): Promise<CiSummary> {
|
export async function taskCiSummary(db: Db, ref: TaskRef): Promise<CiSummary> {
|
||||||
const runs = await db.select().from(checkRuns).where(eq(checkRuns.taskId, ref.task.id)).orderBy(desc(checkRuns.updatedAt));
|
const runs = await db.select().from(checkRuns).where(eq(checkRuns.taskId, ref.task.id)).orderBy(desc(checkRuns.updatedAt));
|
||||||
const sha = runs[0]?.sha ?? null;
|
const sha = runs[0]?.sha ?? null;
|
||||||
const head = sha ? await getSetting<HeadChecks>(db, headChecksKey(ref.task.id)) : null;
|
return summarizeChecks(configuredChecks(workspaceProjectJson(ref.project)), runs.filter((r) => r.sha === sha), sha);
|
||||||
const configured = head?.sha === sha ? head.checks : configuredChecks(workspaceProjectJson(ref.project));
|
|
||||||
return summarizeChecks(configured, runs.filter((r) => r.sha === sha), sha);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GateResult {
|
export interface GateResult {
|
||||||
|
|||||||
@ -77,10 +77,6 @@ export interface IntakeState {
|
|||||||
attempts: number;
|
attempts: number;
|
||||||
/** Why the roles were skipped or gave up, if they did. */
|
/** Why the roles were skipped or gave up, if they did. */
|
||||||
note?: string;
|
note?: string;
|
||||||
/** PEP-304: all the project's subscriptions are in a limit — the next try not before this (ms). */
|
|
||||||
retryAt?: number;
|
|
||||||
/** PEP-304: the reset (ms, 0 = unknown) the owner was already told about — one note per limit. */
|
|
||||||
limitNoted?: number;
|
|
||||||
}
|
}
|
||||||
const taskKey = (taskId: number) => `intake.task:${taskId}`;
|
const taskKey = (taskId: number) => `intake.task:${taskId}`;
|
||||||
|
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
|
// Service monitoring (PEP-20): web, bot and watchdog write heartbeats into `settings`; the
|
||||||
// watchdog and the bot check each other (and the web) and alert the platform admins in
|
// watchdog and the bot check each other (and the web) and alert the platform admins in
|
||||||
// Telegram through the outbox when a service goes quiet, without spamming.
|
// Telegram through the outbox when a service goes quiet, without spamming.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { m as tr } from "@peppa/shared/i18n";
|
import { m as tr } from "@peppa/shared/i18n";
|
||||||
import { execFileSync } from "node:child_process";
|
import { execFileSync } from "node:child_process";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
@ -302,8 +301,7 @@ export async function alertAdmins(db: Db, key: string, text: string, log: (m: st
|
|||||||
return queued;
|
return queued;
|
||||||
}
|
}
|
||||||
|
|
||||||
// PEP-304: the platform's zone, not the server's.
|
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||||
const hhmm = platformTime;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Checks every service but `self` and alerts admins about outages and recoveries.
|
* Checks every service but `self` and alerts admins about outages and recoveries.
|
||||||
|
|||||||
@ -4,7 +4,6 @@
|
|||||||
// the main database. The `peppa-observer` process runs `observeTick`; the web and MCP read and
|
// the main database. The `peppa-observer` process runs `observeTick`; the web and MCP read and
|
||||||
// change monitors through the functions here. Only the superadmin and the platform's agents get here.
|
// change monitors through the functions here. Only the superadmin and the platform's agents get here.
|
||||||
// glossary-ignore-file: the section is for the superadmin only.
|
// glossary-ignore-file: the section is for the superadmin only.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { DatabaseSync } from "node:sqlite";
|
import { DatabaseSync } from "node:sqlite";
|
||||||
import { mkdirSync } from "node:fs";
|
import { mkdirSync } from "node:fs";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
@ -262,9 +261,6 @@ export function observeDb(): DatabaseSync {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** Tests: forget opened files. */
|
/** Tests: forget opened files. */
|
||||||
/** Index of the migration whose SQL mentions `needle` (the `user_version` right before it); -1 — none. For tests that put a file back before one migration. */
|
|
||||||
export const observeMigrationIndex = (needle: string): number => MIGRATIONS.findIndex((m) => m.some((sql) => sql.includes(needle)));
|
|
||||||
|
|
||||||
export function closeObserveDb(): void {
|
export function closeObserveDb(): void {
|
||||||
for (const db of opened.values()) db.close();
|
for (const db of opened.values()) db.close();
|
||||||
opened.clear();
|
opened.clear();
|
||||||
@ -666,8 +662,14 @@ async function send(db: Db, key: string, text: string, log: (s: string) => void)
|
|||||||
await alertAdmins(db, `mon:${key}`, text, log);
|
await alertAdmins(db, `mon:${key}`, text, log);
|
||||||
}
|
}
|
||||||
|
|
||||||
// PEP-304: the platform's zone; a wrong PEPPA_TZ falls back inside platformTime.
|
const clock = (iso: string) => {
|
||||||
const clock = (iso: string) => platformTime(iso);
|
const d = new Date(iso);
|
||||||
|
try {
|
||||||
|
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
} catch {
|
||||||
|
return d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/** PEP-223: text of a reminder about an ongoing outage. */
|
/** PEP-223: text of a reminder about an ongoing outage. */
|
||||||
export function reminderText(m: Pick<Monitor, "name" | "state" | "lastCheckAt" | "lastDetail">, inc: Pick<MonitorIncident, "startedAt" | "reason">, now = new Date()): string {
|
export function reminderText(m: Pick<Monitor, "name" | "state" | "lastCheckAt" | "lastDetail">, inc: Pick<MonitorIncident, "startedAt" | "reason">, now = new Date()): string {
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// PEP-31: first-run checklist on the home page and the "agents won't start" project warning.
|
// PEP-31: first-run checklist on the home page and the "agents won't start" project warning.
|
||||||
import { platformDayTime } from "@peppa/shared/time";
|
|
||||||
import { m as tr } from "@peppa/shared/i18n";
|
import { m as tr } from "@peppa/shared/i18n";
|
||||||
import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
|
import { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
|
||||||
import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
|
import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
|
||||||
@ -176,7 +175,7 @@ export async function projectAgentWarning(db: Db, projectId: number, now = new D
|
|||||||
const why = subs.map((s) => {
|
const why = subs.map((s) => {
|
||||||
const v = { name: publicSubscriptionName(s), status: STATUS_RU[s.status] ?? s.status };
|
const v = { name: publicSubscriptionName(s), status: STATUS_RU[s.status] ?? s.status };
|
||||||
if (s.status !== "limited" || !s.limitedUntil) return tr("{name} — {status}", v);
|
if (s.status !== "limited" || !s.limitedUntil) return tr("{name} — {status}", v);
|
||||||
return tr("{name} — {status} до {until}", { ...v, until: platformDayTime(s.limitedUntil) });
|
return tr("{name} — {status} до {until}", { ...v, until: s.limitedUntil.toLocaleString("ru-RU", { hour: "2-digit", minute: "2-digit", day: "2-digit", month: "2-digit", timeZone: process.env.PEPPA_TZ || undefined }) });
|
||||||
});
|
});
|
||||||
return tr("у проекта нет рабочей подписки: {why}", { why: why.join(", ") });
|
return tr("у проекта нет рабочей подписки: {why}", { why: why.join(", ") });
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
// not the owner's business. The story is marked «задержка на нашей стороне» — one line in its
|
// not the owner's business. The story is marked «задержка на нашей стороне» — one line in its
|
||||||
// header and on its board card — the platform retries by itself, and the superadmin gets ONE
|
// header and on its board card — the platform retries by itself, and the superadmin gets ONE
|
||||||
// message with the details: again only when the state changed or the attempts ran out.
|
// message with the details: again only when the state changed or the attempts ran out.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import { projects, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
import { projects, settings, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||||
import { formatTaskKey } from "@peppa/shared";
|
import { formatTaskKey } from "@peppa/shared";
|
||||||
import { m as tr } from "@peppa/shared/i18n";
|
import { m as tr } from "@peppa/shared/i18n";
|
||||||
@ -293,7 +292,7 @@ export async function taskDelayLine(db: Db, taskId: number, o: { now?: Date; tim
|
|||||||
// PEP-268: a failure of the platform itself — the story keeps all its attempts and goes on by itself.
|
// PEP-268: a failure of the platform itself — the story keeps all its attempts and goes on by itself.
|
||||||
const platform = list.some((d) => d.state === "platform");
|
const platform = list.some((d) => d.state === "platform");
|
||||||
if (next == null) return platform ? tr("Сбой на нашей стороне, чиним — задача продолжится сама") : tr("Задерживается на нашей стороне, мы этим занимаемся");
|
if (next == null) return platform ? tr("Сбой на нашей стороне, чиним — задача продолжится сама") : tr("Задерживается на нашей стороне, мы этим занимаемся");
|
||||||
const tz = o.timeZone ?? platformZone();
|
const tz = o.timeZone ?? process.env.PEPPA_TZ ?? undefined;
|
||||||
const time = new Intl.DateTimeFormat("ru-RU", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(Math.max(next, now)));
|
const time = new Intl.DateTimeFormat("ru-RU", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(Math.max(next, now)));
|
||||||
const day = (t: number) => new Intl.DateTimeFormat("en-CA", { timeZone: tz }).format(new Date(t));
|
const day = (t: number) => new Intl.DateTimeFormat("en-CA", { timeZone: tz }).format(new Date(t));
|
||||||
if (platform) return day(next) !== day(now)
|
if (platform) return day(next) !== day(now)
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// PEP-107: development doesn't stop on a limit — what a pool looks like right now (which
|
// PEP-107: development doesn't stop on a limit — what a pool looks like right now (which
|
||||||
// subscription is at work, when a limit resets), an early warning when a project is down to
|
// subscription is at work, when a limit resets), an early warning when a project is down to
|
||||||
// its last subscription, and a superadmin lending a spare subscription to someone's pool.
|
// its last subscription, and a superadmin lending a spare subscription to someone's pool.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { events, projects, sessions, settings, subscriptionPoolMembers, tasks, type Db, keyPrefix } from "@peppa/db";
|
import { events, projects, sessions, settings, subscriptionPoolMembers, tasks, type Db, keyPrefix } from "@peppa/db";
|
||||||
import { and, desc, eq, inArray, like } from "drizzle-orm";
|
import { and, desc, eq, inArray, like } from "drizzle-orm";
|
||||||
import { m as tr, ruPlural } from "@peppa/shared/i18n";
|
import { m as tr, ruPlural } from "@peppa/shared/i18n";
|
||||||
@ -17,7 +16,7 @@ import type { User } from "./users.ts";
|
|||||||
|
|
||||||
export const warnThresholdPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85);
|
export const warnThresholdPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85);
|
||||||
|
|
||||||
const hhmm = platformTime;
|
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
|
||||||
// ── loans ────────────────────────────────────────────────────────────────────────
|
// ── loans ────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
|||||||
@ -414,22 +414,6 @@ export async function claudeTokenForProject(db: Db, project: Pick<Project, "id">
|
|||||||
return s ? subscriptionSecret(s) : null;
|
return s ? subscriptionSecret(s) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* PEP-304: why there is no Claude token for the project. `null` — the pool has no Claude
|
|
||||||
* subscription at all (or no pool): «нет подписки». Otherwise every Claude subscription is out
|
|
||||||
* for now: `until` — the earliest reset of a limited one (null when unknown or none is limited).
|
|
||||||
*/
|
|
||||||
export async function projectClaudeLimit(db: Db, project: Pick<Project, "id">, now = new Date()): Promise<{ until: Date | null; limited: boolean } | null> {
|
|
||||||
const [p] = await db.select({ poolId: projects.subscriptionPoolId }).from(projects).where(eq(projects.id, project.id));
|
|
||||||
if (p?.poolId == null) return null;
|
|
||||||
const claude = (await poolSubscriptions(db, p.poolId)).filter((x) => x.provider === "claude" && x.secretEnc);
|
|
||||||
if (!claude.length || claude.some((x) => isUsable(x, now))) return null;
|
|
||||||
const limited = claude.filter((x) => x.status === "limited");
|
|
||||||
if (!limited.length) return null;
|
|
||||||
const resets = limited.map((x) => x.limitedUntil?.getTime()).filter((t): t is number => t != null && t > now.getTime());
|
|
||||||
return { limited: true, until: resets.length ? new Date(Math.min(...resets)) : null };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Pool name of a project (for the project settings), or null. */
|
/** Pool name of a project (for the project settings), or null. */
|
||||||
export async function projectPool(db: Db, projectId: number): Promise<SubscriptionPool | null> {
|
export async function projectPool(db: Db, projectId: number): Promise<SubscriptionPool | null> {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
// Sources: Claude Code's statusLine command (cost, context window, 5h/7d limit windows) and
|
// Sources: Claude Code's statusLine command (cost, context window, 5h/7d limit windows) and
|
||||||
// the session transcript (token usage of every assistant message). Codex/OpenCode report
|
// the session transcript (token usage of every assistant message). Codex/OpenCode report
|
||||||
// neither — the UI says «нет данных» rather than inventing numbers.
|
// neither — the UI says «нет данных» rather than inventing numbers.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { m as tr } from "@peppa/shared/i18n";
|
import { m as tr } from "@peppa/shared/i18n";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens, keyPrefix } from "@peppa/db";
|
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens, keyPrefix } from "@peppa/db";
|
||||||
@ -375,7 +374,7 @@ export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] |
|
|||||||
return out.sort((a, b) => accountPeak(b) - accountPeak(a));
|
return out.sort((a, b) => accountPeak(b) - accountPeak(a));
|
||||||
}
|
}
|
||||||
|
|
||||||
const hhmm = platformTime;
|
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
|
||||||
/** «5 ч 42% (сброс 14:30) · 7 д 18%» — one line for the bot and MCP. */
|
/** «5 ч 42% (сброс 14:30) · 7 д 18%» — one line for the bot and MCP. */
|
||||||
export function describeAccount(a: AccountUsage): string {
|
export function describeAccount(a: AccountUsage): string {
|
||||||
|
|||||||
@ -498,11 +498,7 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
|
|||||||
const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type });
|
const r = await callConnection(db, { sessionId, connection, method, path, body, contentType: content_type });
|
||||||
if (!r.ok) {
|
if (!r.ok) {
|
||||||
// PEP-259: a term that ran out / a grant revoked for no use — the owner extends it with one click.
|
// PEP-259: a term that ran out / a grant revoked for no use — the owner extends it with one click.
|
||||||
// PEP-261: ask again through request_access — the owner answers with buttons (rights and term).
|
const again = r.reason === "expired" || r.reason === "idle_revoked" ? `. Access to «${String(connection)}» ended — ask the owner to extend it (one click in «Подключения»; tell them through ask_pm which service and what for), or continue without it.` : "";
|
||||||
const ended = r.reason === "expired" || r.reason === "idle_revoked";
|
|
||||||
const svc = ended && sessionId ? await refusedCallService(db, sessionId, connection, method, path).catch(() => null) : null;
|
|
||||||
const ask = svc?.catalogId ? `service: "${svc.catalogId}"` : svc?.baseUrl ? `host: "${svc.baseUrl}"` : `service: "${String(connection)}"`;
|
|
||||||
const again = ended ? `. Access to «${String(connection)}» ended — if you still need it, call request_access(${ask}, purpose: "<what for, in plain words>", mode: ${svc?.kind ?? "read"}); the owner gives it again with one button. Otherwise continue without it.` : "";
|
|
||||||
const refused = `Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}${again}`;
|
const refused = `Refused: ${stripAsIs(CONNECTION_REASON_TEXT[r.reason])} (${r.reason})${r.status ? `, HTTP ${r.status}` : ""}${again}`;
|
||||||
// PEP-250: no grant for this service → the refusal becomes an access request by itself.
|
// PEP-250: no grant for this service → the refusal becomes an access request by itself.
|
||||||
const asked = await autoRequest(r, String(connection), method, path).catch(() => null);
|
const asked = await autoRequest(r, String(connection), method, path).catch(() => null);
|
||||||
|
|||||||
@ -2,7 +2,7 @@
|
|||||||
// to a question: the live agent of the story gets a message; with nobody alive a story still in
|
// to a question: the live agent of the story gets a message; with nobody alive a story still in
|
||||||
// work goes back to work with that message. A project on pause wakes nobody (the decision is in
|
// work goes back to work with that message. A project on pause wakes nobody (the decision is in
|
||||||
// list_requests). Owner checks are in core (accessRequestForUser).
|
// list_requests). Owner checks are in core (accessRequestForUser).
|
||||||
import { connectAndGrantAccess, denyAccessRequest, grantAccessByButton, grantAccessFromExisting, isProjectPaused, listConnections, listSessions, logEvent, type AccessGrantChoice, type AccessRequestView, type ConnectionInput, type GrantTerm } from "@peppa/core";
|
import { connectAndGrantAccess, denyAccessRequest, grantAccessFromExisting, isProjectPaused, listConnections, listSessions, logEvent, type AccessRequestView, type ConnectionInput } from "@peppa/core";
|
||||||
import type { Db } from "@peppa/db";
|
import type { Db } from "@peppa/db";
|
||||||
import { moveTask } from "./flow.ts";
|
import { moveTask } from "./flow.ts";
|
||||||
import { resolveTaskById, sendToSession } from "./sessions.ts";
|
import { resolveTaskById, sendToSession } from "./sessions.ts";
|
||||||
@ -10,17 +10,13 @@ import { resolveTaskById, sendToSession } from "./sessions.ts";
|
|||||||
/** A story in these states gets a new agent with the decision; review/done/backlog are left alone. */
|
/** A story in these states gets a new agent with the decision; review/done/backlog are left alone. */
|
||||||
const WAKE = ["proposing", "in_progress", "blocked"];
|
const WAKE = ["proposing", "in_progress", "blocked"];
|
||||||
|
|
||||||
// i18n-ignore: text for the agent
|
|
||||||
const TERM_FOR_AGENT: Record<GrantTerm, string> = { "1h": "на 1 час", "1d": "на 1 день", "7d": "на 7 дней", forever: "до отзыва" };
|
|
||||||
|
|
||||||
export type AccessDelivery = "agent" | "restarted" | "none";
|
export type AccessDelivery = "agent" | "restarted" | "none";
|
||||||
|
|
||||||
/** Text for the agent (agents read English/Russian prompts — not translated). */
|
/** Text for the agent (agents read English/Russian prompts — not translated). */
|
||||||
export function accessDecisionText(r: AccessRequestView, slug?: string | null): string {
|
export function accessDecisionText(r: AccessRequestView, slug?: string | null): string {
|
||||||
if (r.status === "granted") {
|
if (r.status === "granted") {
|
||||||
const what = (r.rights ?? (r.mode === "write" ? "full" : "read")) === "full" ? "чтение и запись" : "чтение";
|
const what = r.mode === "write" ? "чтение и запись" : "чтение";
|
||||||
const term = r.term ? ` ${TERM_FOR_AGENT[r.term]}` : "";
|
return `Доступ выдан (запрос #${r.id}): владелец разрешил ${r.service} — ${what}. Посмотри list_connections и вызывай call_connection${slug ? `("${slug}", …)` : ""}; ключ подставит FORGE. Продолжай задачу.`;
|
||||||
return `Доступ выдан (запрос #${r.id}): владелец разрешил ${r.service} — ${what}${term}. Посмотри list_connections и вызывай call_connection${slug ? `("${slug}", …)` : ""}; ключ подставит FORGE. Продолжай задачу.`;
|
|
||||||
}
|
}
|
||||||
return `Владелец отказал в доступе к ${r.service} (запрос #${r.id}).${r.reason ? ` Причина: ${r.reason}` : " Причину не указал."} Продолжай без этого сервиса (мок, другой путь) и не проси этот доступ снова без новой причины.`;
|
return `Владелец отказал в доступе к ${r.service} (запрос #${r.id}).${r.reason ? ` Причина: ${r.reason}` : " Причину не указал."} Продолжай без этого сервиса (мок, другой путь) и не проси этот доступ снова без новой причины.`;
|
||||||
}
|
}
|
||||||
@ -48,15 +44,15 @@ export async function tellAgentAboutAccess(db: Db, r: AccessRequestView, slug?:
|
|||||||
return action;
|
return action;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function grantAccessRequestFromExisting(db: Db, userId: number, id: number, connectionId: number, choice: AccessGrantChoice = {}): Promise<AccessRequestView> {
|
export async function grantAccessRequestFromExisting(db: Db, userId: number, id: number, connectionId: number): Promise<AccessRequestView> {
|
||||||
const r = await grantAccessFromExisting(db, userId, id, connectionId, choice);
|
const r = await grantAccessFromExisting(db, userId, id, connectionId);
|
||||||
const slug = (await listConnections(db, userId)).find((c) => c.id === connectionId)?.slug ?? null;
|
const slug = (await listConnections(db, userId)).find((c) => c.id === connectionId)?.slug ?? null;
|
||||||
await tellAgentAboutAccess(db, r, slug);
|
await tellAgentAboutAccess(db, r, slug);
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function connectAndGrantAccessRequest(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }, choice: AccessGrantChoice = {}) {
|
export async function connectAndGrantAccessRequest(db: Db, userId: number, id: number, i: Omit<ConnectionInput, "catalogId"> & { secret: string }) {
|
||||||
const out = await connectAndGrantAccess(db, userId, id, i, choice);
|
const out = await connectAndGrantAccess(db, userId, id, i);
|
||||||
await tellAgentAboutAccess(db, out.request, out.connection.slug);
|
await tellAgentAboutAccess(db, out.request, out.connection.slug);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@ -66,10 +62,3 @@ export async function denyAccessRequestAndTell(db: Db, userId: number, id: numbe
|
|||||||
await tellAgentAboutAccess(db, r);
|
await tellAgentAboutAccess(db, r);
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** PEP-261: «Дать: чтение / полные права» + term by a button (Telegram, «Агенты просят доступ»). */
|
|
||||||
export async function grantAccessRequestByButton(db: Db, userId: number, id: number, choice: AccessGrantChoice): Promise<AccessRequestView> {
|
|
||||||
const { request, connection } = await grantAccessByButton(db, userId, id, choice);
|
|
||||||
await tellAgentAboutAccess(db, request, connection.slug);
|
|
||||||
return request;
|
|
||||||
}
|
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
// project's own subscription, like the intake roles) together with the project's context and
|
// project's own subscription, like the intake roles) together with the project's context and
|
||||||
// the last messages, and the answer is posted into the same discussion. Stories the person
|
// the last messages, and the answer is posted into the same discussion. Stories the person
|
||||||
// asked for are filed into the backlog, already formulated (the intake roles skip them).
|
// asked for are filed into the backlog, already formulated (the intake roles skip them).
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import {
|
import {
|
||||||
addChatMessage,
|
addChatMessage,
|
||||||
analystChatContext,
|
analystChatContext,
|
||||||
@ -148,14 +147,8 @@ async function answer(db: Db, project: Project, chatId: number, from: number, up
|
|||||||
// Whatever happens, this message is dealt with: a failure is said once, not retried forever.
|
// Whatever happens, this message is dealt with: a failure is said once, not retried forever.
|
||||||
await setAnalystCursor(db, chatId, upTo);
|
await setAnalystCursor(db, chatId, upTo);
|
||||||
if (!out.ok) {
|
if (!out.ok) {
|
||||||
const noSub = !out.limited && /нет подписки/.test(out.error);
|
const noSub = /нет подписки/.test(out.error);
|
||||||
// PEP-304: all subscriptions in a limit — say until when, not «не подключена».
|
await offer(await say(db, project, chatId, (noSub ? tr("Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.") : tr("Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже.")) + pick, false), { kind: "choice", text, answer: null });
|
||||||
const limited = out.limited
|
|
||||||
? out.limitedUntil
|
|
||||||
? tr("Аналитик отвечает на подписке проекта, а она сейчас в лимите до {time}. Напишите ещё раз после этого времени.", { time: platformTime(out.limitedUntil) })
|
|
||||||
: tr("Аналитик отвечает на подписке проекта, а она сейчас в лимите. Напишите ещё раз чуть позже.")
|
|
||||||
: null;
|
|
||||||
await offer(await say(db, project, chatId, (limited ?? (noSub ? tr("Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.") : tr("Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже."))) + pick, false), { kind: "choice", text, answer: null });
|
|
||||||
log(`analyst chat ${project.key}: ${out.error}`);
|
log(`analyst chat ${project.key}: ${out.error}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -22,7 +22,6 @@ import {
|
|||||||
taskPrNumber,
|
taskPrNumber,
|
||||||
foreignPrUrl,
|
foreignPrUrl,
|
||||||
upsertCheckRun,
|
upsertCheckRun,
|
||||||
rememberHeadChecks,
|
|
||||||
verifyHookSignature,
|
verifyHookSignature,
|
||||||
type CheckReport,
|
type CheckReport,
|
||||||
type GiteaClient,
|
type GiteaClient,
|
||||||
@ -128,8 +127,6 @@ export interface CheckOutcome {
|
|||||||
export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise<CheckOutcome> {
|
export async function recordCheck(db: Db, project: Project, r: CheckReport): Promise<CheckOutcome> {
|
||||||
const ref = await taskForCheck(db, project, r.branch, r.prNumber);
|
const ref = await taskForCheck(db, project, r.branch, r.prNumber);
|
||||||
const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r);
|
const { changed } = await upsertCheckRun(db, project, ref?.task.id ?? null, r);
|
||||||
// PEP-298: the card counts the checks by the same list as the gate — that of this commit.
|
|
||||||
if (ref) await rememberHeadChecks(db, ref, r.sha).catch(() => {});
|
|
||||||
if (changed && r.state === "success" && r.branch === "main") await offerPlatformRelease(db, project, r.sha);
|
if (changed && r.state === "success" && r.branch === "main") await offerPlatformRelease(db, project, r.sha);
|
||||||
if (!ref || !changed) return { task: ref?.key ?? null, action: "none" };
|
if (!ref || !changed) return { task: ref?.key ?? null, action: "none" };
|
||||||
if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" };
|
if (!["proposing", "in_progress", "review", "blocked"].includes(ref.task.status)) return { task: ref.key, action: "none" };
|
||||||
|
|||||||
@ -6,8 +6,7 @@ import { spawn } from "node:child_process";
|
|||||||
import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
|
import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { claudeTokenForProject, isProjectPaused, mayUseMachineLogin, NO_AUTOUPDATE_ENV, projectClaudeLimit, type Project } from "@peppa/core";
|
import { claudeTokenForProject, isProjectPaused, mayUseMachineLogin, NO_AUTOUPDATE_ENV, type Project } from "@peppa/core";
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { projects, type Db } from "@peppa/db";
|
import { projects, type Db } from "@peppa/db";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
|
|
||||||
@ -25,11 +24,7 @@ export interface ClaudePrintOptions {
|
|||||||
files?: Array<{ name: string; path: string }>;
|
files?: Array<{ name: string; path: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export type ClaudePrintResult = { ok: true; text: string } | { ok: false; error: string };
|
||||||
* `limited` (PEP-304): the project has Claude subscriptions, but all are in a usage limit —
|
|
||||||
* not «нет подписки»; `limitedUntil` — the earliest reset, when known.
|
|
||||||
*/
|
|
||||||
export type ClaudePrintResult = { ok: true; text: string } | { ok: false; error: string; limited?: boolean; limitedUntil?: Date | null };
|
|
||||||
|
|
||||||
/** Text answer from the CLI's JSON envelope (or the raw output when it isn't one); null on an error envelope. */
|
/** Text answer from the CLI's JSON envelope (or the raw output when it isn't one); null on an error envelope. */
|
||||||
export function envelopeText(stdout: string): string | null {
|
export function envelopeText(stdout: string): string | null {
|
||||||
@ -49,17 +44,7 @@ export async function claudePrint(db: Db, project: Pick<Project, "id">, o: Claud
|
|||||||
// login — fine for the platform's and allowlisted owners' projects, never for a self-registered one.
|
// login — fine for the platform's and allowlisted owners' projects, never for a self-registered one.
|
||||||
if (!token) {
|
if (!token) {
|
||||||
const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, project.id));
|
const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, project.id));
|
||||||
if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) {
|
if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) return { ok: false, error: m("{who}: у проекта нет подписки Claude", { who: o.who }) };
|
||||||
const limit = await projectClaudeLimit(db, project);
|
|
||||||
if (limit)
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
limited: true,
|
|
||||||
limitedUntil: limit.until,
|
|
||||||
error: limit.until ? m("{who}: подписки проекта в лимите до {time}", { who: o.who, time: platformTime(limit.until) }) : m("{who}: подписки проекта в лимите", { who: o.who }),
|
|
||||||
};
|
|
||||||
return { ok: false, error: m("{who}: у проекта нет подписки Claude", { who: o.who }) };
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
|
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
|
||||||
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
|
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
|
||||||
|
|||||||
@ -12,9 +12,7 @@ import { existsSync } from "node:fs";
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import {
|
import {
|
||||||
askPmProject,
|
askPmProject,
|
||||||
clearCapacityWait,
|
|
||||||
clearPlatformDelay,
|
clearPlatformDelay,
|
||||||
dropQueuedTask,
|
|
||||||
deleteSetting,
|
deleteSetting,
|
||||||
getSetting,
|
getSetting,
|
||||||
giteaForBot,
|
giteaForBot,
|
||||||
@ -28,7 +26,6 @@ import {
|
|||||||
queuedItems,
|
queuedItems,
|
||||||
setSetting,
|
setSetting,
|
||||||
taskPrNumber,
|
taskPrNumber,
|
||||||
type GateResult,
|
|
||||||
type GiteaClient,
|
type GiteaClient,
|
||||||
type GiteaPull,
|
type GiteaPull,
|
||||||
type Question,
|
type Question,
|
||||||
@ -39,7 +36,6 @@ import { and, eq, min } from "drizzle-orm";
|
|||||||
import { asIs, m } from "@peppa/shared/i18n";
|
import { asIs, m } from "@peppa/shared/i18n";
|
||||||
import { archiveTask, requestRebase } from "./flow.ts";
|
import { archiveTask, requestRebase } from "./flow.ts";
|
||||||
import { credentialHelper, run } from "./git.ts";
|
import { credentialHelper, run } from "./git.ts";
|
||||||
import { platformToReview } from "./review-wanted.ts";
|
|
||||||
import { onAnswer, resolveTaskById } from "./sessions.ts";
|
import { onAnswer, resolveTaskById } from "./sessions.ts";
|
||||||
|
|
||||||
type Log = (m: string) => void;
|
type Log = (m: string) => void;
|
||||||
@ -50,11 +46,6 @@ export const CONFLICT_MAX_ATTEMPTS = 2;
|
|||||||
export const CONFLICT_WAIT_MIN = 90;
|
export const CONFLICT_WAIT_MIN = 90;
|
||||||
/** A new head is judged only after Gitea had this long (min) to re-check it. */
|
/** A new head is judged only after Gitea had this long (min) to re-check it. */
|
||||||
export const CONFLICT_SETTLE_MIN = 2;
|
export const CONFLICT_SETTLE_MIN = 2;
|
||||||
/** PEP-298: the first request about a conflict waits this long (min) for a second sight; `PEPPA_CONFLICT_SETTLE_MIN` (tests: 0). */
|
|
||||||
export const conflictSettleMs = () => {
|
|
||||||
const v = Number(process.env.PEPPA_CONFLICT_SETTLE_MIN ?? CONFLICT_SETTLE_MIN);
|
|
||||||
return (Number.isFinite(v) && v >= 0 ? v : CONFLICT_SETTLE_MIN) * 60_000;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface ConflictStep {
|
export interface ConflictStep {
|
||||||
/** Head of the result and of the main branch when the agent was last asked. */
|
/** Head of the result and of the main branch when the agent was last asked. */
|
||||||
@ -67,11 +58,8 @@ export interface ConflictStep {
|
|||||||
seen?: { sha: string; at: number };
|
seen?: { sha: string; at: number };
|
||||||
/** A person decides: why and which files. */
|
/** A person decides: why and which files. */
|
||||||
escalated?: { at: number; why: string; files: string[] };
|
escalated?: { at: number; why: string; files: string[] };
|
||||||
/** PEP-298: the story's status when the agent was first asked (a story taken from review in vain goes back). */
|
|
||||||
from?: string;
|
|
||||||
}
|
}
|
||||||
/** `settling` (PEP-298): the conflict was first seen less than CONFLICT_SETTLE_MIN ago — Gitea may still be re-checking. */
|
export type ConflictOutcome = "requested" | "waiting" | "held" | "escalated";
|
||||||
export type ConflictOutcome = "requested" | "waiting" | "held" | "escalated" | "settling";
|
|
||||||
|
|
||||||
const PREFIX = "conflict.step:";
|
const PREFIX = "conflict.step:";
|
||||||
const stepKey = (taskId: number) => `${PREFIX}${taskId}`;
|
const stepKey = (taskId: number) => `${PREFIX}${taskId}`;
|
||||||
@ -90,24 +78,9 @@ const HELD = "conflict.held:";
|
|||||||
const heldKey = (taskId: number) => `${HELD}${taskId}`;
|
const heldKey = (taskId: number) => `${HELD}${taskId}`;
|
||||||
export const getConflictHeld = (db: Db, taskId: number) => getSetting<ConflictHeld>(db, heldKey(taskId));
|
export const getConflictHeld = (db: Db, taskId: number) => getSetting<ConflictHeld>(db, heldKey(taskId));
|
||||||
|
|
||||||
/**
|
|
||||||
* PEP-298: the first sight of a conflict on this head. Gitea re-checks mergeability in the background
|
|
||||||
* after a push and after FORGE updates the branch, and answers «conflict» meanwhile: 15 of 40 requests
|
|
||||||
* on 25.11 were false. The first request goes only when the same head still conflicts
|
|
||||||
* CONFLICT_SETTLE_MIN later; the minute tick looks again, so a periodic caller needs no second visit.
|
|
||||||
*/
|
|
||||||
export interface ConflictSeen {
|
|
||||||
sha: string;
|
|
||||||
at: number;
|
|
||||||
}
|
|
||||||
const SEEN = "conflict.seen:";
|
|
||||||
const seenKey = (taskId: number) => `${SEEN}${taskId}`;
|
|
||||||
export const getConflictSeen = (db: Db, taskId: number) => getSetting<ConflictSeen>(db, seenKey(taskId));
|
|
||||||
|
|
||||||
/** The conflict is gone (or the story left work): the step and its delay card go. */
|
/** The conflict is gone (or the story left work): the step and its delay card go. */
|
||||||
export async function clearConflictStep(db: Db, ref: Pick<TaskRef, "project" | "task">, log?: Log): Promise<void> {
|
export async function clearConflictStep(db: Db, ref: Pick<TaskRef, "project" | "task">, log?: Log): Promise<void> {
|
||||||
await deleteSetting(db, heldKey(ref.task.id));
|
await deleteSetting(db, heldKey(ref.task.id));
|
||||||
await deleteSetting(db, seenKey(ref.task.id));
|
|
||||||
const step = await getConflictStep(db, ref.task.id);
|
const step = await getConflictStep(db, ref.task.id);
|
||||||
if (!step) return;
|
if (!step) return;
|
||||||
await deleteSetting(db, stepKey(ref.task.id));
|
await deleteSetting(db, stepKey(ref.task.id));
|
||||||
@ -162,9 +135,7 @@ const working = async (db: Db, taskId: number) => (await listSessions(db, { acti
|
|||||||
async function ask(db: Db, ref: TaskRef, pull: GiteaPull, attempts: number, now: number, log: Log, force?: boolean): Promise<boolean> {
|
async function ask(db: Db, ref: TaskRef, pull: GiteaPull, attempts: number, now: number, log: Log, force?: boolean): Promise<boolean> {
|
||||||
if (!(await requestRebase(db, ref, { force }))) return false;
|
if (!(await requestRebase(db, ref, { force }))) return false;
|
||||||
await deleteSetting(db, heldKey(ref.task.id));
|
await deleteSetting(db, heldKey(ref.task.id));
|
||||||
await deleteSetting(db, seenKey(ref.task.id));
|
await setSetting(db, stepKey(ref.task.id), { headSha: pull.head.sha, baseSha: pull.base.sha ?? null, at: now, attempts } satisfies ConflictStep);
|
||||||
const from = attempts === 1 ? ref.task.status : (await getConflictStep(db, ref.task.id))?.from;
|
|
||||||
await setSetting(db, stepKey(ref.task.id), { headSha: pull.head.sha, baseSha: pull.base.sha ?? null, at: now, attempts, ...(from ? { from } : {}) } satisfies ConflictStep);
|
|
||||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_rebase_requested", payload: { attempt: attempts, head: pull.head.sha } });
|
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_rebase_requested", payload: { attempt: attempts, head: pull.head.sha } });
|
||||||
log(`${ref.key}: conflict with the main branch — rebase requested (${attempts}/${CONFLICT_MAX_ATTEMPTS})`);
|
log(`${ref.key}: conflict with the main branch — rebase requested (${attempts}/${CONFLICT_MAX_ATTEMPTS})`);
|
||||||
return true;
|
return true;
|
||||||
@ -198,16 +169,6 @@ export async function conflictStep(db: Db, ref: TaskRef, pull: GiteaPull, o: { n
|
|||||||
const now = (o.now ?? new Date()).getTime();
|
const now = (o.now ?? new Date()).getTime();
|
||||||
const step = await getConflictStep(db, ref.task.id);
|
const step = await getConflictStep(db, ref.task.id);
|
||||||
if (!step) {
|
if (!step) {
|
||||||
// PEP-298: two sights of the same head CONFLICT_SETTLE_MIN apart — Gitea's answer right after a push is not a conflict yet.
|
|
||||||
const settle = conflictSettleMs();
|
|
||||||
const seen = settle ? await getConflictSeen(db, ref.task.id) : null;
|
|
||||||
if (settle && seen?.sha !== pull.head.sha) {
|
|
||||||
await setSetting(db, seenKey(ref.task.id), { sha: pull.head.sha, at: now } satisfies ConflictSeen);
|
|
||||||
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, type: "conflict_seen", payload: { head: pull.head.sha } });
|
|
||||||
log(`${ref.key}: Gitea says conflict — looking again in ${settle / 60_000} min`);
|
|
||||||
return "settling";
|
|
||||||
}
|
|
||||||
if (seen && now - seen.at < settle) return "settling";
|
|
||||||
if (await ask(db, ref, pull, 1, now, log, o.force)) return "requested";
|
if (await ask(db, ref, pull, 1, now, log, o.force)) return "requested";
|
||||||
// PEP-301: the request was held (the checks queue, running checks) — not done, the tick repeats it.
|
// PEP-301: the request was held (the checks queue, running checks) — not done, the tick repeats it.
|
||||||
const held = await getConflictHeld(db, ref.task.id);
|
const held = await getConflictHeld(db, ref.task.id);
|
||||||
@ -253,7 +214,7 @@ export async function conflictStep(db: Db, ref: TaskRef, pull: GiteaPull, o: { n
|
|||||||
export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaClient; log?: Log } = {}): Promise<void> {
|
export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaClient; log?: Log } = {}): Promise<void> {
|
||||||
const log = o.log ?? (() => {});
|
const log = o.log ?? (() => {});
|
||||||
const ids = new Set<number>();
|
const ids = new Set<number>();
|
||||||
for (const prefix of [PREFIX, HELD, SEEN]) {
|
for (const prefix of [PREFIX, HELD]) {
|
||||||
for (const row of await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, prefix))) ids.add(Number(row.key.slice(prefix.length)));
|
for (const row of await db.select({ key: settings.key }).from(settings).where(keyPrefix(settings.key, prefix))) ids.add(Number(row.key.slice(prefix.length)));
|
||||||
}
|
}
|
||||||
for (const taskId of ids) {
|
for (const taskId of ids) {
|
||||||
@ -262,7 +223,6 @@ export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaCli
|
|||||||
if (!ref) {
|
if (!ref) {
|
||||||
await deleteSetting(db, stepKey(taskId));
|
await deleteSetting(db, stepKey(taskId));
|
||||||
await deleteSetting(db, heldKey(taskId));
|
await deleteSetting(db, heldKey(taskId));
|
||||||
await deleteSetting(db, seenKey(taskId));
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (ref.task.archivedAt || ["done", "backlog"].includes(ref.task.status)) {
|
if (ref.task.archivedAt || ["done", "backlog"].includes(ref.task.status)) {
|
||||||
@ -274,7 +234,6 @@ export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaCli
|
|||||||
if (!gate) continue; // Gitea unreachable: the next minute
|
if (!gate) continue; // Gitea unreachable: the next minute
|
||||||
const pull = gate.pull;
|
const pull = gate.pull;
|
||||||
if (!pull || pull.merged || pull.state !== "open" || pull.mergeable !== false) {
|
if (!pull || pull.merged || pull.state !== "open" || pull.mergeable !== false) {
|
||||||
if (pull && !pull.merged && pull.state === "open" && (await backToReview(db, ref, gate, log)) === "later") continue;
|
|
||||||
await clearConflictStep(db, ref, log);
|
await clearConflictStep(db, ref, log);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@ -285,28 +244,6 @@ export async function conflictStepTick(db: Db, o: { now?: Date; gitea?: GiteaCli
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* PEP-298: the conflict is gone, but the story was taken from review for it and its agent never
|
|
||||||
* started (it waits for a place among the agents or in the runner queue), and nothing was pushed —
|
|
||||||
* the request was in vain: the story goes back to review by itself. `later` — its checks still run.
|
|
||||||
*/
|
|
||||||
async function backToReview(db: Db, ref: TaskRef, gate: GateResult, log: Log): Promise<"back" | "later" | "no"> {
|
|
||||||
const step = await getConflictStep(db, ref.task.id);
|
|
||||||
const pull = gate.pull;
|
|
||||||
if (!step || step.escalated || step.from !== "review" || ref.task.status !== "in_progress" || !pull) return "no";
|
|
||||||
if (pull.head.sha !== step.headSha) return "no"; // the agent pushed: its own hand-off
|
|
||||||
if ((await listSessions(db, { active: true, taskId: ref.task.id })).length) return "no";
|
|
||||||
if (gate.summary?.state === "pending" && !gate.lost?.length) return "later";
|
|
||||||
if (!(gate.ok || gate.behind)) return "no";
|
|
||||||
await dropQueuedTask(db, ref.task.id);
|
|
||||||
await clearCapacityWait(db, ref.task.id);
|
|
||||||
await clearConflictStep(db, ref, log);
|
|
||||||
const withPr = ref.task.prUrl ? ref : { ...ref, task: { ...ref.task, prUrl: pull.html_url } };
|
|
||||||
await platformToReview(db, withPr, pull.head.sha, "conflict_false_back_to_review");
|
|
||||||
log(`${ref.key}: the conflict went by itself before the agent started — back to review`);
|
|
||||||
return "back";
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── PEP-301: conflicts nobody works on ────────────────────────────────────────────────────────
|
// ── PEP-301: conflicts nobody works on ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/** The hourly sweep. */
|
/** The hourly sweep. */
|
||||||
|
|||||||
@ -7,7 +7,6 @@
|
|||||||
// dispatcher skips stories the analyst has not finished with (`readyBacklog`); a PM who drags the
|
// dispatcher skips stories the analyst has not finished with (`readyBacklog`); a PM who drags the
|
||||||
// card to work overrides it.
|
// card to work overrides it.
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import {
|
import {
|
||||||
addDependency,
|
addDependency,
|
||||||
addIntakeNote,
|
addIntakeNote,
|
||||||
@ -56,19 +55,7 @@ const ask = (db: Db, project: Project, prompt: string, who: string) =>
|
|||||||
});
|
});
|
||||||
|
|
||||||
/** Plain words for the owner: why the analyst could not read the story (no technical text). */
|
/** Plain words for the owner: why the analyst could not read the story (no technical text). */
|
||||||
const failureReason = (error: string) => (/нет подписки/i.test(error) ? m("у проекта не подключена подписка") : /формат/i.test(error) ? m("ответ разбора пришёл не по форме") : m("сервис разбора сейчас не отвечает"));
|
const failureReason = (error: string) => (/нет подписки|подписк/i.test(error) ? m("у проекта не подключена подписка") : /формат/i.test(error) ? m("ответ разбора пришёл не по форме") : m("сервис разбора сейчас не отвечает"));
|
||||||
|
|
||||||
/** PEP-304: the subscriptions are in a limit — not a failure of the story; wait for the reset. */
|
|
||||||
class LimitedError extends Error {
|
|
||||||
until: Date | null;
|
|
||||||
constructor(message: string, until: Date | null) {
|
|
||||||
super(message);
|
|
||||||
this.until = until;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
/** Unknown reset: look again in half an hour. After a known one — a minute of margin. */
|
|
||||||
const LIMIT_PROBE_MS = 30 * 60_000;
|
|
||||||
const LIMIT_MARGIN_MS = 60_000;
|
|
||||||
|
|
||||||
/** The one step (PEP-198): a single model call; returns the new state. Throws on a model failure (the caller counts attempts). */
|
/** The one step (PEP-198): a single model call; returns the new state. Throws on a model failure (the caller counts attempts). */
|
||||||
async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) => void): Promise<IntakeState> {
|
async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) => void): Promise<IntakeState> {
|
||||||
@ -76,7 +63,7 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) =
|
|||||||
const context = await intakeContext(db, project, task);
|
const context = await intakeContext(db, project, task);
|
||||||
const legacy = { product: state.product, analyst: state.stage === "finalize" ? state.analyst : undefined, answer: state.stage === "finalize" ? state.answer : undefined };
|
const legacy = { product: state.product, analyst: state.stage === "finalize" ? state.analyst : undefined, answer: state.stage === "finalize" ? state.answer : undefined };
|
||||||
const out = await ask(db, project, intakePrompt(context, { title: task.title, description: state.original.description }, legacy), m("аналитик"));
|
const out = await ask(db, project, intakePrompt(context, { title: task.title, description: state.original.description }, legacy), m("аналитик"));
|
||||||
if (!out.ok) throw out.limited ? new LimitedError(out.error, out.limitedUntil ?? null) : new Error(out.error);
|
if (!out.ok) throw new Error(out.error);
|
||||||
const note = parseIntakeNote(out.text, task.title);
|
const note = parseIntakeNote(out.text, task.title);
|
||||||
if (!note) throw new Error(m("аналитик ответил не по формату"));
|
if (!note) throw new Error(m("аналитик ответил не по формату"));
|
||||||
// The parts of the request: each checked for a repeat first (3.5), then filed after this story.
|
// The parts of the request: each checked for a repeat first (3.5), then filed after this story.
|
||||||
@ -137,29 +124,11 @@ async function advance(db: Db, taskId: number, now: Date, log: (m: string) => vo
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (state.retryAt && state.retryAt > now.getTime()) return;
|
|
||||||
try {
|
try {
|
||||||
state = await step(db, ref, state, log);
|
state = await step(db, ref, state, log);
|
||||||
await setIntakeState(db, taskId, state);
|
await setIntakeState(db, taskId, state);
|
||||||
log(`${ref.key}: intake → ${state.stage}`);
|
log(`${ref.key}: intake → ${state.stage}`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (e instanceof LimitedError) {
|
|
||||||
// PEP-304: a limit is no attempt — the story waits for the reset, the owner hears it once per limit.
|
|
||||||
const until = e.until?.getTime() ?? 0;
|
|
||||||
const retryAt = until ? until + LIMIT_MARGIN_MS : now.getTime() + LIMIT_PROBE_MS;
|
|
||||||
if (state.limitNoted !== until)
|
|
||||||
await addIntakeNote(
|
|
||||||
db,
|
|
||||||
ref.task,
|
|
||||||
"analyst",
|
|
||||||
until
|
|
||||||
? m("Аналитик разберёт задачу позже: подписки проекта в лимите до {time}. После этого разбор продолжится сам.", { time: platformTime(until) })
|
|
||||||
: m("Аналитик разберёт задачу позже: подписки проекта в лимите. Когда лимит сбросится, разбор продолжится сам."),
|
|
||||||
);
|
|
||||||
await setIntakeState(db, taskId, { ...state, retryAt, limitNoted: until });
|
|
||||||
log(`${ref.key}: intake waits for the limit (${e.message})`);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const attempts = state.attempts + 1;
|
const attempts = state.attempts + 1;
|
||||||
// The roles must never hold a story for ever: after a couple of failures it goes on as written.
|
// The roles must never hold a story for ever: after a couple of failures it goes on as written.
|
||||||
if (attempts >= MAX_ATTEMPTS) {
|
if (attempts >= MAX_ATTEMPTS) {
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
// PEP-150: a usage limit with no subscription to switch to. Kept light — the hook process
|
// PEP-150: a usage limit with no subscription to switch to. Kept light — the hook process
|
||||||
// imports it (no runner flow behind it).
|
// imports it (no runner flow behind it).
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { asIs, m } from "@peppa/shared/i18n";
|
import { asIs, m } from "@peppa/shared/i18n";
|
||||||
import { answerQuestion, askPm, clearPlatformDelay, getSession, getSetting, listSessions, sessionDelay, setSetting, type SessionView, type TaskRef } from "@peppa/core";
|
import { answerQuestion, askPm, clearPlatformDelay, getSession, getSetting, listSessions, sessionDelay, setSetting, type SessionView, type TaskRef } from "@peppa/core";
|
||||||
import { projects, tasks, type Db } from "@peppa/db";
|
import { projects, tasks, type Db } from "@peppa/db";
|
||||||
@ -51,7 +50,7 @@ export async function limitDelay(db: Db, s: SessionView, text: string, o: { now?
|
|||||||
const [row] = await db.select({ task: tasks, project: projects }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, s.taskId));
|
const [row] = await db.select({ task: tasks, project: projects }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, s.taskId));
|
||||||
if (!row) return;
|
if (!row) return;
|
||||||
const ref: TaskRef = { ...row, key: formatTaskKey(row.project.key, row.task.number) };
|
const ref: TaskRef = { ...row, key: formatTaskKey(row.project.key, row.task.number) };
|
||||||
const time = platformTime(resumeAt);
|
const time = new Date(resumeAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
const q = await askPm(db, ref, {
|
const q = await askPm(db, ref, {
|
||||||
kind: "question",
|
kind: "question",
|
||||||
options: [LIMIT_ADD, LIMIT_REQUEST, LIMIT_WAIT],
|
options: [LIMIT_ADD, LIMIT_REQUEST, LIMIT_WAIT],
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
// Usage limits (PEP-56): when does the agent's limit reset, and what to tell the PM.
|
// Usage limits (PEP-56): when does the agent's limit reset, and what to tell the PM.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core";
|
import { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core";
|
||||||
import type { Db } from "@peppa/db";
|
import type { Db } from "@peppa/db";
|
||||||
@ -122,7 +121,7 @@ export function passedReset(text: string, now: Date): Date | null {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PEP-300: people read the time in the platform's zone (PEPPA_TZ), not in the server's (UTC in the containers).
|
// PEP-300: people read the time in the platform's zone (PEPPA_TZ), not in the server's (UTC in the containers).
|
||||||
const hhmm = platformTime;
|
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, local
|
const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, local
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// PEP-174: «Поставить на паузу» / «Продолжить» for a project. The pause itself is a setting
|
// PEP-174: «Поставить на паузу» / «Продолжить» for a project. The pause itself is a setting
|
||||||
// (core/project-pause.ts) every place that starts agents, calls the AI roles or notifies people
|
// (core/project-pause.ts) every place that starts agents, calls the AI roles or notifies people
|
||||||
// checks; here the live agents are stopped and, on «Продолжить», resumed.
|
// checks; here the live agents are stopped and, on «Продолжить», resumed.
|
||||||
import { platformDayTime } from "@peppa/shared/time";
|
|
||||||
import {
|
import {
|
||||||
activateRunnerTask,
|
activateRunnerTask,
|
||||||
clearProjectPause,
|
clearProjectPause,
|
||||||
@ -18,7 +17,7 @@ import { resumeSession, stopSession } from "./sessions.ts";
|
|||||||
const WORKING = ["proposing", "in_progress"];
|
const WORKING = ["proposing", "in_progress"];
|
||||||
|
|
||||||
const stamp = (ms: number) =>
|
const stamp = (ms: number) =>
|
||||||
platformDayTime(ms);
|
new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Puts the project on pause: from this moment nothing starts and nobody is notified; the live
|
* Puts the project on pause: from this moment nothing starts and nobody is notified; the live
|
||||||
|
|||||||
@ -3,7 +3,6 @@
|
|||||||
// `workTo`, `workDays`, platform time zone): one message of the analyst in the project's
|
// `workTo`, `workDays`, platform time zone): one message of the analyst in the project's
|
||||||
// discussion — it reaches the project's people in Telegram and the browser like any message of
|
// discussion — it reaches the project's people in Telegram and the browser like any message of
|
||||||
// the analyst. An empty digest is not sent.
|
// the analyst. An empty digest is not sent.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import { ensureProjectChat, heldReadyStories, markReadyDigest, pausedProjectIds, readyDigestDay, readyDigestText, listProjects } from "@peppa/core";
|
import { ensureProjectChat, heldReadyStories, markReadyDigest, pausedProjectIds, readyDigestDay, readyDigestText, listProjects } from "@peppa/core";
|
||||||
import type { Db } from "@peppa/db";
|
import type { Db } from "@peppa/db";
|
||||||
import { sayInDiscussion } from "./analyst-chat.ts";
|
import { sayInDiscussion } from "./analyst-chat.ts";
|
||||||
@ -11,7 +10,7 @@ import { getWatchdogSettings } from "./recovery.ts";
|
|||||||
|
|
||||||
/** The day (YYYY-MM-DD), hour and weekday (1 = Mon) in the platform's time zone. */
|
/** The day (YYYY-MM-DD), hour and weekday (1 = Mon) in the platform's time zone. */
|
||||||
function localNow(now: Date): { day: string; hour: number; weekday: number } {
|
function localNow(now: Date): { day: string; hour: number; weekday: number } {
|
||||||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: platformZone(), year: "numeric", month: "2-digit", day: "2-digit", weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, year: "numeric", month: "2-digit", day: "2-digit", weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
||||||
const get = (t: string) => parts.find((x) => x.type === t)?.value ?? "";
|
const get = (t: string) => parts.find((x) => x.type === t)?.value ?? "";
|
||||||
return { day: `${get("year")}-${get("month")}-${get("day")}`, hour: Number(get("hour")), weekday: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(get("weekday")) + 1 };
|
return { day: `${get("year")}-${get("month")}-${get("day")}`, hour: Number(get("hour")), weekday: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(get("weekday")) + 1 };
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// PEP-28: watchdog 2.0 — the watchdog fixes what it can by itself (restarts a crashed or
|
// PEP-28: watchdog 2.0 — the watchdog fixes what it can by itself (restarts a crashed or
|
||||||
// stalled runner within a limit), reminds about unanswered questions and escalates them,
|
// stalled runner within a limit), reminds about unanswered questions and escalates them,
|
||||||
// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env.
|
// and stops runners that wait for nobody. Thresholds: `platform.watchdog` over env.
|
||||||
import { platformZone } from "@peppa/shared/time";
|
|
||||||
import { asIs, m } from "@peppa/shared/i18n";
|
import { asIs, m } from "@peppa/shared/i18n";
|
||||||
import { and, desc, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
|
import { and, desc, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
|
||||||
import {
|
import {
|
||||||
@ -500,7 +499,7 @@ const KIND_RU: Record<string, string> = { question: m("Вопрос"), permissio
|
|||||||
*/
|
*/
|
||||||
/** PEP-173: is it working time in the platform's time zone (PEPPA_TZ, else this machine's)? */
|
/** PEP-173: is it working time in the platform's time zone (PEPPA_TZ, else this machine's)? */
|
||||||
export function inWorkingTime(now: Date, cfg: Pick<WatchdogSettings, "workFrom" | "workTo" | "workDays">): boolean {
|
export function inWorkingTime(now: Date, cfg: Pick<WatchdogSettings, "workFrom" | "workTo" | "workDays">): boolean {
|
||||||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: platformZone(), weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
||||||
const hour = Number(parts.find((x) => x.type === "hour")?.value ?? 0);
|
const hour = Number(parts.find((x) => x.type === "hour")?.value ?? 0);
|
||||||
const day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(parts.find((x) => x.type === "weekday")?.value ?? "") + 1;
|
const day = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(parts.find((x) => x.type === "weekday")?.value ?? "") + 1;
|
||||||
return cfg.workDays.includes(day) && hour >= cfg.workFrom && hour < cfg.workTo;
|
return cfg.workDays.includes(day) && hour >= cfg.workFrom && hour < cfg.workTo;
|
||||||
|
|||||||
@ -1,7 +1,6 @@
|
|||||||
// Subscription rotation (PEP-39): a session that hit a usage limit — or got close to it —
|
// Subscription rotation (PEP-39): a session that hit a usage limit — or got close to it —
|
||||||
// moves to another usable subscription of its pool at a turn boundary, continuing the same
|
// moves to another usable subscription of its pool at a turn boundary, continuing the same
|
||||||
// conversation where the CLI allows it. Decided by the watchdog; hooks only set flags.
|
// conversation where the CLI allows it. Decided by the watchdog; hooks only set flags.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import {
|
import {
|
||||||
expireSessionQuestions,
|
expireSessionQuestions,
|
||||||
@ -59,7 +58,7 @@ export async function planRotation(db: Db, s: SessionView, reason: RotateReason,
|
|||||||
return rotationCandidate(db, s, { now, onlyIdle: reason === "threshold" });
|
return rotationCandidate(db, s, { now, onlyIdle: reason === "threshold" });
|
||||||
}
|
}
|
||||||
|
|
||||||
const hhmm = platformTime;
|
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Relaunches the session on `target`: Claude Code and OpenCode continue the same
|
* Relaunches the session on `target`: Claude Code and OpenCode continue the same
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
// The watchdog calls `storyRefineTick`; the model call runs in the background of the tick, on the
|
// The watchdog calls `storyRefineTick`; the model call runs in the background of the tick, on the
|
||||||
// project's subscription, like the intake roles. A failure is said once and never retried — the
|
// project's subscription, like the intake roles. A failure is said once and never retried — the
|
||||||
// comment stays where the developer agent reads it.
|
// comment stays where the developer agent reads it.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { m } from "@peppa/shared/i18n";
|
import { m } from "@peppa/shared/i18n";
|
||||||
import {
|
import {
|
||||||
addIntakeNote,
|
addIntakeNote,
|
||||||
@ -87,16 +86,7 @@ async function refine(db: Db, taskId: number, fresh: RefineComment[], log: (m: s
|
|||||||
}
|
}
|
||||||
const note = out.ok ? parseAnalystNote(out.text) : null;
|
const note = out.ok ? parseAnalystNote(out.text) : null;
|
||||||
if (!note) {
|
if (!note) {
|
||||||
// PEP-304: subscriptions in a limit are not «no subscription» — say until when.
|
const why = out.ok ? m("ответ не по форме") : /нет подписки/.test(out.error) ? m("у проекта не подключена подписка Claude — «⋯ Настройки проекта → Подписки»") : out.error.slice(0, 200);
|
||||||
const why = out.ok
|
|
||||||
? m("ответ не по форме")
|
|
||||||
: out.limited
|
|
||||||
? out.limitedUntil
|
|
||||||
? m("подписки проекта в лимите до {time}", { time: platformTime(out.limitedUntil) })
|
|
||||||
: m("подписки проекта в лимите")
|
|
||||||
: /нет подписки/.test(out.error)
|
|
||||||
? m("у проекта не подключена подписка Claude — «⋯ Настройки проекта → Подписки»")
|
|
||||||
: out.error.slice(0, 200);
|
|
||||||
await addIntakeNote(db, task, "analyst", m("Не смог уточнить постановку ({why}). Описание задачи не менял — комментарий увидит агент, когда возьмётся за задачу.", { why }));
|
await addIntakeNote(db, task, "analyst", m("Не смог уточнить постановку ({why}). Описание задачи не менял — комментарий увидит агент, когда возьмётся за задачу.", { why }));
|
||||||
log(`${ref.key}: story refine failed: ${why}`);
|
log(`${ref.key}: story refine failed: ${why}`);
|
||||||
return;
|
return;
|
||||||
|
|||||||
@ -293,14 +293,12 @@ async function healOne(db: Db, ref: TaskRef, delays: Awaited<ReturnType<typeof l
|
|||||||
}
|
}
|
||||||
if (d.kind === "agent" && d.conflict && d.pull) {
|
if (d.kind === "agent" && d.conflict && d.pull) {
|
||||||
const r = await conflictStep(db, ref, d.pull, { now: new Date(now), log, force: forced });
|
const r = await conflictStep(db, ref, d.pull, { now: new Date(now), log, force: forced });
|
||||||
// PEP-298: `settling` — Gitea's «conflict» is checked again in a minute (the conflict step's tick), not here.
|
if (r !== "held") {
|
||||||
const taken = r !== "held" && r !== "settling";
|
|
||||||
if (taken) {
|
|
||||||
await clearStuckHeal(db, ref.task.id);
|
await clearStuckHeal(db, ref.task.id);
|
||||||
if (card) await clearPlatformDelay(db, scope, "stuck");
|
if (card) await clearPlatformDelay(db, scope, "stuck");
|
||||||
}
|
}
|
||||||
log(`${ref.key}: stuck — a conflict with the main branch, the conflict step: ${r}`);
|
log(`${ref.key}: stuck — a conflict with the main branch, the conflict step: ${r}`);
|
||||||
return taken;
|
return r !== "held";
|
||||||
}
|
}
|
||||||
// PEP-247: no agent ever ran and there is no result yet — the agent simply starts the story.
|
// PEP-247: no agent ever ran and there is no result yet — the agent simply starts the story.
|
||||||
if (!s && !d.pull) {
|
if (!s && !d.pull) {
|
||||||
|
|||||||
@ -2,7 +2,6 @@
|
|||||||
// superadmin for one. The superadmin gets a question with buttons in the platform project; «lend»
|
// superadmin for one. The superadmin gets a question with buttons in the platform project; «lend»
|
||||||
// puts a free subscription of the factory into the project's pool for a while (PEP-107 loans),
|
// puts a free subscription of the factory into the project's pool for a while (PEP-107 loans),
|
||||||
// the waiting agents move onto it at once, and when the time is up it goes back.
|
// the waiting agents move onto it at once, and when the time is up it goes back.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { asIs, m } from "@peppa/shared/i18n";
|
import { asIs, m } from "@peppa/shared/i18n";
|
||||||
import {
|
import {
|
||||||
answerQuestion,
|
answerQuestion,
|
||||||
@ -78,7 +77,7 @@ const requestKey = (projectId: number) => `${PREFIX}${projectId}`;
|
|||||||
const questionKey = (questionId: number) => `subscription.request.q:${questionId}`;
|
const questionKey = (questionId: number) => `subscription.request.q:${questionId}`;
|
||||||
const logKey = (userId: number) => `subscription.request.log:${userId}`;
|
const logKey = (userId: number) => `subscription.request.log:${userId}`;
|
||||||
|
|
||||||
const hhmm = platformTime;
|
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
|
|
||||||
export async function subscriptionRequest(db: Db, projectId: number): Promise<SubscriptionRequest | null> {
|
export async function subscriptionRequest(db: Db, projectId: number): Promise<SubscriptionRequest | null> {
|
||||||
return getSetting<SubscriptionRequest>(db, requestKey(projectId));
|
return getSetting<SubscriptionRequest>(db, requestKey(projectId));
|
||||||
|
|||||||
@ -1,6 +1,5 @@
|
|||||||
// Watchdog: polls Peppa's tmux sessions, tracks activity, and alerts the PM when a
|
// Watchdog: polls Peppa's tmux sessions, tracks activity, and alerts the PM when a
|
||||||
// session dies, stalls, or hits a usage limit. Run under launchd with caffeinate.
|
// session dies, stalls, or hits a usage limit. Run under launchd with caffeinate.
|
||||||
import { platformTime } from "@peppa/shared/time";
|
|
||||||
import { asIs, m } from "@peppa/shared/i18n";
|
import { asIs, m } from "@peppa/shared/i18n";
|
||||||
import { runnerTick } from "./runners.ts";
|
import { runnerTick } from "./runners.ts";
|
||||||
import { projectTrashTick } from "./project-trash.ts";
|
import { projectTrashTick } from "./project-trash.ts";
|
||||||
@ -523,7 +522,7 @@ async function rotateLimited(db: Db, s: SessionView, now: Date, log: (m: string)
|
|||||||
if (s.rotateReason) {
|
if (s.rotateReason) {
|
||||||
await updateSession(db, s.id, { rotateReason: null });
|
await updateSession(db, s.id, { rotateReason: null });
|
||||||
await logSessionEvent(db, s, "rotation_skipped", { reason: "limit", why: m("нет свободной подписки") });
|
await logSessionEvent(db, s, "rotation_skipped", { reason: "limit", why: m("нет свободной подписки") });
|
||||||
const at = platformTime(s.resumeAt!);
|
const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||||
await limitDelay(db, s, m("{who}: лимит, свободных подписок нет — продолжит в {time} сам.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), time: at }), { now, log });
|
await limitDelay(db, s, m("{who}: лимит, свободных подписок нет — продолжит в {time} сам.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), time: at }), { now, log });
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@ -9,8 +9,7 @@
|
|||||||
"./i18n": "./src/i18n/index.ts",
|
"./i18n": "./src/i18n/index.ts",
|
||||||
"./wording": "./src/wording.ts",
|
"./wording": "./src/wording.ts",
|
||||||
"./glossary": "./src/glossary.ts",
|
"./glossary": "./src/glossary.ts",
|
||||||
"./format": "./src/format.ts",
|
"./format": "./src/format.ts"
|
||||||
"./time": "./src/time.ts"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"typecheck": "tsc -p ."
|
"typecheck": "tsc -p ."
|
||||||
|
|||||||
@ -183,6 +183,8 @@ export const accessHub: Record<string, string> = {
|
|||||||
"Зачем": "What for",
|
"Зачем": "What for",
|
||||||
"Причина отказа": "Reason for refusal",
|
"Причина отказа": "Reason for refusal",
|
||||||
"без причины": "no reason",
|
"без причины": "no reason",
|
||||||
|
"Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "The project's agents will be able to read and change data in this service. You can change or revoke the access in «Connections».",
|
||||||
|
"Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "The project's agents will only be able to read data in this service. You can change or revoke the access in «Connections».",
|
||||||
"Или разрешить из уже подключённого": "Or allow from what's already connected",
|
"Или разрешить из уже подключённого": "Or allow from what's already connected",
|
||||||
"Причина — агент её получит, например «используйте тестовые данные»": "Reason — the agent will get it, e.g. «use test data»",
|
"Причина — агент её получит, например «используйте тестовые данные»": "Reason — the agent will get it, e.g. «use test data»",
|
||||||
"читать и менять": "read and change",
|
"читать и менять": "read and change",
|
||||||
@ -367,18 +369,4 @@ export const accessHub: Record<string, string> = {
|
|||||||
"Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}": "The ID goes to `PEPPA_OAUTH_GITHUB_CLIENT_ID`, the new secret to `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}",
|
"Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}": "The ID goes to `PEPPA_OAUTH_GITHUB_CLIENT_ID`, the new secret to `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}",
|
||||||
"Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать.": "Delete the old secret in GitHub; tokens already given to users keep working.",
|
"Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать.": "Delete the old secret in GitHub; tokens already given to users keep working.",
|
||||||
"Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.": "Mark it: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.",
|
"Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.": "Mark it: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.",
|
||||||
// PEP-261: «Дать» buttons under an agent's access request
|
|
||||||
"на срок": "for",
|
|
||||||
"Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».": "The project's agents get the chosen access for the chosen term. You can change, extend or revoke it in «Connections».",
|
|
||||||
"Полные права: чтение и изменения": "Full rights: read and change",
|
|
||||||
"Дать: чтение": "Give: read",
|
|
||||||
"Дать: полные права": "Give: full rights",
|
|
||||||
"Выберите, что дать агенту": "Choose what to give the agent",
|
|
||||||
"Выберите срок": "Choose the term",
|
|
||||||
"полные права": "full rights",
|
|
||||||
"Готово: {what}, {term}. Агент узнает об этом.": "Done: {what}, {term}. The agent will be told.",
|
|
||||||
"Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.": "Choose what to give the agent and for how long (usually 1 day), or refuse.",
|
|
||||||
"Полные права — на какой срок?": "Full rights — for how long?",
|
|
||||||
"Чтение — на какой срок?": "Read — for how long?",
|
|
||||||
"Подключения ещё нет — откройте запрос и подключите сервис": "No connection yet — open the request and connect the service",
|
|
||||||
};
|
};
|
||||||
|
|||||||
@ -543,12 +543,4 @@ export const runner: Dict = {
|
|||||||
"Откройте Главную: там всё по порядку — посмотреть, принять или поправить.": "Open the Home page: everything is there in order — look, accept or ask for changes.",
|
"Откройте Главную: там всё по порядку — посмотреть, принять или поправить.": "Open the Home page: everything is there in order — look, accept or ask for changes.",
|
||||||
"Открыть Главную": "Open Home",
|
"Открыть Главную": "Open Home",
|
||||||
"Задач: {n}": "Tasks: {n}",
|
"Задач: {n}": "Tasks: {n}",
|
||||||
"{who}: подписки проекта в лимите до {time}": "{who}: the project's subscriptions are in a usage limit until {time}",
|
|
||||||
"{who}: подписки проекта в лимите": "{who}: the project's subscriptions are in a usage limit",
|
|
||||||
"Аналитик разберёт задачу позже: подписки проекта в лимите до {time}. После этого разбор продолжится сам.": "The analyst will go through the task later: the project's subscriptions are in a usage limit until {time}. After that the review continues by itself.",
|
|
||||||
"Аналитик разберёт задачу позже: подписки проекта в лимите. Когда лимит сбросится, разбор продолжится сам.": "The analyst will go through the task later: the project's subscriptions are in a usage limit. When the limit resets, the review continues by itself.",
|
|
||||||
"подписки проекта в лимите до {time}": "the project's subscriptions are in a usage limit until {time}",
|
|
||||||
"подписки проекта в лимите": "the project's subscriptions are in a usage limit",
|
|
||||||
"Аналитик отвечает на подписке проекта, а она сейчас в лимите до {time}. Напишите ещё раз после этого времени.": "The analyst answers on the project's subscription, and it is in a usage limit until {time}. Please write again after that time.",
|
|
||||||
"Аналитик отвечает на подписке проекта, а она сейчас в лимите. Напишите ещё раз чуть позже.": "The analyst answers on the project's subscription, and it is in a usage limit right now. Please write again a little later.",
|
|
||||||
};
|
};
|
||||||
|
|||||||
@ -183,6 +183,8 @@ export const accessHub: Record<string, string> = {
|
|||||||
"Зачем": "Не үшін",
|
"Зачем": "Не үшін",
|
||||||
"Причина отказа": "Бас тарту себебі",
|
"Причина отказа": "Бас тарту себебі",
|
||||||
"без причины": "себепсіз",
|
"без причины": "себепсіз",
|
||||||
|
"Агенты проекта смогут читать и менять данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері бұл сервистегі деректерді оқып, өзгерте алады. Қолжетімділікті «Қосылымдар» бөлімінде өзгертуге немесе қайтарып алуға болады.",
|
||||||
|
"Агенты проекта смогут только читать данные в этом сервисе. Изменить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері бұл сервистегі деректерді тек оқи алады. Қолжетімділікті «Қосылымдар» бөлімінде өзгертуге немесе қайтарып алуға болады.",
|
||||||
"Или разрешить из уже подключённого": "Немесе бұрыннан қосылғаннан рұқсат беру",
|
"Или разрешить из уже подключённого": "Немесе бұрыннан қосылғаннан рұқсат беру",
|
||||||
"Причина — агент её получит, например «используйте тестовые данные»": "Себеп — агент оны алады, мысалы «сынақ деректерін пайдаланыңыз»",
|
"Причина — агент её получит, например «используйте тестовые данные»": "Себеп — агент оны алады, мысалы «сынақ деректерін пайдаланыңыз»",
|
||||||
"читать и менять": "оқу және өзгерту",
|
"читать и менять": "оқу және өзгерту",
|
||||||
@ -367,18 +369,4 @@ export const accessHub: Record<string, string> = {
|
|||||||
"Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}": "Идентификатор — `PEPPA_OAUTH_GITHUB_CLIENT_ID`-ге, жаңа құпия — `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`-ке, {restart}",
|
"Идентификатор — в `PEPPA_OAUTH_GITHUB_CLIENT_ID`, новый секрет — в `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`, {restart}": "Идентификатор — `PEPPA_OAUTH_GITHUB_CLIENT_ID`-ге, жаңа құпия — `PEPPA_OAUTH_GITHUB_CLIENT_SECRET`-ке, {restart}",
|
||||||
"Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать.": "Ескі құпияны GitHub-та өшіріңіз; пайдаланушыларға берілген токендер жұмыс істей береді.",
|
"Старый секрет удалить в GitHub; выданные пользователям токены продолжают работать.": "Ескі құпияны GitHub-та өшіріңіз; пайдаланушыларға берілген токендер жұмыс істей береді.",
|
||||||
"Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.": "Белгілеу: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.",
|
"Отметить: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.": "Белгілеу: `peppa secrets rotated PEPPA_OAUTH_GITHUB_CLIENT_SECRET`.",
|
||||||
// PEP-261: «Дать» buttons under an agent's access request
|
|
||||||
"на срок": "мерзімге",
|
|
||||||
"Агенты проекта получат выбранный доступ на выбранный срок. Изменить, продлить или отозвать доступ можно в разделе «Подключения».": "Жоба агенттері таңдалған қолжетімділікті таңдалған мерзімге алады. Оны «Қосылымдар» бөлімінде өзгертуге, ұзартуға немесе қайтарып алуға болады.",
|
|
||||||
"Полные права: чтение и изменения": "Толық құқық: оқу және өзгерту",
|
|
||||||
"Дать: чтение": "Беру: оқу",
|
|
||||||
"Дать: полные права": "Беру: толық құқық",
|
|
||||||
"Выберите, что дать агенту": "Агентке не беретініңізді таңдаңыз",
|
|
||||||
"Выберите срок": "Мерзімді таңдаңыз",
|
|
||||||
"полные права": "толық құқық",
|
|
||||||
"Готово: {what}, {term}. Агент узнает об этом.": "Дайын: {what}, {term}. Агент бұл туралы біледі.",
|
|
||||||
"Выберите, что дать агенту и на какой срок (обычно 1 день), или откажите.": "Агентке не және қанша мерзімге беретініңізді таңдаңыз (әдетте 1 күн) немесе бас тартыңыз.",
|
|
||||||
"Полные права — на какой срок?": "Толық құқық — қанша мерзімге?",
|
|
||||||
"Чтение — на какой срок?": "Оқу — қанша мерзімге?",
|
|
||||||
"Подключения ещё нет — откройте запрос и подключите сервис": "Қосылым әлі жоқ — сұрауды ашып, сервисті қосыңыз",
|
|
||||||
};
|
};
|
||||||
|
|||||||
@ -451,12 +451,4 @@ export const runner: Dict = {
|
|||||||
"Откройте Главную: там всё по порядку — посмотреть, принять или поправить.": "Басты бетті ашыңыз: бәрі ретімен — қарау, қабылдау немесе түзету.",
|
"Откройте Главную: там всё по порядку — посмотреть, принять или поправить.": "Басты бетті ашыңыз: бәрі ретімен — қарау, қабылдау немесе түзету.",
|
||||||
"Открыть Главную": "Басты бетті ашу",
|
"Открыть Главную": "Басты бетті ашу",
|
||||||
"Задач: {n}": "Тапсырмалар: {n}",
|
"Задач: {n}": "Тапсырмалар: {n}",
|
||||||
"{who}: подписки проекта в лимите до {time}": "{who}: жоба жазылымдары {time} дейін лимитте",
|
|
||||||
"{who}: подписки проекта в лимите": "{who}: жоба жазылымдары лимитте",
|
|
||||||
"Аналитик разберёт задачу позже: подписки проекта в лимите до {time}. После этого разбор продолжится сам.": "Аналитик тапсырманы кейінірек талдайды: жоба жазылымдары {time} дейін лимитте. Одан кейін талдау өзі жалғасады.",
|
|
||||||
"Аналитик разберёт задачу позже: подписки проекта в лимите. Когда лимит сбросится, разбор продолжится сам.": "Аналитик тапсырманы кейінірек талдайды: жоба жазылымдары лимитте. Лимит жаңарғанда талдау өзі жалғасады.",
|
|
||||||
"подписки проекта в лимите до {time}": "жоба жазылымдары {time} дейін лимитте",
|
|
||||||
"подписки проекта в лимите": "жоба жазылымдары лимитте",
|
|
||||||
"Аналитик отвечает на подписке проекта, а она сейчас в лимите до {time}. Напишите ещё раз после этого времени.": "Аналитик жоба жазылымымен жауап береді, ал ол қазір {time} дейін лимитте. Осы уақыттан кейін қайта жазыңыз.",
|
|
||||||
"Аналитик отвечает на подписке проекта, а она сейчас в лимите. Напишите ещё раз чуть позже.": "Аналитик жоба жазылымымен жауап береді, ал ол қазір лимитте. Сәл кейінірек қайта жазыңыз.",
|
|
||||||
};
|
};
|
||||||
|
|||||||
@ -1,36 +0,0 @@
|
|||||||
// PEP-304: the time people read — always in the platform's zone (PEPPA_TZ), never the server's
|
|
||||||
// (UTC in the containers). No Node modules: the hook's light modules and the browser may use it.
|
|
||||||
|
|
||||||
const valid = new Map<string, boolean>();
|
|
||||||
const zoneOk = (tz: string) => {
|
|
||||||
let ok = valid.get(tz);
|
|
||||||
if (ok === undefined) {
|
|
||||||
try {
|
|
||||||
new Intl.DateTimeFormat("en-GB", { timeZone: tz });
|
|
||||||
ok = true;
|
|
||||||
} catch {
|
|
||||||
ok = false;
|
|
||||||
}
|
|
||||||
valid.set(tz, ok);
|
|
||||||
}
|
|
||||||
return ok;
|
|
||||||
};
|
|
||||||
|
|
||||||
/** The platform's time zone for `Intl` (`PEPPA_TZ`), or undefined — the process's own — when unset or not a zone. */
|
|
||||||
export function platformZone(env: Record<string, string | undefined> = process.env): string | undefined {
|
|
||||||
const tz = env.PEPPA_TZ?.trim();
|
|
||||||
return tz && zoneOk(tz) ? tz : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
const at = (d: Date | number | string) => (d instanceof Date ? d : new Date(d));
|
|
||||||
|
|
||||||
/** «23:35» in the platform's zone. */
|
|
||||||
export const platformTime = (d: Date | number | string, timeZone = platformZone()) =>
|
|
||||||
new Intl.DateTimeFormat("ru-RU", { timeZone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(at(d));
|
|
||||||
|
|
||||||
/** «25.11, 23:35» in the platform's zone. */
|
|
||||||
export const platformDayTime = (d: Date | number | string, timeZone = platformZone()) =>
|
|
||||||
new Intl.DateTimeFormat("ru-RU", { timeZone, day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(at(d));
|
|
||||||
|
|
||||||
/** «2026-11-25» — the calendar day in the platform's zone (to compare days). */
|
|
||||||
export const platformDay = (d: Date | number | string, timeZone = platformZone()) => new Intl.DateTimeFormat("en-CA", { timeZone }).format(at(d));
|
|
||||||
@ -93,7 +93,7 @@ describe("Срок разрешения", () => {
|
|||||||
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
||||||
assert.ok(r.isError);
|
assert.ok(r.isError);
|
||||||
assert.match(text, /\(expired\)/);
|
assert.match(text, /\(expired\)/);
|
||||||
assert.match(text, /request_access/);
|
assert.match(text, /extend/);
|
||||||
const list = await client.callTool({ name: "list_connections", arguments: {} });
|
const list = await client.callTool({ name: "list_connections", arguments: {} });
|
||||||
assert.match((list.content as Array<{ text: string }>)[0]!.text, /No connections/, "an expired grant is not offered");
|
assert.match((list.content as Array<{ text: string }>)[0]!.text, /No connections/, "an expired grant is not offered");
|
||||||
});
|
});
|
||||||
|
|||||||
@ -1,99 +0,0 @@
|
|||||||
// PEP-315: права истёкшей или снятой выдачи не возвращаются с новой.
|
|
||||||
// 27.11.2026, приёмка PEP-261: агенту дали полные права на срок, срок вышел; на новый запрос владелец
|
|
||||||
// нажал «Дать: чтение» — и проект снова получил запись. grantFor расширял права по строке прошлой
|
|
||||||
// выдачи и не смотрел, действует ли она. Mock service on 127.0.0.1; no agent process.
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { createServer, type Server } from "node:http";
|
|
||||||
import type { AddressInfo } from "node:net";
|
|
||||||
import { after, before, describe, test } from "node:test";
|
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
import { core, db, project, runner, teardown } from "./helpers.ts";
|
|
||||||
|
|
||||||
process.env.PEPPA_SECRET ??= "mock-access-regrant-secret";
|
|
||||||
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1
|
|
||||||
const { agents, connectionGrants, sessions } = await import("@peppa/db");
|
|
||||||
|
|
||||||
const H = 3600_000;
|
|
||||||
let mock: Server;
|
|
||||||
let origin: string;
|
|
||||||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
||||||
|
|
||||||
before(async () => {
|
|
||||||
mock = createServer((req, res) => {
|
|
||||||
res.writeHead(200, { "content-type": "application/json" });
|
|
||||||
res.end(JSON.stringify({ ok: true, path: req.url }));
|
|
||||||
});
|
|
||||||
await new Promise<void>((r) => mock.listen(0, "127.0.0.1", r));
|
|
||||||
origin = `http://127.0.0.1:${(mock.address() as AddressInfo).port}`;
|
|
||||||
anna = await core.upsertUserFromGitea(db, { id: 3151, login: "mock-anna-315" }, { access_token: "a" });
|
|
||||||
});
|
|
||||||
after(async () => {
|
|
||||||
await new Promise<void>((r) => mock.close(() => r()));
|
|
||||||
await teardown();
|
|
||||||
});
|
|
||||||
|
|
||||||
let seq = 0;
|
|
||||||
/** Anna's project with an isolated agent session (no live process: the decision is only logged). */
|
|
||||||
async function setup() {
|
|
||||||
const p = await project({ turns: [] });
|
|
||||||
const proj = await core.getProject(db, p.key);
|
|
||||||
await core.setProjectOwner(db, proj.id, anna.id);
|
|
||||||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
|
||||||
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
|
||||||
const [a] = await db.insert(agents).values({ name: `Мок-агент 315-${++seq}-${Date.now()}` }).returning();
|
|
||||||
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}`, status: "done" }).where(eq(sessions.id, s.id));
|
|
||||||
return { proj, sessionId: s.id };
|
|
||||||
}
|
|
||||||
const crm = (n: string) => core.createConnection(db, anna.id, { name: `CRM ${n}`, baseUrl: `${origin}/api`, secret: `sk_mock_315_${n}_abcdef` });
|
|
||||||
const ask = (sessionId: number, mode: "read" | "write") => core.requestAccess(db, { sessionId, purpose: "посмотреть заказы клиента", host: origin, mode });
|
|
||||||
const grantOf = async (connectionId: number, projectId: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId))).find((g) => g.projectId === projectId && g.agentId == null)!;
|
|
||||||
const read = (sessionId: number, connection: number) => core.callConnection(db, { sessionId, connection, method: "GET", path: "/items" });
|
|
||||||
const write = (sessionId: number, connection: number) => core.callConnection(db, { sessionId, connection, method: "POST", path: "/items", body: "{}" });
|
|
||||||
|
|
||||||
describe("PEP-315: прошлая выдача расширяет новую, только пока она действует", () => {
|
|
||||||
test("Полные права истекли — «Дать: чтение» даёт только чтение", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("expired");
|
|
||||||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "full", term: "1h", operations: ["POST /items"], now: new Date(Date.now() - 2 * H) });
|
|
||||||
assert.deepEqual(await write(sessionId, c.id), { ok: false, reason: "expired" }, "the old grant is over");
|
|
||||||
|
|
||||||
// The agent asks again, for reading; the owner answers «Дать: чтение», 1 day.
|
|
||||||
const { request } = await ask(sessionId, "read");
|
|
||||||
const done = await runner.grantAccessRequestByButton(db, anna.id, request.id, { rights: "read", term: "1d" });
|
|
||||||
assert.equal(done.status, "granted");
|
|
||||||
const g = await grantOf(c.id, proj.id);
|
|
||||||
assert.equal(g.readMode, "auto");
|
|
||||||
assert.equal(g.writeMode, "off", "the owner gave reading only — writing of the expired grant does not come back");
|
|
||||||
assert.deepEqual(g.operations, [], "operations of the expired grant do not come back either");
|
|
||||||
assert.ok((await read(sessionId, c.id)).ok, "reading works");
|
|
||||||
assert.equal((await write(sessionId, c.id)).ok, false, "writing is refused");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Права сняты «без дела» — новая выдача их не возвращает", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("idle");
|
|
||||||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "full", term: "forever" });
|
|
||||||
const old = await grantOf(c.id, proj.id);
|
|
||||||
await db.update(connectionGrants).set({ endedAt: new Date(), endReason: "idle" }).where(eq(connectionGrants.id, old.id));
|
|
||||||
assert.deepEqual(await write(sessionId, c.id), { ok: false, reason: "idle_revoked" });
|
|
||||||
|
|
||||||
const { request } = await ask(sessionId, "read");
|
|
||||||
await runner.grantAccessRequestFromExisting(db, anna.id, request.id, c.id, { rights: "read", term: "7d" });
|
|
||||||
const g = await grantOf(c.id, proj.id);
|
|
||||||
assert.equal(g.writeMode, "off", "reading only");
|
|
||||||
assert.equal(g.endedAt, null, "the grant works again");
|
|
||||||
assert.equal((await write(sessionId, c.id)).ok, false, "writing is refused");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Действующая выдача по-прежнему только расширяется", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("active");
|
|
||||||
// The request is open; meanwhile the owner gives full rights in «Подключениях» and then answers the old request with «Дать: чтение».
|
|
||||||
const { request } = await ask(sessionId, "read");
|
|
||||||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "full", term: "forever" });
|
|
||||||
await runner.grantAccessRequestByButton(db, anna.id, request.id, { rights: "read", term: "1d" });
|
|
||||||
const g = await grantOf(c.id, proj.id);
|
|
||||||
assert.equal(g.writeMode, "auto", "the button does not take away what works now");
|
|
||||||
assert.ok((await write(sessionId, c.id)).ok);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,187 +0,0 @@
|
|||||||
// PEP-261 Access Hub: the owner answers an agent's access request with buttons — «Дать: чтение» /
|
|
||||||
// «Дать: полные права» → term (1 h · 1 day · 7 days · until revoked) or «Отказать» — in Telegram
|
|
||||||
// and in «Агенты просят доступ». Scenario names follow
|
|
||||||
// openspec/changes/archive/2026-11-27-pep-261-access-request-buttons/specs/access-hub/spec.md.
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { createServer, type Server } from "node:http";
|
|
||||||
import type { AddressInfo } from "node:net";
|
|
||||||
import { after, before, describe, test } from "node:test";
|
|
||||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
||||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
||||||
import { eq } from "drizzle-orm";
|
|
||||||
import { stripAsIs } from "@peppa/shared/i18n";
|
|
||||||
import type { Bot } from "@peppa/bot";
|
|
||||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
|
||||||
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
|
|
||||||
|
|
||||||
process.env.PEPPA_SECRET ??= "mock-access-buttons-secret";
|
|
||||||
process.env.PEPPA_CONNECTIONS_ALLOW_PRIVATE = "1"; // the mock service listens on 127.0.0.1
|
|
||||||
process.env.PEPPA_WEB_URL = "https://forge.mock.test";
|
|
||||||
const { createBot } = await import("@peppa/bot");
|
|
||||||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
|
||||||
const { createAgentServer } = await import("@peppa/mcp/agent");
|
|
||||||
const { agents, connectionGrants, sessions } = await import("@peppa/db");
|
|
||||||
|
|
||||||
const H = 3600_000;
|
|
||||||
const tg = await new MockTelegram().start();
|
|
||||||
const ANNA = { id: 2611, chatId: 2611, username: "anna261" };
|
|
||||||
const BORIS = { id: 2612, chatId: 2612, username: "boris261" };
|
|
||||||
let bot: Bot;
|
|
||||||
let mock: Server;
|
|
||||||
let origin: string;
|
|
||||||
let anna: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
||||||
let boris: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
||||||
|
|
||||||
const said = (who: typeof ANNA, re: RegExp) => waitFor(`bot message ${re}`, async () => tg.botMessages(who.chatId).filter((m) => re.test(stripAsIs(m.text))).at(-1));
|
|
||||||
const datas = (m: MockTgMessage) => (m.reply_markup?.inline_keyboard.flat() ?? []).map((b) => b.callback_data ?? (b as { url?: string }).url ?? "");
|
|
||||||
const toast = (id: string) => waitFor(`answer to ${id}`, async () => tg.callbackAnswers.find((a) => a.id === id)?.text);
|
|
||||||
const pair = async (who: typeof ANNA, userId: number) => {
|
|
||||||
tg.userSends(who, `/start ${await core.createPairingCode(db, tg.token, userId)}`);
|
|
||||||
await said(who, /Привязано/);
|
|
||||||
};
|
|
||||||
|
|
||||||
before(async () => {
|
|
||||||
mock = createServer((req, res) => {
|
|
||||||
res.writeHead(200, { "content-type": "application/json" });
|
|
||||||
res.end(JSON.stringify({ ok: true, path: req.url }));
|
|
||||||
});
|
|
||||||
await new Promise<void>((r) => mock.listen(0, "127.0.0.1", r));
|
|
||||||
origin = `http://127.0.0.1:${(mock.address() as AddressInfo).port}`;
|
|
||||||
anna = await core.upsertUserFromGitea(db, { id: 2611, login: "mock-anna-261" }, { access_token: "a" });
|
|
||||||
boris = await core.upsertUserFromGitea(db, { id: 2612, login: "mock-boris-261" }, { access_token: "b" });
|
|
||||||
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "https://forge.mock.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 400 });
|
|
||||||
await bot.start();
|
|
||||||
await pair(ANNA, anna.id);
|
|
||||||
await pair(BORIS, boris.id);
|
|
||||||
});
|
|
||||||
after(async () => {
|
|
||||||
await bot.stop();
|
|
||||||
await tg.stop();
|
|
||||||
await new Promise<void>((r) => mock.close(() => r()));
|
|
||||||
await teardown();
|
|
||||||
});
|
|
||||||
|
|
||||||
let seq = 0;
|
|
||||||
/** Anna's project with an isolated agent session (no live process: the decision is only logged). */
|
|
||||||
async function setup() {
|
|
||||||
const p = await project({ turns: [] });
|
|
||||||
const proj = await core.getProject(db, p.key);
|
|
||||||
await core.setProjectOwner(db, proj.id, anna.id);
|
|
||||||
const task = (await core.listTasks(db, { projectId: proj.id }))[0]!;
|
|
||||||
const s = await core.createSession(db, { projectId: proj.id, taskId: task.id });
|
|
||||||
const [a] = await db.insert(agents).values({ name: `Мок-агент 261-${++seq}-${Date.now()}` }).returning();
|
|
||||||
await db.update(sessions).set({ agentId: a!.id, container: `peppa-s${s.id}`, status: "done" }).where(eq(sessions.id, s.id));
|
|
||||||
return { proj, sessionId: s.id };
|
|
||||||
}
|
|
||||||
const crm = (n: string) => core.createConnection(db, anna.id, { name: `CRM ${n}`, baseUrl: `${origin}/api`, secret: `sk_mock_261_${n}_abcdef` });
|
|
||||||
const ask = (sessionId: number, o: { host?: string; service?: string; mode?: "read" | "write" }) => core.requestAccess(db, { sessionId, purpose: "посмотреть заказы клиента", ...o });
|
|
||||||
const grantsOf = async (connectionId: number, projectId: number) => (await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connectionId))).filter((g) => g.projectId === projectId);
|
|
||||||
const message = (id: number) => waitFor(`message about request #${id}`, async () => tg.botMessages(ANNA.chatId).find((m) => datas(m).includes(`ar:${id}:no`)));
|
|
||||||
|
|
||||||
describe("Кнопки выдачи под запросом доступа", () => {
|
|
||||||
test("Чтение на 1 день кнопкой в Telegram", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("tg");
|
|
||||||
const { request } = await ask(sessionId, { host: origin, mode: "read" });
|
|
||||||
const m = await message(request.id);
|
|
||||||
assert.match(stripAsIs(m.text), /на какой срок/, "the text says to choose rights and term");
|
|
||||||
assert.ok(datas(m).includes(`ar:${request.id}:r`) && datas(m).includes(`ar:${request.id}:f`), JSON.stringify(m.reply_markup));
|
|
||||||
|
|
||||||
// «Дать: чтение» → the keyboard turns into terms, 1 day first.
|
|
||||||
assert.match((await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:r`)))!, /срок/);
|
|
||||||
const terms = await waitFor("term buttons", async () => (datas(tg.messages.get(m.message_id)!).includes(`ar:${request.id}:r:7d`) ? tg.messages.get(m.message_id)! : null));
|
|
||||||
assert.deepEqual(datas(terms).slice(1, 5), ["1d", "1h", "7d", "forever"].map((t) => `ar:${request.id}:r:${t}`));
|
|
||||||
// «Назад» brings the rights back; then read + 1 day.
|
|
||||||
await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:back`));
|
|
||||||
await waitFor("rights again", async () => datas(tg.messages.get(m.message_id)!).includes(`ar:${request.id}:f`) || null);
|
|
||||||
const done = await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:r:1d`));
|
|
||||||
assert.match(stripAsIs(done!), /Готово: чтение, 1 день/);
|
|
||||||
await waitFor("buttons removed", async () => (datas(tg.messages.get(m.message_id)!).length === 0) || null);
|
|
||||||
|
|
||||||
assert.equal((await core.getAccessRequest(db, request.id))!.status, "granted");
|
|
||||||
const [g] = await grantsOf(c.id, proj.id);
|
|
||||||
assert.equal(g!.term, "1d");
|
|
||||||
assert.equal(g!.readMode, "auto");
|
|
||||||
assert.equal(g!.writeMode, "off");
|
|
||||||
assert.ok(Math.abs(g!.expiresAt!.getTime() - (Date.now() + 24 * H)) < 60_000, "expires in a day");
|
|
||||||
|
|
||||||
// The agent calls now — and gets «истёк» a day later.
|
|
||||||
const now = await core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" });
|
|
||||||
assert.ok(now.ok, JSON.stringify(now));
|
|
||||||
const later = await core.callConnection(db, { sessionId, connection: c.id, method: "GET", path: "/items" }, { now: new Date(Date.now() + 25 * H) });
|
|
||||||
assert.deepEqual(later, { ok: false, reason: "expired" });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Чужой не может нажать «Дать»", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("boris");
|
|
||||||
const { request } = await ask(sessionId, { host: origin, mode: "write" });
|
|
||||||
const m = await message(request.id);
|
|
||||||
await assert.rejects(runner.grantAccessRequestByButton(db, boris.id, request.id, { rights: "full", term: "forever" }), /Запрос не найден/);
|
|
||||||
const answer = await toast(tg.userClicks(BORIS, m.message_id, `ar:${request.id}:f:forever`));
|
|
||||||
assert.doesNotMatch(stripAsIs(answer ?? ""), /Готово/);
|
|
||||||
assert.equal((await core.getAccessRequest(db, request.id))!.status, "open");
|
|
||||||
assert.equal((await grantsOf(c.id, proj.id)).length, 0, "no grant");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Подключения ещё нет", async () => {
|
|
||||||
const { sessionId } = await setup();
|
|
||||||
const { request } = await ask(sessionId, { service: "stripe" });
|
|
||||||
const m = await message(request.id);
|
|
||||||
assert.ok(!datas(m).includes(`ar:${request.id}:r`), "no «Дать» without a connection");
|
|
||||||
assert.ok(datas(m).includes(`https://forge.mock.test/connections/requests/${request.id}`), "«Подключить» — the request's card");
|
|
||||||
assert.match(stripAsIs(m.text), /Откройте запрос/);
|
|
||||||
await assert.rejects(runner.grantAccessRequestByButton(db, anna.id, request.id, { rights: "read" }), /Подключения ещё нет/);
|
|
||||||
const answer = await toast(tg.userClicks(ANNA, m.message_id, `ar:${request.id}:r`));
|
|
||||||
assert.match(stripAsIs(answer!), /Подключения ещё нет/);
|
|
||||||
assert.equal((await core.getAccessRequest(db, request.id))!.status, "open");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Срок на карточке запроса", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const { request } = await ask(sessionId, { service: "stripe", mode: "read" });
|
|
||||||
const out = await runner.connectAndGrantAccessRequest(db, anna.id, request.id, { secret: "sk_test_mock_STRIPE_261_123456" }, { rights: "full", term: "7d" });
|
|
||||||
assert.equal(out.request.status, "granted");
|
|
||||||
const [g] = await grantsOf(out.connection.id, proj.id);
|
|
||||||
assert.equal(g!.term, "7d");
|
|
||||||
assert.equal(g!.readMode, "auto");
|
|
||||||
assert.equal(g!.writeMode, "auto", "full rights");
|
|
||||||
assert.equal(out.request.term, "7d");
|
|
||||||
assert.match(runner.accessDecisionText(out.request), /чтение и запись на 7 дней/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Без выбора — срок 1 день и права по запросу", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("default");
|
|
||||||
const { request } = await ask(sessionId, { host: origin, mode: "write" });
|
|
||||||
await runner.grantAccessRequestFromExisting(db, anna.id, request.id, c.id);
|
|
||||||
const [g] = await grantsOf(c.id, proj.id);
|
|
||||||
assert.equal(g!.term, "1d");
|
|
||||||
assert.equal(g!.writeMode, "auto");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Разбор кнопок", () => {
|
|
||||||
assert.deepEqual(core.parseAccessCallback("ar:5:r"), { id: 5, action: "rights", rights: "read" });
|
|
||||||
assert.deepEqual(core.parseAccessCallback("ar:5:f:7d"), { id: 5, action: "grant", rights: "full", term: "7d" });
|
|
||||||
assert.deepEqual(core.parseAccessCallback("ar:5:no"), { id: 5, action: "no" });
|
|
||||||
assert.equal(core.parseAccessCallback("ar:5:r:2d"), null);
|
|
||||||
assert.equal(core.parseAccessCallback("ar:5:no:1d"), null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Истёкший доступ — новый запрос", () => {
|
|
||||||
test("Отказ после истечения", async () => {
|
|
||||||
const { proj, sessionId } = await setup();
|
|
||||||
const c = await crm("expired");
|
|
||||||
await core.grantConnection(db, anna.id, c.id, { projectId: proj.id, rights: "read", term: "1h", now: new Date(Date.now() - 2 * H) });
|
|
||||||
const [a, b] = InMemoryTransport.createLinkedPair();
|
|
||||||
await createAgentServer(db, { defaultKey: proj.key, sessionId, lockProject: true }).connect(a);
|
|
||||||
const client = new Client({ name: "mock-agent", version: "0" });
|
|
||||||
await client.connect(b);
|
|
||||||
const r = await client.callTool({ name: "call_connection", arguments: { connection: c.id, method: "GET", path: "/items" } });
|
|
||||||
const text = (r.content as Array<{ text: string }>)[0]!.text;
|
|
||||||
assert.equal(r.isError, true);
|
|
||||||
assert.match(text, /expired/);
|
|
||||||
assert.ok(text.includes(`request_access(host: "${origin}/api"`), text);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,183 +0,0 @@
|
|||||||
// PEP-298, spec platform-delays «Конфликт с основной веткой — отдельный шаг»: Gitea re-checks
|
|
||||||
// mergeability in the background after a push or a branch update and answers «conflict» meanwhile.
|
|
||||||
// The first request to the agent goes only when the same head still conflicts CONFLICT_SETTLE_MIN
|
|
||||||
// later; a story taken from review in vain goes back by itself. And the story card counts the checks
|
|
||||||
// by the same list as the gate (that of the head commit). Mock Gitea, no agent turns.
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { mkdtempSync, writeFileSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join } from "node:path";
|
|
||||||
import { after, before, describe, test } from "node:test";
|
|
||||||
import { core, db, project, runner, setDefaultOwner, teardown } from "./helpers.ts";
|
|
||||||
import { MockGitea } from "../src/mock-gitea.ts";
|
|
||||||
import { events, sessions } from "@peppa/db";
|
|
||||||
import { and, eq } from "drizzle-orm";
|
|
||||||
|
|
||||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
|
||||||
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-settle-")), "gitea"));
|
|
||||||
const BOT = { id: 74, login: "peppa-bot", token: "mock-token-bot" };
|
|
||||||
const MIN = 60_000;
|
|
||||||
|
|
||||||
before(async () => {
|
|
||||||
await gitea.start();
|
|
||||||
process.env.GITEA_URL = gitea.url;
|
|
||||||
process.env.GITEA_TOKEN = BOT.token;
|
|
||||||
// The pause this story adds (helpers.ts turns it off for the other suites).
|
|
||||||
process.env.PEPPA_CONFLICT_SETTLE_MIN = String(runner.CONFLICT_SETTLE_MIN);
|
|
||||||
gitea.addUser(BOT);
|
|
||||||
const owner = await core.upsertUserFromGitea(db, { id: 9401, login: "mock-owner-settle" }, { access_token: "x" });
|
|
||||||
setDefaultOwner(owner.id);
|
|
||||||
runner.setConflictFilesLister(async () => ["a.txt"]);
|
|
||||||
});
|
|
||||||
after(async () => {
|
|
||||||
process.env.PEPPA_CONFLICT_SETTLE_MIN = "0";
|
|
||||||
runner.setConflictFilesLister(null);
|
|
||||||
await gitea.stop();
|
|
||||||
await teardown();
|
|
||||||
});
|
|
||||||
|
|
||||||
/** A story in review, its agent finished, its green result in a PR; `checks` — the list of the head commit. */
|
|
||||||
async function inReview(checks: Record<string, string> = { test: "pnpm test" }) {
|
|
||||||
const tp = await project({ turns: [] });
|
|
||||||
const proj = await core.getProject(db, tp.key);
|
|
||||||
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks });
|
|
||||||
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
|
|
||||||
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
|
|
||||||
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
|
|
||||||
const branch = `task/${tp.taskKey}`;
|
|
||||||
let n = 0;
|
|
||||||
const push = (files: Record<string, string> = {}) => {
|
|
||||||
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { [`f${n++}.txt`]: String(n), ...files });
|
|
||||||
for (const c of Object.keys(checks)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "success");
|
|
||||||
return sha;
|
|
||||||
};
|
|
||||||
push();
|
|
||||||
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
|
|
||||||
const ref = await core.resolveTask(db, tp.taskKey);
|
|
||||||
await core.updateTask(db, ref, { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
|
|
||||||
const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id });
|
|
||||||
await db.update(sessions).set({ status: "done", endedAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s.id));
|
|
||||||
const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
|
|
||||||
const requests = async () => (await db.select().from(events).where(and(eq(events.taskId, ref.task.id), eq(events.type, "conflict_rebase_requested")))).length;
|
|
||||||
const status = async () => (await core.resolveTask(db, tp.taskKey)).task.status;
|
|
||||||
const live = async () => (await core.listSessions(db, { active: true, taskId: ref.task.id })).length;
|
|
||||||
const fresh = () => core.resolveTask(db, tp.taskKey);
|
|
||||||
return { tp, proj, ref, pull, push, requests, status, live, fresh };
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A periodic path that sees the conflict (the held «готово», the accept, the auto-merge…), then the minute tick. */
|
|
||||||
async function sight(t: Awaited<ReturnType<typeof inReview>>, at: number) {
|
|
||||||
const ref = await t.fresh();
|
|
||||||
const pull = (await core.prGate(ref)).pull!;
|
|
||||||
if (pull.mergeable === false) await runner.conflictStep(db, ref, pull, { now: new Date(at) });
|
|
||||||
await runner.conflictStepTick(db, { now: new Date(at) });
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("Конфликт с основной веткой — ложный «конфликт» сразу после обновления (PEP-298)", () => {
|
|
||||||
test("Scenario: Gitea две минуты после обновления ветки отвечает «конфликт» — агент не вызывается", async () => {
|
|
||||||
const t = await inReview();
|
|
||||||
const T = Date.now();
|
|
||||||
// FORGE updated the branch: a new head, Gitea re-checks it and says «conflict» meanwhile.
|
|
||||||
t.push();
|
|
||||||
t.pull().mergeable = false;
|
|
||||||
await sight(t, T);
|
|
||||||
assert.equal(await t.requests(), 0, "the first sight asks nobody");
|
|
||||||
assert.ok(await runner.getConflictSeen(db, t.ref.task.id), "the sight is remembered");
|
|
||||||
await sight(t, T + 1 * MIN);
|
|
||||||
assert.equal(await t.requests(), 0, "a minute later — still waiting for the second look");
|
|
||||||
// Gitea finished re-checking: no conflict.
|
|
||||||
t.pull().mergeable = true;
|
|
||||||
await sight(t, T + 2 * MIN);
|
|
||||||
await sight(t, T + 5 * MIN);
|
|
||||||
assert.equal(await t.requests(), 0, "no request at all");
|
|
||||||
assert.equal(await t.status(), "review", "the story stays in review");
|
|
||||||
assert.equal(await t.live(), 0, "no agent started");
|
|
||||||
assert.equal(await runner.getConflictSeen(db, t.ref.task.id), null, "the sight is forgotten");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Scenario: Настоящий конфликт — просьба уходит через CONFLICT_SETTLE_MIN", async () => {
|
|
||||||
const t = await inReview();
|
|
||||||
const T = Date.now();
|
|
||||||
t.pull().mergeable = false;
|
|
||||||
// The agent cannot start right away (no room): the request waits in the queue.
|
|
||||||
await core.waitForCapacity(db, t.ref.task.id, null, new Date(T));
|
|
||||||
await sight(t, T);
|
|
||||||
await runner.conflictStepTick(db, { now: new Date(T + 1 * MIN) });
|
|
||||||
assert.equal(await t.requests(), 0);
|
|
||||||
// Only the minute tick looks again — a periodic path that comes once an hour needs no second visit.
|
|
||||||
await runner.conflictStepTick(db, { now: new Date(T + runner.CONFLICT_SETTLE_MIN * MIN) });
|
|
||||||
assert.equal(await t.requests(), 1, "the request goes after the settle time");
|
|
||||||
assert.equal(await t.status(), "in_progress");
|
|
||||||
assert.equal((await runner.getConflictStep(db, t.ref.task.id))?.from, "review");
|
|
||||||
await runner.conflictStepTick(db, { now: new Date(T + 10 * MIN) });
|
|
||||||
assert.equal(await t.requests(), 1, "one request per conflict");
|
|
||||||
await core.clearCapacityWait(db, t.ref.task.id);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Scenario: Новая голова сбрасывает ожидание", async () => {
|
|
||||||
const t = await inReview();
|
|
||||||
const T = Date.now();
|
|
||||||
t.pull().mergeable = false;
|
|
||||||
await sight(t, T);
|
|
||||||
t.push(); // the agent (or FORGE) pushed a minute later
|
|
||||||
await sight(t, T + 1 * MIN);
|
|
||||||
await sight(t, T + 2 * MIN);
|
|
||||||
assert.equal(await t.requests(), 0, "the new head is judged from its own first sight");
|
|
||||||
assert.equal(await t.status(), "review");
|
|
||||||
t.pull().mergeable = true;
|
|
||||||
await sight(t, T + 3 * MIN);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Scenario: Зря переведённая в работу задача возвращается на проверку сама", async () => {
|
|
||||||
const t = await inReview();
|
|
||||||
const T = Date.now();
|
|
||||||
t.pull().mergeable = false;
|
|
||||||
await core.waitForCapacity(db, t.ref.task.id, null, new Date(T));
|
|
||||||
await sight(t, T);
|
|
||||||
await sight(t, T + 3 * MIN);
|
|
||||||
assert.equal(await t.requests(), 1);
|
|
||||||
assert.equal(await t.status(), "in_progress");
|
|
||||||
// The conflict went by itself (Gitea re-checked longer than usual), the agent never started.
|
|
||||||
t.pull().mergeable = true;
|
|
||||||
await runner.conflictStepTick(db, { now: new Date(T + 4 * MIN) });
|
|
||||||
assert.equal(await t.status(), "review", "back to review");
|
|
||||||
assert.equal(await core.isWaitingForCapacity(db, t.ref.task.id), false, "the agent's place in the queue is given up");
|
|
||||||
assert.equal(await runner.getConflictStep(db, t.ref.task.id), null);
|
|
||||||
const [e] = await db.select().from(events).where(and(eq(events.taskId, t.ref.task.id), eq(events.type, "conflict_false_back_to_review")));
|
|
||||||
assert.ok(e, "logged");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Агент уже обновил изменения — задача на проверку сама не возвращается", async () => {
|
|
||||||
const t = await inReview();
|
|
||||||
const T = Date.now();
|
|
||||||
t.pull().mergeable = false;
|
|
||||||
await core.waitForCapacity(db, t.ref.task.id, null, new Date(T));
|
|
||||||
await sight(t, T);
|
|
||||||
await sight(t, T + 3 * MIN);
|
|
||||||
assert.equal(await t.status(), "in_progress");
|
|
||||||
t.push();
|
|
||||||
t.pull().mergeable = true;
|
|
||||||
await runner.conflictStepTick(db, { now: new Date(T + 10 * MIN) });
|
|
||||||
assert.equal(await t.status(), "in_progress", "the agent hands it off itself");
|
|
||||||
await core.clearCapacityWait(db, t.ref.task.id);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Карточка задачи и допуск считают проверки по одному списку (PEP-298)", () => {
|
|
||||||
test("Scenario: В последней версии нужна проверка, которой нет в основной копии", async () => {
|
|
||||||
// The head's list has four checks, the main working copy — three (PEP-217: «4 из 4» against «3 из 4»).
|
|
||||||
const t = await inReview({ lint: "pnpm lint", build: "pnpm build", typecheck: "pnpm typecheck", test: "pnpm test" });
|
|
||||||
writeFileSync(join(t.tp.dir, ".peppa/project.json"), JSON.stringify({ slug: t.proj.slug, key: t.tp.key, checks: { lint: "x", build: "x", typecheck: "x" } }));
|
|
||||||
const head = (await core.prGate(await t.fresh())).pull!.head.sha;
|
|
||||||
const r = gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo);
|
|
||||||
// `test` never reported on this head.
|
|
||||||
r.statuses.set(head, (r.statuses.get(head) ?? []).filter((s) => s.context !== "peppa/test"));
|
|
||||||
for (const c of ["lint", "build", "typecheck"]) await runner.recordCheck(db, t.proj, { sha: head, branch: `task/${t.tp.taskKey}`, check: c, state: "success" });
|
|
||||||
const ref = await t.fresh();
|
|
||||||
const card = await core.taskCiSummary(db, ref);
|
|
||||||
const gate = await core.prGate(ref);
|
|
||||||
assert.equal(card.total, gate.summary?.total, "one list");
|
|
||||||
assert.equal(card.label, gate.summary?.label);
|
|
||||||
assert.equal(card.state, "pending");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -88,8 +88,8 @@ describe("PEP-272: ответы веба не раскрывают служеб
|
|||||||
});
|
});
|
||||||
|
|
||||||
for (const [url, shown] of [
|
for (const [url, shown] of [
|
||||||
["http://git.vibe42.kz/avatars/1", "https://git.vibe42.kz/avatars/1"],
|
["http://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"],
|
||||||
["https://git.vibe42.kz/avatars/1", "https://git.vibe42.kz/avatars/1"],
|
["https://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"],
|
||||||
["javascript:alert(1)", null],
|
["javascript:alert(1)", null],
|
||||||
["", null],
|
["", null],
|
||||||
] as const) {
|
] as const) {
|
||||||
@ -99,7 +99,7 @@ describe("PEP-272: ответы веба не раскрывают служеб
|
|||||||
}
|
}
|
||||||
|
|
||||||
test("Аватар Gitea по http сохраняется как https", async () => {
|
test("Аватар Gitea по http сохраняется как https", async () => {
|
||||||
const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.vibe42.kz/avatars/7" }, { access_token: "x" });
|
const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.telecom.quest/avatars/7" }, { access_token: "x" });
|
||||||
assert.equal(u.avatarUrl, "https://git.vibe42.kz/avatars/7");
|
assert.equal(u.avatarUrl, "https://git.telecom.quest/avatars/7");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@ -54,9 +54,6 @@ Object.assign(process.env, {
|
|||||||
PEPPA_READY_DIGEST: "off",
|
PEPPA_READY_DIGEST: "off",
|
||||||
PEPPA_STUCK_TASKS: "off",
|
PEPPA_STUCK_TASKS: "off",
|
||||||
PEPPA_ORPHAN_CONFLICTS: "off",
|
PEPPA_ORPHAN_CONFLICTS: "off",
|
||||||
// PEP-298: the first request about a conflict waits for a second sight 2 min later; suites that
|
|
||||||
// script a conflict step by step ask at once — conflict-settle.test.ts turns the pause on.
|
|
||||||
PEPPA_CONFLICT_SETTLE_MIN: "0",
|
|
||||||
// PEP-266: the launch smoke test starts agents on its own — launch-smoke.test.ts turns it on.
|
// PEP-266: the launch smoke test starts agents on its own — launch-smoke.test.ts turns it on.
|
||||||
PEPPA_SMOKE: "off",
|
PEPPA_SMOKE: "off",
|
||||||
PEPPA_CONNECTION_CHECK: "off",
|
PEPPA_CONNECTION_CHECK: "off",
|
||||||
|
|||||||
@ -1,116 +0,0 @@
|
|||||||
// PEP-304: subscriptions in a limit are not «no subscription»; the time people read is in the
|
|
||||||
// platform's zone (PEPPA_TZ), whatever the process's own zone is.
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join, resolve } from "node:path";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import { after, before, describe, test } from "node:test";
|
|
||||||
import { platformDayTime, platformTime, platformZone } from "@peppa/shared/time";
|
|
||||||
import { stripAsIs } from "@peppa/shared/i18n";
|
|
||||||
import { releases } from "@peppa/db";
|
|
||||||
import { core, db, runner, teardown } from "./helpers.ts";
|
|
||||||
|
|
||||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
|
||||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
|
||||||
const TMP = mkdtempSync(join(tmpdir(), "peppa-limit-reason-"));
|
|
||||||
const scenario = join(TMP, "scenario.json");
|
|
||||||
const savedTz = process.env.PEPPA_TZ;
|
|
||||||
|
|
||||||
type User = Awaited<ReturnType<typeof core.registerEgovUser>>;
|
|
||||||
let owner: User;
|
|
||||||
let seq = 0;
|
|
||||||
before(async () => {
|
|
||||||
process.env.PEPPA_INTAKE_BIN = join(ROOT, "packages/testkit/bin/mock-intake");
|
|
||||||
process.env.MOCK_INTAKE_SCENARIO = scenario;
|
|
||||||
writeFileSync(scenario, "{}");
|
|
||||||
// Self-registered: no machine login for its projects — only the project's own subscriptions.
|
|
||||||
owner = await core.registerEgovUser(db, { iin: "900101300304", name: "САДОВА ГУЛЬНАРА" });
|
|
||||||
});
|
|
||||||
after(async () => {
|
|
||||||
if (savedTz === undefined) delete process.env.PEPPA_TZ;
|
|
||||||
else process.env.PEPPA_TZ = savedTz;
|
|
||||||
await teardown();
|
|
||||||
});
|
|
||||||
|
|
||||||
async function project(withSub: "limited" | "none") {
|
|
||||||
const n = ++seq;
|
|
||||||
const ws = join(TMP, `ws${n}`);
|
|
||||||
mkdirSync(join(ws, ".peppa"), { recursive: true });
|
|
||||||
const p = await core.createProject(db, { slug: `mock-garden-${n}`, key: `GRD${String.fromCharCode(64 + n)}`, name: `Сад ${n}`, giteaOwner: "x", workspacePath: ws, ownerId: owner.id });
|
|
||||||
await core.setIntakeSettings(db, p.id, { enabled: true });
|
|
||||||
if (withSub === "limited") {
|
|
||||||
const sub = await core.createSubscription(db, { provider: "claude", name: `mock-sub-${p.key}`, authKind: "oauth", secret: "mock-token" });
|
|
||||||
await core.updateSubscription(db, sub.id, { status: "limited", limitedUntil: RESET });
|
|
||||||
const pool = await core.createPool(db, { name: `mock-pool-${p.key}`, subscriptionIds: [sub.id] });
|
|
||||||
await core.setProjectPool(db, p.id, pool.id);
|
|
||||||
}
|
|
||||||
return p;
|
|
||||||
}
|
|
||||||
// A future reset (the subscriptions judge «limited» by the real clock); 18:50 UTC = 23:50 in Almaty.
|
|
||||||
const RESET = new Date("2030-01-10T18:50:00Z");
|
|
||||||
const notes = async (taskId: number) => (await core.storyComments(db, taskId)).map((c) => stripAsIs(c.text));
|
|
||||||
|
|
||||||
describe("PEP-304: подписки в лимите — не «нет подписки»", () => {
|
|
||||||
test("Scenario: Все подписки в лимите — заметка с временем сброса, разбор повторяется после него", async () => {
|
|
||||||
process.env.PEPPA_TZ = "Asia/Almaty"; // UTC+5
|
|
||||||
const p = await project("limited");
|
|
||||||
const ref = await core.createTask(db, { projectId: p.id, title: "Полив по расписанию", description: "Хочу включать полив по часам" });
|
|
||||||
const now = new Date("2030-01-10T18:35:00Z");
|
|
||||||
await runner.intakeTick(db, { wait: true, now });
|
|
||||||
await runner.intakeTick(db, { wait: true, now: new Date(now.getTime() + 60_000) });
|
|
||||||
let state = (await core.getIntakeState(db, ref.task.id))!;
|
|
||||||
const said = await notes(ref.task.id);
|
|
||||||
assert.equal(said.length, 1, "one note per limit");
|
|
||||||
assert.match(said[0]!, /подписки проекта в лимите до 23:50/);
|
|
||||||
assert.doesNotMatch(said[0]!, /не подключена подписка|идёт в работу как написана/);
|
|
||||||
assert.notEqual(state.stage, "done", "the story waits for the analyst, not «as written»");
|
|
||||||
assert.equal(state.attempts, 0, "a limit is no attempt");
|
|
||||||
assert.equal(state.retryAt, Date.parse("2030-01-10T18:51:00Z"));
|
|
||||||
|
|
||||||
// Before the reset: not even a try. After it the subscription is usable again — the analyst goes through the story.
|
|
||||||
await runner.intakeTick(db, { wait: true, now: new Date("2030-01-10T18:50:30Z") });
|
|
||||||
assert.notEqual((await core.getIntakeState(db, ref.task.id))!.stage, "done");
|
|
||||||
const [sub] = (await core.listSubscriptions(db)).filter((x) => x.name === `mock-sub-${p.key}`);
|
|
||||||
await core.updateSubscription(db, sub!.id, { status: "active", limitedUntil: null });
|
|
||||||
await runner.intakeTick(db, { wait: true, now: new Date("2030-01-10T18:52:00Z") });
|
|
||||||
state = (await core.getIntakeState(db, ref.task.id))!;
|
|
||||||
assert.equal(state.stage, "done");
|
|
||||||
assert.equal((await notes(ref.task.id)).filter((t) => /в лимите/.test(t)).length, 1);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Scenario: Подписки нет — прежняя причина «не подключена подписка»", async () => {
|
|
||||||
const p = await project("none");
|
|
||||||
const ref = await core.createTask(db, { projectId: p.id, title: "Учёт урожая", description: "Записывать, сколько собрали" });
|
|
||||||
await runner.intakeTick(db, { wait: true });
|
|
||||||
await runner.intakeTick(db, { wait: true });
|
|
||||||
const said = await notes(ref.task.id);
|
|
||||||
assert.equal(said.length, 1);
|
|
||||||
assert.match(said[0]!, /у проекта не подключена подписка/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("PEP-304: время для людей — в поясе платформы", () => {
|
|
||||||
test("Scenario: Пояс платформы отличается от пояса сервера", () => {
|
|
||||||
process.env.PEPPA_TZ = "Asia/Almaty";
|
|
||||||
const at = new Date("2026-11-25T18:35:00Z");
|
|
||||||
assert.equal(platformTime(at), "23:35");
|
|
||||||
assert.equal(platformDayTime(at), "25.11, 23:35");
|
|
||||||
process.env.PEPPA_TZ = "America/New_York";
|
|
||||||
assert.equal(platformTime(at), "13:35");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Scenario: Неверный пояс — время в поясе процесса, без падения", () => {
|
|
||||||
process.env.PEPPA_TZ = "Not/AZone";
|
|
||||||
assert.equal(platformZone(), undefined);
|
|
||||||
const at = new Date("2026-11-25T18:35:00Z");
|
|
||||||
assert.equal(platformTime(at), at.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", hourCycle: "h23" }));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Scenario: Подпись версии в чате — в поясе платформы", async () => {
|
|
||||||
process.env.PEPPA_TZ = "Asia/Almaty";
|
|
||||||
const p = await project("none");
|
|
||||||
const [rel] = await db.insert(releases).values({ projectId: p.id, env: "staging", sha: "a".repeat(40), status: "healthy", createdAt: new Date("2026-11-25T18:35:00Z") }).returning();
|
|
||||||
assert.match(stripAsIs((await core.threadTitle(db, `release:${rel!.id}`))!), /25\.11, 23:35$/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -72,8 +72,7 @@ function oldMonitor(hosts: string[]): number {
|
|||||||
VALUES ('Интернет', 'internet', ?, 60, 5000, 3, 2, 'system', ?, ?, ?) RETURNING id`,
|
VALUES ('Интернет', 'internet', ?, 60, 5000, 3, 2, 'system', ?, ?, ?) RETURNING id`,
|
||||||
)
|
)
|
||||||
.get(JSON.stringify({ hosts }), iso, iso, iso) as { id: number };
|
.get(JSON.stringify({ hosts }), iso, iso, iso) as { id: number };
|
||||||
// The version right before the PEP-281 migration — other migrations (PEP-217: web_vitals) stay applied.
|
raw.exec("PRAGMA user_version = 3");
|
||||||
raw.exec(`PRAGMA user_version = ${core.observeMigrationIndex(OLD_HOST)}`);
|
|
||||||
raw.close();
|
raw.close();
|
||||||
return row.id;
|
return row.id;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -85,32 +85,6 @@ describe("Вкладка «Код»", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// PEP-313 (27.11.2026): the CI step's report and the watchdog's poll wrote the same check at once —
|
|
||||||
// «UNIQUE constraint failed: check_runs.project_id, check_runs.sha, check_runs.check», the report was lost.
|
|
||||||
describe("Результат проверки пишут двое сразу", () => {
|
|
||||||
test("Отчёт шага и опрос статусов одновременно — одна запись, журнал отчёта цел, «изменилось» — один раз", async () => {
|
|
||||||
const p = await tabsProject("MTRACE", { "README.md": "# R" }, { ".peppa/project.json": JSON.stringify({ key: "MTRACE", checks: { test: "pnpm test" } }) });
|
|
||||||
const ref = await core.createTask(db, { projectId: p.id, title: "Гонка отчётов" });
|
|
||||||
const sha = "c".repeat(40);
|
|
||||||
const [a, b] = await Promise.all([
|
|
||||||
core.upsertCheckRun(db, p, ref.task.id, { sha, check: "test", state: "failure", logTail: "✖ упал один тест", source: "report" }),
|
|
||||||
core.upsertCheckRun(db, p, null, { sha, check: "test", state: "failure", source: "poll" }),
|
|
||||||
]);
|
|
||||||
assert.equal(a.run.id, b.run.id, "one row for the commit and the check");
|
|
||||||
assert.deepEqual([a.changed, b.changed], [true, false], "the red check is news once");
|
|
||||||
assert.equal(b.run.logTail, "✖ упал один тест", "the poll keeps the log the CI step sent");
|
|
||||||
assert.equal(b.run.taskId, ref.task.id);
|
|
||||||
// The other order: the poll first, the report with the log second.
|
|
||||||
const sha2 = "d".repeat(40);
|
|
||||||
const [c, d] = await Promise.all([
|
|
||||||
core.upsertCheckRun(db, p, null, { sha: sha2, check: "test", state: "success", source: "poll" }),
|
|
||||||
core.upsertCheckRun(db, p, ref.task.id, { sha: sha2, check: "test", state: "success", logTail: "ok", source: "report" }),
|
|
||||||
]);
|
|
||||||
assert.equal(c.run.id, d.run.id);
|
|
||||||
assert.equal(d.run.logTail, "ok");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Вкладка «PR»", () => {
|
describe("Вкладка «PR»", () => {
|
||||||
test("Scenario: PR стори — ключ стори и «Проверки: 2 из 2 пройдены»; PR без стори — без проверок", async () => {
|
test("Scenario: PR стори — ключ стори и «Проверки: 2 из 2 пройдены»; PR без стори — без проверок", async () => {
|
||||||
const p = await tabsProject("MTPR", { "README.md": "# PR" }, { ".peppa/project.json": JSON.stringify({ key: "MTPR", checks: { test: "pnpm test", build: "pnpm build" } }) });
|
const p = await tabsProject("MTPR", { "README.md": "# PR" }, { ".peppa/project.json": JSON.stringify({ key: "MTPR", checks: { test: "pnpm test", build: "pnpm build" } }) });
|
||||||
|
|||||||
@ -1,84 +0,0 @@
|
|||||||
// PEP-285: аудит стека FORGE относительно Default Stack — все слои стандарта, статус из шкалы, разделы.
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { existsSync, readFileSync } from "node:fs";
|
|
||||||
import { resolve } from "node:path";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import { describe, test } from "node:test";
|
|
||||||
|
|
||||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
|
||||||
const STANDARD = "docs/standards/default-stack.md";
|
|
||||||
const AUDIT = "docs/standards/forge-stack-audit.md";
|
|
||||||
const STATUSES = ["соответствует", "частично", "отклонение", "неприменимо"];
|
|
||||||
const PRIORITIES = ["P1", "P2", "P3", "сохранить", "—"];
|
|
||||||
const SECTIONS = [
|
|
||||||
"Сводка по слоям",
|
|
||||||
"Слои",
|
|
||||||
"DDD-Lite",
|
|
||||||
"PostgreSQL, UUIDv7 и pg_stat_statements",
|
|
||||||
"Bugsink",
|
|
||||||
"Gitea и Forgejo",
|
|
||||||
"Docker",
|
|
||||||
"Roadmap",
|
|
||||||
"На рассмотрение владельцу",
|
|
||||||
];
|
|
||||||
|
|
||||||
function read(path: string): string {
|
|
||||||
return readFileSync(resolve(ROOT, path), "utf8");
|
|
||||||
}
|
|
||||||
|
|
||||||
function sections(text: string, level: string): Map<string, string> {
|
|
||||||
const out = new Map<string, string>();
|
|
||||||
for (const p of text.split(new RegExp(`^${level} `, "m")).slice(1)) {
|
|
||||||
const nl = p.indexOf("\n");
|
|
||||||
out.set(p.slice(0, nl).trim(), p.slice(nl + 1));
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Слои стандарта — заголовки «### …» внутри раздела «## Слои». */
|
|
||||||
function standardLayers(): string[] {
|
|
||||||
return [...sections(sections(read(STANDARD), "##").get("Слои")!, "###").keys()];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Строки таблицы «Сводка по слоям»: слой → ячейки. */
|
|
||||||
function summaryRows(): Map<string, string[]> {
|
|
||||||
const table = sections(read(AUDIT), "##").get("Сводка по слоям")!;
|
|
||||||
const rows = new Map<string, string[]>();
|
|
||||||
for (const line of table.split("\n")) {
|
|
||||||
if (!line.startsWith("|") || /^\|[-| ]+\|$/.test(line)) continue;
|
|
||||||
const cells = line.split("|").slice(1, -1).map((c) => c.trim());
|
|
||||||
if (cells[0] === "Слой") continue;
|
|
||||||
rows.set(cells[0], cells);
|
|
||||||
}
|
|
||||||
return rows;
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("Аудит стека FORGE (PEP-285)", () => {
|
|
||||||
test("Владелец смотрит, где FORGE отличается от стандарта: каждый слой — в таблице и разобран", () => {
|
|
||||||
assert.ok(existsSync(resolve(ROOT, AUDIT)), `нет ${AUDIT}`);
|
|
||||||
const rows = summaryRows();
|
|
||||||
const detail = sections(sections(read(AUDIT), "##").get("Слои")!, "###");
|
|
||||||
for (const layer of standardLayers()) {
|
|
||||||
assert.ok(rows.has(layer), `в аудите нет слоя «${layer}» в сводке`);
|
|
||||||
assert.ok(detail.has(layer), `в аудите нет раздела слоя «${layer}»`);
|
|
||||||
assert.match(detail.get(layer)!, /\*\*Сейчас:\*\*/, `${layer}: нет «Сейчас»`);
|
|
||||||
}
|
|
||||||
assert.equal(rows.get("База данных: PostgreSQL")![3], "отклонение");
|
|
||||||
assert.match(rows.get("База данных: PostgreSQL")![1], /SQLite/);
|
|
||||||
assert.match(detail.get("База данных: PostgreSQL")!, /PEP-36/);
|
|
||||||
assert.equal(rows.get("Аналитика: GA4")![3], "неприменимо");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Статус вне шкалы: у каждого слоя статус и приоритет из шкалы", () => {
|
|
||||||
for (const [layer, cells] of summaryRows()) {
|
|
||||||
assert.ok(STATUSES.includes(cells[3]), `${layer}: статус «${cells[3]}» вне шкалы`);
|
|
||||||
assert.ok(PRIORITIES.includes(cells[5]), `${layer}: приоритет «${cells[5]}» вне шкалы`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Отдельные разделы, roadmap и решения владельцу на месте; стандарт ссылается на аудит", () => {
|
|
||||||
const top = sections(read(AUDIT), "##");
|
|
||||||
for (const s of SECTIONS) assert.ok(top.has(s), `нет раздела: ${s}`);
|
|
||||||
assert.ok(read(STANDARD).includes("forge-stack-audit.md"), "стандарт не ссылается на аудит");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@ -1,99 +0,0 @@
|
|||||||
// PEP-284: новые проекты получают FORGE Default Stack в своих инструкциях — из шаблона в Gitea,
|
|
||||||
// а не только из файла в репозитории платформы; свой AGENTS.md подключённого репозитория не трогаем.
|
|
||||||
// Тесты названы по сценариям openspec/changes/pep-284-template-default-stack/specs/engineering-standards.
|
|
||||||
import assert from "node:assert/strict";
|
|
||||||
import { execFileSync } from "node:child_process";
|
|
||||||
import { cpSync, mkdtempSync, readFileSync } from "node:fs";
|
|
||||||
import { tmpdir } from "node:os";
|
|
||||||
import { join, resolve } from "node:path";
|
|
||||||
import { fileURLToPath } from "node:url";
|
|
||||||
import { after, before, describe, test } from "node:test";
|
|
||||||
import { core, db, runner, teardown } from "./helpers.ts";
|
|
||||||
import { MockGitea } from "../src/mock-gitea.ts";
|
|
||||||
|
|
||||||
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
|
|
||||||
const TMP = mkdtempSync(join(tmpdir(), "peppa-tpl-stack-"));
|
|
||||||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
|
||||||
process.env.PEPPA_WORKSPACES = join(TMP, "workspaces");
|
|
||||||
|
|
||||||
const STANDARD = "docs/standards/default-stack.md";
|
|
||||||
const read = (p: string) => readFileSync(join(ROOT, p), "utf8");
|
|
||||||
const gitea = new MockGitea(join(TMP, "gitea"));
|
|
||||||
const ALICE = { id: 284, login: "mock-stack-alice", token: "mock-token-stack-alice" };
|
|
||||||
const BOT = { id: 285, login: "peppa-bot", token: "mock-token-stack-bot" };
|
|
||||||
let alice: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
|
||||||
let templateUrl = "";
|
|
||||||
|
|
||||||
before(async () => {
|
|
||||||
await gitea.start();
|
|
||||||
process.env.GITEA_URL = gitea.url;
|
|
||||||
process.env.GITEA_TOKEN = BOT.token;
|
|
||||||
for (const u of [ALICE, BOT]) gitea.addUser(u);
|
|
||||||
// The template repository in Gitea is out of date, as before a deploy.
|
|
||||||
templateUrl = gitea.addRepo("peppa-bot", "template", { files: { "AGENTS.md": "# old agents\n", "RULES.md": "# old rules\n" } }).path;
|
|
||||||
alice = await core.upsertUserFromGitea(db, ALICE, { access_token: ALICE.token });
|
|
||||||
});
|
|
||||||
after(async () => {
|
|
||||||
await gitea.stop();
|
|
||||||
await teardown();
|
|
||||||
});
|
|
||||||
|
|
||||||
const show = (repo: string, path: string) => execFileSync("git", ["--git-dir", repo, "show", `main:${path}`], { encoding: "utf8" });
|
|
||||||
const provision = async (o: { slug: string; key: string; existing?: boolean }) =>
|
|
||||||
runner.provisionProject(db, {
|
|
||||||
gitea: await core.giteaForUser(db, alice),
|
|
||||||
owner: ALICE.login,
|
|
||||||
ownerIsUser: true,
|
|
||||||
name: `Mock ${o.key}`,
|
|
||||||
ownerId: alice.id,
|
|
||||||
templateUrl,
|
|
||||||
...o,
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Новый проект получает стандарт стека в своих инструкциях", () => {
|
|
||||||
test("Сценарий: Копия стандарта в шаблоне отстала", () => {
|
|
||||||
assert.equal(read(`template/${STANDARD}`), read(STANDARD), `копия стандарта в шаблоне отличается от ${STANDARD}: скопируйте файл в template/`);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Сценарий: Создание нового проекта", async () => {
|
|
||||||
// The same road as the live system: template/ of the commit → template repo → new project.
|
|
||||||
const dir = join(TMP, "template");
|
|
||||||
cpSync(join(ROOT, "template"), dir, { recursive: true });
|
|
||||||
assert.equal((await runner.syncTemplate({ push: true, dir, templateUrl, commit: "pep284abc" })).state, "pushed");
|
|
||||||
|
|
||||||
await provision({ slug: "stack-demo", key: "STD" });
|
|
||||||
const repo = gitea.repos.get(`${ALICE.login}/stack-demo`)!.path;
|
|
||||||
const agents = show(repo, "AGENTS.md");
|
|
||||||
assert.equal(agents, read("template/AGENTS.md"));
|
|
||||||
const stack = agents.slice(agents.indexOf("## Стек\n"), agents.indexOf("## Проект\n"));
|
|
||||||
assert.ok(stack.length > 20, "в AGENTS.md нового проекта нет раздела «Стек»");
|
|
||||||
for (const w of ["Go", "Gin", "uptrace/bun", "Viper", "PostgreSQL", "UUIDv7", "Next.js App Router", "TanStack", "Vite", "DDD-Lite", STANDARD, "design.md", "remember"]) {
|
|
||||||
assert.ok(stack.includes(w), `раздел «Стек» без «${w}»`);
|
|
||||||
}
|
|
||||||
assert.match(stack, /не переводи на стандарт сам/);
|
|
||||||
assert.equal(show(repo, STANDARD), read(STANDARD));
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("Существующий стек и инструкции проекта важнее стандарта", () => {
|
|
||||||
test("Сценарий: Подключение репозитория со своим AGENTS.md", async () => {
|
|
||||||
const own = "# AGENTS.md\n\nСтек: Python + Django\n";
|
|
||||||
const r = gitea.addRepo(ALICE.login, "legacy-app", { files: { "AGENTS.md": own } });
|
|
||||||
r.collaborators["peppa-bot"] = "write";
|
|
||||||
await provision({ slug: "legacy-app", key: "LEG", existing: true });
|
|
||||||
const agents = show(r.path, "AGENTS.md");
|
|
||||||
assert.equal(agents, own);
|
|
||||||
assert.doesNotMatch(agents, /## Стек\n/);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("Сценарий: Агент в проекте на другом стеке", () => {
|
|
||||||
const rules = read("template/RULES.md");
|
|
||||||
const sec = rules.slice(rules.indexOf("## Стек проекта\n"), rules.indexOf("## CI: проверки перед PR\n"));
|
|
||||||
assert.ok(sec.length > 20, "в RULES.md нет раздела «Стек проекта»");
|
|
||||||
assert.match(sec, /важнее стандарта/);
|
|
||||||
assert.match(sec, /не мигрируй сам/);
|
|
||||||
assert.ok(sec.includes(STANDARD));
|
|
||||||
assert.match(sec, /design\.md/);
|
|
||||||
assert.match(sec, /не переписывай/);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user