PEP-304: подписки в лимите — не «нет подписки»; время людям — в поясе платформы
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
511e85661b
commit
020886eb1c
@ -1,6 +1,7 @@
|
||||
// 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).
|
||||
// «Инженер» and the superadmin see the stack, tags, events and the link to Bugsink.
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Bug, ExternalLink } from "lucide-react";
|
||||
@ -46,8 +47,8 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
|
||||
<ErrorStateBadge state={r.state} t={t} />
|
||||
<span>{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||
{d.users != null ? <span>{t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")}</span> : null}
|
||||
<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()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||
<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.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
{r.taskKey ? (
|
||||
@ -109,7 +110,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">
|
||||
{d.events.map((e) => (
|
||||
<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" })}</span>
|
||||
<span className="tabular-nums">{e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium", timeZone: platformZone() })}</span>
|
||||
<span className="font-mono text-xs text-muted-foreground">{e.id.slice(0, 8)}</span>
|
||||
</li>
|
||||
))}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// glossary-ignore-file: the section is for the superadmin only.
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Trash2 } from "lucide-react";
|
||||
@ -19,7 +20,7 @@ import { deleteMonitorAction, pauseMonitorAction, updateMonitorAction } from "..
|
||||
export const dynamic = "force-dynamic";
|
||||
const PAGE = 100;
|
||||
|
||||
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" });
|
||||
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() });
|
||||
|
||||
export default async function MonitorPage({ params, searchParams }: { params: Promise<{ id: string }>; searchParams: Promise<{ error?: string; page?: string }> }) {
|
||||
const user = await requireUser();
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// glossary-ignore-file: the section is for the superadmin only.
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
||||
@ -80,7 +81,7 @@ async function SmokeSection({ t }: { t: Awaited<ReturnType<typeof getT>> }) {
|
||||
skipped: [t("не проверен"), "text-muted-foreground"],
|
||||
};
|
||||
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" });
|
||||
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() });
|
||||
return (
|
||||
<Section
|
||||
title={t("Запуск агентов")}
|
||||
@ -282,7 +283,7 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
||||
<ul className="m-0 flex list-none flex-col gap-1 p-0 text-sm">
|
||||
{flog.map((e) => (
|
||||
<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" })}</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", timeZone: platformZone() })}</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>
|
||||
{e.reason && <span className="text-muted-foreground">{e.reason}</span>}
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
import { Fragment } from "react";
|
||||
import { ProductCard } from "@/components/ProductCard";
|
||||
@ -769,7 +770,7 @@ export default async function ProjectPage({ params, searchParams }: { params: Pr
|
||||
))}
|
||||
</td>
|
||||
<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" })}
|
||||
{r.deployedBy} · {r.createdAt.toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() })}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// 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 "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Sparkles } from "lucide-react";
|
||||
@ -102,7 +103,7 @@ export default async function PlanEpicPage({ params, searchParams }: { params: P
|
||||
<Button size="sm" variant="ghost">{t("Удалить черновик")}</Button>
|
||||
</form>
|
||||
<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" }), author: draft.createdBy })}
|
||||
{t("Черновик от {date}, {author}.", { date: new Date(draft.createdAt).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }), author: draft.createdBy })}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// 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 { Archive, ExternalLink, GitBranch, GitPullRequest, Pencil } from "lucide-react";
|
||||
import type { Epic, SpecSummary } from "@peppa/core";
|
||||
@ -13,7 +14,7 @@ import { Input, Textarea } from "@/components/ui/input";
|
||||
import { getT } from "@/lib/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" }) : "—");
|
||||
const when = (iso: string | null, t: Translator) => (iso ? new Date(iso).toLocaleString(intlLocale(t.locale), { dateStyle: "short", timeStyle: "short", timeZone: platformZone() }) : "—");
|
||||
|
||||
export async function CodeTab({ code }: { code: RepoOverview }) {
|
||||
const t = await getT();
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// 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 "next/link";
|
||||
import type { ReactNode } from "react";
|
||||
import { Gauge, Hourglass, Play } from "lucide-react";
|
||||
@ -74,7 +75,7 @@ function WindowCell({ label, w, t }: { label: string; w: WindowView | null; t: T
|
||||
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 limited = a.limitedUntil ? ", " + t("в лимите") : "";
|
||||
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale)) }) : "";
|
||||
const updated = a.at ? ", " + t("обновлено {at}", { at: a.at.toLocaleString(intlLocale(t.locale), { timeZone: platformZone() }) }) : "";
|
||||
return t.text(a.name) + " — " + w(t("5 ч"), a.fiveHour) + ", " + w(t("7 д"), a.sevenDay) + limited + updated;
|
||||
}
|
||||
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 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,
|
||||
// stacks and tags; «Продакт» — the title, how often, when and the bug task.
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
import { Bug, TrendingUp } from "lucide-react";
|
||||
import type { ErrorDetail, ErrorFilter, ErrorRow, ErrorScope, ErrorsOverview, ErrorState } from "@peppa/core";
|
||||
@ -16,7 +17,7 @@ import { errorAction } from "@/app/(app)/errors/actions";
|
||||
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 hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
const hhmm = (d: Date, t: Translator) => d.toLocaleTimeString(t.locale === "en" ? "en-GB" : "ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
||||
|
||||
/** 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 }) {
|
||||
@ -91,8 +92,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}
|
||||
{showProject ? <span>{r.bugsinkName}</span> : null}
|
||||
<span className="tabular-nums">{t.n(r.events, "{n} раз", "{n} раза", "{n} раз")}</span>
|
||||
<span title={r.firstSeen.toLocaleString()}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||
<span title={r.lastSeen.toLocaleString()}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||
<span title={r.firstSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("впервые {ago}", { ago: ago(r.firstSeen, t) })}</span>
|
||||
<span title={r.lastSeen.toLocaleString(undefined, { timeZone: platformZone() })}>{t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}</span>
|
||||
{/* 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}
|
||||
{r.taskKey ? <Key href={`/t/${r.taskKey}`}>{r.taskKey}</Key> : null}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// Observability (PEP-202): shared pieces of the monitors list and the monitor page.
|
||||
// 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 type { Translator } from "@peppa/shared/i18n";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
@ -26,7 +27,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" />
|
||||
))}
|
||||
{recent.map((c) => (
|
||||
<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")} />
|
||||
<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")} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
@ -125,4 +126,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>;
|
||||
}
|
||||
|
||||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
import { DELAY_REASON_NAMES, type DelayView } from "@peppa/core";
|
||||
import { delayActionForm } from "@/app/(app)/dashboard/actions";
|
||||
@ -13,7 +14,7 @@ import { getT } from "@/lib/i18n";
|
||||
*/
|
||||
export async function PlatformDelays({ delays, actions = false }: { delays: DelayView[]; actions?: boolean }) {
|
||||
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: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = (ms: number) => new Date(ms).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
||||
return (
|
||||
<ul className="m-0 flex list-none flex-col gap-2 p-0" data-delays>
|
||||
{delays.map((d) => (
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import type { ReactNode } from "react";
|
||||
import Link from "next/link";
|
||||
import type { PoolOverview, PoolSubscriptionState } from "@peppa/core";
|
||||
@ -5,7 +6,7 @@ import { intlLocale, type Locale } from "@peppa/shared/i18n";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { getT } from "@/lib/i18n";
|
||||
|
||||
const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = (d: Date, locale: Locale) => d.toLocaleTimeString(intlLocale(locale), { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
||||
const KIND: Record<PoolSubscriptionState["provider"], string> = { claude: "Claude", codex: "ChatGPT", opencode: "OpenCode" };
|
||||
|
||||
function tone(s: PoolSubscriptionState): "ok" | "warn" | "danger" | "muted" | "primary" {
|
||||
@ -75,7 +76,7 @@ export async function PoolSwitches({ o }: { o: PoolOverview }) {
|
||||
<span className="font-medium text-foreground">{t("Переключения")}</span>
|
||||
{o.switches.map((x, i) => (
|
||||
<span key={i}>
|
||||
{x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined })}
|
||||
{x.at.toLocaleString(intlLocale(t.locale), { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit", timeZone: platformZone() })}
|
||||
{" · "}
|
||||
{x.taskKey ? <Link href={`/t/${x.taskKey}`}>{x.taskKey}</Link> : t("агент №{id}", { id: x.sessionId ?? "?" })}
|
||||
{": "}
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// Domain cards shared by pages: agent questions, runners, project list.
|
||||
import { platformZone } from "@peppa/shared/time";
|
||||
import Link from "next/link";
|
||||
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";
|
||||
@ -358,4 +359,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" });
|
||||
const hhmm = (d: Date) => new Date(d).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: platformZone() });
|
||||
|
||||
@ -0,0 +1,20 @@
|
||||
# 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}`.
|
||||
@ -0,0 +1,26 @@
|
||||
# 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`.
|
||||
@ -0,0 +1,17 @@
|
||||
## 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** заметка «у проекта не подключена подписка»
|
||||
@ -0,0 +1,14 @@
|
||||
## 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** сообщение отправляется со временем в поясе процесса
|
||||
13
openspec/changes/pep-304-limit-reason-platform-time/tasks.md
Normal file
13
openspec/changes/pep-304-limit-reason-platform-time/tasks.md
Normal file
@ -0,0 +1,13 @@
|
||||
## 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, тесты
|
||||
@ -2,6 +2,7 @@
|
||||
// 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
|
||||
// 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 { createHmac, randomBytes } from "node:crypto";
|
||||
import { chatMessages, chats, events, incidents, projects, questions, releases, tasks, telegramOutbox, users, type Db } from "@peppa/db";
|
||||
@ -152,7 +153,7 @@ export async function threadTitle(db: Db, key: string): Promise<string | null> {
|
||||
if (kind === "release") {
|
||||
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.
|
||||
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 r ? `${ENV_RU[r.env] ?? r.env} · ${platformDayTime(r.createdAt)}` : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@ -77,6 +77,10 @@ export interface IntakeState {
|
||||
attempts: number;
|
||||
/** Why the roles were skipped or gave up, if they did. */
|
||||
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}`;
|
||||
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 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
|
||||
// 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 { execFileSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
@ -230,7 +231,8 @@ export async function alertAdmins(db: Db, key: string, text: string, log: (m: st
|
||||
return queued;
|
||||
}
|
||||
|
||||
const hhmm = (iso: string) => new Date(iso).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit" });
|
||||
// PEP-304: the platform's zone, not the server's.
|
||||
const hhmm = platformTime;
|
||||
|
||||
/**
|
||||
* Checks every service but `self` and alerts admins about outages and recoveries.
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
// 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.
|
||||
// glossary-ignore-file: the section is for the superadmin only.
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
@ -640,14 +641,8 @@ async function send(db: Db, key: string, text: string, log: (s: string) => void)
|
||||
await alertAdmins(db, `mon:${key}`, text, log);
|
||||
}
|
||||
|
||||
const clock = (iso: string) => {
|
||||
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-304: the platform's zone; a wrong PEPPA_TZ falls back inside platformTime.
|
||||
const clock = (iso: string) => platformTime(iso);
|
||||
|
||||
/** 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 {
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// 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 { projects, sessions, subscriptions, tasks, users, type Db } from "@peppa/db";
|
||||
import { and, count, eq, inArray, isNotNull } from "drizzle-orm";
|
||||
@ -175,7 +176,7 @@ export async function projectAgentWarning(db: Db, projectId: number, now = new D
|
||||
const why = subs.map((s) => {
|
||||
const v = { name: publicSubscriptionName(s), status: STATUS_RU[s.status] ?? s.status };
|
||||
if (s.status !== "limited" || !s.limitedUntil) return tr("{name} — {status}", v);
|
||||
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("{name} — {status} до {until}", { ...v, until: platformDayTime(s.limitedUntil) });
|
||||
});
|
||||
return tr("у проекта нет рабочей подписки: {why}", { why: why.join(", ") });
|
||||
}
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
// 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
|
||||
// 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 { formatTaskKey } from "@peppa/shared";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
@ -292,7 +293,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.
|
||||
const platform = list.some((d) => d.state === "platform");
|
||||
if (next == null) return platform ? tr("Сбой на нашей стороне, чиним — задача продолжится сама") : tr("Задерживается на нашей стороне, мы этим занимаемся");
|
||||
const tz = o.timeZone ?? process.env.PEPPA_TZ ?? undefined;
|
||||
const tz = o.timeZone ?? platformZone();
|
||||
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));
|
||||
if (platform) return day(next) !== day(now)
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 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
|
||||
// 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 { and, desc, eq, inArray, like } from "drizzle-orm";
|
||||
import { m as tr, ruPlural } from "@peppa/shared/i18n";
|
||||
@ -16,7 +17,7 @@ import type { User } from "./users.ts";
|
||||
|
||||
export const warnThresholdPct = () => Number(process.env.PEPPA_ROTATE_THRESHOLD_PCT ?? 85);
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = platformTime;
|
||||
|
||||
// ── loans ────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@ -414,6 +414,22 @@ export async function claudeTokenForProject(db: Db, project: Pick<Project, "id">
|
||||
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. */
|
||||
export async function projectPool(db: Db, projectId: number): Promise<SubscriptionPool | null> {
|
||||
const [row] = await db
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// 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
|
||||
// neither — the UI says «нет данных» rather than inventing numbers.
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import { m as tr } from "@peppa/shared/i18n";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { projects, sessions, settings, subscriptionPoolMembers, subscriptions, type Db, type SessionUsage, type UsageTokens, keyPrefix } from "@peppa/db";
|
||||
@ -374,7 +375,7 @@ export async function listAccountUsage(db: Db, o: { subscriptionIds?: number[] |
|
||||
return out.sort((a, b) => accountPeak(b) - accountPeak(a));
|
||||
}
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = platformTime;
|
||||
|
||||
/** «5 ч 42% (сброс 14:30) · 7 д 18%» — one line for the bot and MCP. */
|
||||
export function describeAccount(a: AccountUsage): string {
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
// 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
|
||||
// asked for are filed into the backlog, already formulated (the intake roles skip them).
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import {
|
||||
addChatMessage,
|
||||
analystChatContext,
|
||||
@ -147,8 +148,14 @@ 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.
|
||||
await setAnalystCursor(db, chatId, upTo);
|
||||
if (!out.ok) {
|
||||
const noSub = /нет подписки/.test(out.error);
|
||||
await offer(await say(db, project, chatId, (noSub ? tr("Аналитик отвечает на подписке проекта, а она не подключена. Подключите Claude в «⋯ Настройки проекта → Подписки» — и напишите ещё раз.") : tr("Аналитик сейчас не смог ответить. Напишите ещё раз чуть позже.")) + pick, false), { kind: "choice", text, answer: null });
|
||||
const noSub = !out.limited && /нет подписки/.test(out.error);
|
||||
// PEP-304: all subscriptions in a limit — say until when, not «не подключена».
|
||||
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}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@ -6,7 +6,8 @@ import { spawn } from "node:child_process";
|
||||
import { copyFileSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { claudeTokenForProject, isProjectPaused, mayUseMachineLogin, NO_AUTOUPDATE_ENV, type Project } from "@peppa/core";
|
||||
import { claudeTokenForProject, isProjectPaused, mayUseMachineLogin, NO_AUTOUPDATE_ENV, projectClaudeLimit, type Project } from "@peppa/core";
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import { projects, type Db } from "@peppa/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
@ -24,7 +25,11 @@ export interface ClaudePrintOptions {
|
||||
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. */
|
||||
export function envelopeText(stdout: string): string | null {
|
||||
@ -44,7 +49,17 @@ 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.
|
||||
if (!token) {
|
||||
const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, project.id));
|
||||
if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) return { ok: false, error: m("{who}: у проекта нет подписки Claude", { who: o.who }) };
|
||||
if (!(await mayUseMachineLogin(db, p?.ownerId ?? null))) {
|
||||
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.
|
||||
const cwd = mkdtempSync(join(tmpdir(), "peppa-print-"));
|
||||
|
||||
@ -7,6 +7,7 @@
|
||||
// dispatcher skips stories the analyst has not finished with (`readyBacklog`); a PM who drags the
|
||||
// card to work overrides it.
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import {
|
||||
addDependency,
|
||||
addIntakeNote,
|
||||
@ -55,7 +56,19 @@ 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). */
|
||||
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). */
|
||||
async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) => void): Promise<IntakeState> {
|
||||
@ -63,7 +76,7 @@ async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) =
|
||||
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 out = await ask(db, project, intakePrompt(context, { title: task.title, description: state.original.description }, legacy), m("аналитик"));
|
||||
if (!out.ok) throw new Error(out.error);
|
||||
if (!out.ok) throw out.limited ? new LimitedError(out.error, out.limitedUntil ?? null) : new Error(out.error);
|
||||
const note = parseIntakeNote(out.text, task.title);
|
||||
if (!note) throw new Error(m("аналитик ответил не по формату"));
|
||||
// The parts of the request: each checked for a repeat first (3.5), then filed after this story.
|
||||
@ -124,11 +137,29 @@ async function advance(db: Db, taskId: number, now: Date, log: (m: string) => vo
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (state.retryAt && state.retryAt > now.getTime()) return;
|
||||
try {
|
||||
state = await step(db, ref, state, log);
|
||||
await setIntakeState(db, taskId, state);
|
||||
log(`${ref.key}: intake → ${state.stage}`);
|
||||
} 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;
|
||||
// The roles must never hold a story for ever: after a couple of failures it goes on as written.
|
||||
if (attempts >= MAX_ATTEMPTS) {
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// PEP-150: a usage limit with no subscription to switch to. Kept light — the hook process
|
||||
// imports it (no runner flow behind it).
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import { asIs, m } from "@peppa/shared/i18n";
|
||||
import { answerQuestion, askPm, clearPlatformDelay, getSession, getSetting, listSessions, sessionDelay, setSetting, type SessionView, type TaskRef } from "@peppa/core";
|
||||
import { projects, tasks, type Db } from "@peppa/db";
|
||||
@ -50,7 +51,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));
|
||||
if (!row) return;
|
||||
const ref: TaskRef = { ...row, key: formatTaskKey(row.project.key, row.task.number) };
|
||||
const time = new Date(resumeAt).toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const time = platformTime(resumeAt);
|
||||
const q = await askPm(db, ref, {
|
||||
kind: "question",
|
||||
options: [LIMIT_ADD, LIMIT_REQUEST, LIMIT_WAIT],
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
// 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 { markSubscriptionLimited, updateSession, type SessionView } from "@peppa/core";
|
||||
import type { Db } from "@peppa/db";
|
||||
@ -109,7 +110,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).
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = platformTime;
|
||||
const today = (now: Date) => now.toLocaleDateString("sv-SE"); // YYYY-MM-DD, local
|
||||
|
||||
/**
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 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
|
||||
// checks; here the live agents are stopped and, on «Продолжить», resumed.
|
||||
import { platformDayTime } from "@peppa/shared/time";
|
||||
import {
|
||||
activateRunnerTask,
|
||||
clearProjectPause,
|
||||
@ -17,7 +18,7 @@ import { resumeSession, stopSession } from "./sessions.ts";
|
||||
const WORKING = ["proposing", "in_progress"];
|
||||
|
||||
const stamp = (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 });
|
||||
platformDayTime(ms);
|
||||
|
||||
/**
|
||||
* Puts the project on pause: from this moment nothing starts and nobody is notified; the live
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
// `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
|
||||
// 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 type { Db } from "@peppa/db";
|
||||
import { sayInDiscussion } from "./analyst-chat.ts";
|
||||
@ -10,7 +11,7 @@ import { getWatchdogSettings } from "./recovery.ts";
|
||||
|
||||
/** 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 } {
|
||||
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 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 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 };
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 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,
|
||||
// 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 { and, desc, eq, gt, gte, inArray, isNull, sql } from "drizzle-orm";
|
||||
import {
|
||||
@ -499,7 +500,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)? */
|
||||
export function inWorkingTime(now: Date, cfg: Pick<WatchdogSettings, "workFrom" | "workTo" | "workDays">): boolean {
|
||||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: process.env.PEPPA_TZ || undefined, weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
||||
const parts = new Intl.DateTimeFormat("en-GB", { timeZone: platformZone(), weekday: "short", hour: "numeric", hourCycle: "h23" }).formatToParts(now);
|
||||
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;
|
||||
return cfg.workDays.includes(day) && hour >= cfg.workFrom && hour < cfg.workTo;
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
// 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
|
||||
// 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 {
|
||||
expireSessionQuestions,
|
||||
@ -57,7 +58,7 @@ export async function planRotation(db: Db, s: SessionView, reason: RotateReason,
|
||||
return rotationCandidate(db, s, { now, onlyIdle: reason === "threshold" });
|
||||
}
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = platformTime;
|
||||
|
||||
/**
|
||||
* Relaunches the session on `target`: Claude Code and OpenCode continue the same
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// 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
|
||||
// comment stays where the developer agent reads it.
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import { m } from "@peppa/shared/i18n";
|
||||
import {
|
||||
addIntakeNote,
|
||||
@ -86,7 +87,16 @@ async function refine(db: Db, taskId: number, fresh: RefineComment[], log: (m: s
|
||||
}
|
||||
const note = out.ok ? parseAnalystNote(out.text) : null;
|
||||
if (!note) {
|
||||
const why = out.ok ? m("ответ не по форме") : /нет подписки/.test(out.error) ? m("у проекта не подключена подписка Claude — «⋯ Настройки проекта → Подписки»") : out.error.slice(0, 200);
|
||||
// PEP-304: subscriptions in a limit are not «no subscription» — say until when.
|
||||
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 }));
|
||||
log(`${ref.key}: story refine failed: ${why}`);
|
||||
return;
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// 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),
|
||||
// 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 {
|
||||
answerQuestion,
|
||||
@ -77,7 +78,7 @@ const requestKey = (projectId: number) => `${PREFIX}${projectId}`;
|
||||
const questionKey = (questionId: number) => `subscription.request.q:${questionId}`;
|
||||
const logKey = (userId: number) => `subscription.request.log:${userId}`;
|
||||
|
||||
const hhmm = (d: Date) => d.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const hhmm = platformTime;
|
||||
|
||||
export async function subscriptionRequest(db: Db, projectId: number): Promise<SubscriptionRequest | null> {
|
||||
return getSetting<SubscriptionRequest>(db, requestKey(projectId));
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
// 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.
|
||||
import { platformTime } from "@peppa/shared/time";
|
||||
import { asIs, m } from "@peppa/shared/i18n";
|
||||
import { runnerTick } from "./runners.ts";
|
||||
import { projectTrashTick } from "./project-trash.ts";
|
||||
@ -511,7 +512,7 @@ async function rotateLimited(db: Db, s: SessionView, now: Date, log: (m: string)
|
||||
if (s.rotateReason) {
|
||||
await updateSession(db, s.id, { rotateReason: null });
|
||||
await logSessionEvent(db, s, "rotation_skipped", { reason: "limit", why: m("нет свободной подписки") });
|
||||
const at = s.resumeAt!.toLocaleTimeString("ru-RU", { hour: "2-digit", minute: "2-digit", timeZone: process.env.PEPPA_TZ || undefined });
|
||||
const at = platformTime(s.resumeAt!);
|
||||
await limitDelay(db, s, m("{who}: лимит, свободных подписок нет — продолжит в {time} сам.", { who: s.taskKey ?? m("Агент №{id}", { id: s.id }), time: at }), { now, log });
|
||||
}
|
||||
return false;
|
||||
|
||||
@ -9,7 +9,8 @@
|
||||
"./i18n": "./src/i18n/index.ts",
|
||||
"./wording": "./src/wording.ts",
|
||||
"./glossary": "./src/glossary.ts",
|
||||
"./format": "./src/format.ts"
|
||||
"./format": "./src/format.ts",
|
||||
"./time": "./src/time.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc -p ."
|
||||
|
||||
@ -516,4 +516,12 @@ export const runner: Dict = {
|
||||
"Обновить и показать": "Update and show",
|
||||
"🗂 {project}: задач ждут вашей проверки больше недели — {n}. Их изменения расходятся с основной версией, принять их сейчас нельзя.": "🗂 {project}: tasks have been waiting for your check for over a week — {n}. Their changes diverge from the main version, so they cannot be accepted now.",
|
||||
"«Обновить и показать» — агент обновит изменения, и задачи снова придут к вам на проверку. «Закрыть» — задачи уйдут в архив, их изменения не попадут в продукт.": "«Update and show» — the agent updates the changes, and the tasks come back to you for checking. «Close» — the tasks go to the archive, their changes do not get into the product.",
|
||||
"{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.",
|
||||
};
|
||||
|
||||
@ -424,4 +424,12 @@ export const runner: Dict = {
|
||||
"Обновить и показать": "Жаңартып, көрсету",
|
||||
"🗂 {project}: задач ждут вашей проверки больше недели — {n}. Их изменения расходятся с основной версией, принять их сейчас нельзя.": "🗂 {project}: бір аптадан астам сіздің тексеруіңізді күтіп тұрған тапсырмалар — {n}. Олардың өзгерістері негізгі нұсқадан алшақ, оларды қазір қабылдау мүмкін емес.",
|
||||
"«Обновить и показать» — агент обновит изменения, и задачи снова придут к вам на проверку. «Закрыть» — задачи уйдут в архив, их изменения не попадут в продукт.": "«Жаңартып, көрсету» — агент өзгерістерді жаңартады, тапсырмалар сізге қайта тексеруге келеді. «Жабу» — тапсырмалар мұрағатқа кетеді, олардың өзгерістері өнімге түспейді.",
|
||||
"{who}: подписки проекта в лимите до {time}": "{who}: жоба жазылымдары {time} дейін лимитте",
|
||||
"{who}: подписки проекта в лимите": "{who}: жоба жазылымдары лимитте",
|
||||
"Аналитик разберёт задачу позже: подписки проекта в лимите до {time}. После этого разбор продолжится сам.": "Аналитик тапсырманы кейінірек талдайды: жоба жазылымдары {time} дейін лимитте. Одан кейін талдау өзі жалғасады.",
|
||||
"Аналитик разберёт задачу позже: подписки проекта в лимите. Когда лимит сбросится, разбор продолжится сам.": "Аналитик тапсырманы кейінірек талдайды: жоба жазылымдары лимитте. Лимит жаңарғанда талдау өзі жалғасады.",
|
||||
"подписки проекта в лимите до {time}": "жоба жазылымдары {time} дейін лимитте",
|
||||
"подписки проекта в лимите": "жоба жазылымдары лимитте",
|
||||
"Аналитик отвечает на подписке проекта, а она сейчас в лимите до {time}. Напишите ещё раз после этого времени.": "Аналитик жоба жазылымымен жауап береді, ал ол қазір {time} дейін лимитте. Осы уақыттан кейін қайта жазыңыз.",
|
||||
"Аналитик отвечает на подписке проекта, а она сейчас в лимите. Напишите ещё раз чуть позже.": "Аналитик жоба жазылымымен жауап береді, ал ол қазір лимитте. Сәл кейінірек қайта жазыңыз.",
|
||||
};
|
||||
|
||||
36
packages/shared/src/time.ts
Normal file
36
packages/shared/src/time.ts
Normal file
@ -0,0 +1,36 @@
|
||||
// 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));
|
||||
116
packages/testkit/test/limit-reason-time.test.ts
Normal file
116
packages/testkit/test/limit-reason-time.test.ts
Normal file
@ -0,0 +1,116 @@
|
||||
// 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$/);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user