From 020886eb1cb6d02fd9d7a67c35a99407a3ed9b76 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 22:55:49 +0000 Subject: [PATCH 1/2] =?UTF-8?q?PEP-304:=20=D0=BF=D0=BE=D0=B4=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D0=BA=D0=B8=20=D0=B2=20=D0=BB=D0=B8=D0=BC=D0=B8=D1=82?= =?UTF-8?q?=D0=B5=20=E2=80=94=20=D0=BD=D0=B5=20=C2=AB=D0=BD=D0=B5=D1=82=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=BF=D0=B8=D1=81=D0=BA=D0=B8=C2=BB;=20?= =?UTF-8?q?=D0=B2=D1=80=D0=B5=D0=BC=D1=8F=20=D0=BB=D1=8E=D0=B4=D1=8F=D0=BC?= =?UTF-8?q?=20=E2=80=94=20=D0=B2=20=D0=BF=D0=BE=D1=8F=D1=81=D0=B5=20=D0=BF?= =?UTF-8?q?=D0=BB=D0=B0=D1=82=D1=84=D0=BE=D1=80=D0=BC=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/web/app/(app)/errors/[id]/page.tsx | 7 +- .../web/app/(app)/observability/[id]/page.tsx | 3 +- apps/web/app/(app)/observability/page.tsx | 5 +- apps/web/app/(app)/p/[key]/page.tsx | 3 +- .../app/(app)/p/[key]/plan/[epic]/page.tsx | 3 +- apps/web/app/(app)/p/[key]/tabs.tsx | 3 +- apps/web/components/Accounting.tsx | 3 +- apps/web/components/Errors.tsx | 7 +- apps/web/components/Observability.tsx | 5 +- apps/web/components/PlatformDelays.tsx | 3 +- apps/web/components/PoolSubscriptions.tsx | 5 +- apps/web/components/cards.tsx | 3 +- .../design.md | 20 +++ .../proposal.md | 26 ++++ .../specs/analyst-voice/spec.md | 17 +++ .../specs/platform-time/spec.md | 14 +++ .../tasks.md | 13 ++ packages/core/src/chats.ts | 3 +- packages/core/src/intake.ts | 4 + packages/core/src/monitor.ts | 4 +- packages/core/src/observe.ts | 11 +- packages/core/src/onboarding.ts | 3 +- packages/core/src/platform-delay.ts | 3 +- packages/core/src/subscription-care.ts | 3 +- packages/core/src/subscriptions.ts | 16 +++ packages/core/src/usage.ts | 3 +- packages/runner/src/analyst-chat.ts | 11 +- packages/runner/src/claude-print.ts | 21 +++- packages/runner/src/intake.ts | 35 +++++- packages/runner/src/limit-delay.ts | 3 +- packages/runner/src/limits.ts | 3 +- packages/runner/src/pause.ts | 3 +- packages/runner/src/ready-digest.ts | 3 +- packages/runner/src/recovery.ts | 3 +- packages/runner/src/rotation.ts | 3 +- packages/runner/src/story-refine.ts | 12 +- packages/runner/src/subscription-request.ts | 3 +- packages/runner/src/watchdog.ts | 3 +- packages/shared/package.json | 3 +- packages/shared/src/i18n/en/runner.ts | 8 ++ packages/shared/src/i18n/kk/runner.ts | 8 ++ packages/shared/src/time.ts | 36 ++++++ .../testkit/test/limit-reason-time.test.ts | 116 ++++++++++++++++++ 43 files changed, 414 insertions(+), 50 deletions(-) create mode 100644 openspec/changes/pep-304-limit-reason-platform-time/design.md create mode 100644 openspec/changes/pep-304-limit-reason-platform-time/proposal.md create mode 100644 openspec/changes/pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md create mode 100644 openspec/changes/pep-304-limit-reason-platform-time/specs/platform-time/spec.md create mode 100644 openspec/changes/pep-304-limit-reason-platform-time/tasks.md create mode 100644 packages/shared/src/time.ts create mode 100644 packages/testkit/test/limit-reason-time.test.ts diff --git a/apps/web/app/(app)/errors/[id]/page.tsx b/apps/web/app/(app)/errors/[id]/page.tsx index f90a055f..c0a46475 100644 --- a/apps/web/app/(app)/errors/[id]/page.tsx +++ b/apps/web/app/(app)/errors/[id]/page.tsx @@ -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 {t.n(r.events, "{n} раз", "{n} раза", "{n} раз")} {d.users != null ? {t.n(d.users, "у {n} пользователя", "у {n} пользователей", "у {n} пользователей")} : null} - {t("впервые {ago}", { ago: ago(r.firstSeen, t) })} - {t("последний раз {ago}", { ago: ago(r.lastSeen, t) })} + {t("впервые {ago}", { ago: ago(r.firstSeen, t) })} + {t("последний раз {ago}", { ago: ago(r.lastSeen, t) })}
{r.taskKey ? ( @@ -109,7 +110,7 @@ export default async function ErrorPage({ params, searchParams }: { params: Prom
    {d.events.map((e) => (
  • - {e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium" })} + {e.at.toLocaleString(t.locale === "en" ? "en-GB" : "ru-RU", { dateStyle: "short", timeStyle: "medium", timeZone: platformZone() })} {e.id.slice(0, 8)}
  • ))} diff --git a/apps/web/app/(app)/observability/[id]/page.tsx b/apps/web/app/(app)/observability/[id]/page.tsx index c0f70dfd..0738fdf1 100644 --- a/apps/web/app/(app)/observability/[id]/page.tsx +++ b/apps/web/app/(app)/observability/[id]/page.tsx @@ -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(); diff --git a/apps/web/app/(app)/observability/page.tsx b/apps/web/app/(app)/observability/page.tsx index af674e8b..5389c706 100644 --- a/apps/web/app/(app)/observability/page.tsx +++ b/apps/web/app/(app)/observability/page.tsx @@ -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> }) { 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 (
    {flog.map((e) => (
  • - {new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })} + {new Date(e.at).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit", timeZone: platformZone() })} {e.state === "unavailable" ? t("отключена") : t("снова включена")} {t(FEATURES[e.name].label)} {e.reason && {e.reason}} diff --git a/apps/web/app/(app)/p/[key]/page.tsx b/apps/web/app/(app)/p/[key]/page.tsx index f3d7271c..05170a5e 100644 --- a/apps/web/app/(app)/p/[key]/page.tsx +++ b/apps/web/app/(app)/p/[key]/page.tsx @@ -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 ))} - {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() })} ))} diff --git a/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx b/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx index c67f6864..a6a0b5f0 100644 --- a/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx +++ b/apps/web/app/(app)/p/[key]/plan/[epic]/page.tsx @@ -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

    - {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 })}

    )} diff --git a/apps/web/app/(app)/p/[key]/tabs.tsx b/apps/web/app/(app)/p/[key]/tabs.tsx index ee216b82..8b447a5e 100644 --- a/apps/web/app/(app)/p/[key]/tabs.tsx +++ b/apps/web/app/(app)/p/[key]/tabs.tsx @@ -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(); diff --git a/apps/web/components/Accounting.tsx b/apps/web/components/Accounting.tsx index 7cd8d9d9..038fdbe2 100644 --- a/apps/web/components/Accounting.tsx +++ b/apps/web/components/Accounting.tsx @@ -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; } diff --git a/apps/web/components/Errors.tsx b/apps/web/components/Errors.tsx index 1dea4af3..23cfecef 100644 --- a/apps/web/components/Errors.tsx +++ b/apps/web/components/Errors.tsx @@ -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 = { unresolved: m("не решена"), resolved: m("решена"), muted: m("приглушена") }; const STATE_TONE: Record = { 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 ? {r.culprit} : null} {showProject ? {r.bugsinkName} : null} {t.n(r.events, "{n} раз", "{n} раза", "{n} раз")} - {t("впервые {ago}", { ago: ago(r.firstSeen, t) })} - {t("последний раз {ago}", { ago: ago(r.lastSeen, t) })} + {t("впервые {ago}", { ago: ago(r.firstSeen, t) })} + {t("последний раз {ago}", { ago: ago(r.lastSeen, t) })} {/* glossary-ignore: the release is shown to «Инженер» and the superadmin only */} {tech && r.release ? {t("релиз {sha}", { sha: r.release.slice(0, 8) })} : null} {r.taskKey ? {r.taskKey} : null} diff --git a/apps/web/components/Observability.tsx b/apps/web/components/Observability.tsx index 964d1a67..f583d02c 100644 --- a/apps/web/components/Observability.tsx +++ b/apps/web/components/Observability.tsx @@ -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 ))} {recent.map((c) => ( - + ))}
); @@ -125,4 +126,4 @@ export function OutageLine({ m, t, now = new Date() }: { m: MonitorView; t: Tran return {parts.join(" · ")}; } -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() }); diff --git a/apps/web/components/PlatformDelays.tsx b/apps/web/components/PlatformDelays.tsx index de076cec..fa7f1bb8 100644 --- a/apps/web/components/PlatformDelays.tsx +++ b/apps/web/components/PlatformDelays.tsx @@ -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 (
    {delays.map((d) => ( diff --git a/apps/web/components/PoolSubscriptions.tsx b/apps/web/components/PoolSubscriptions.tsx index 3ae6723d..f7a9eeef 100644 --- a/apps/web/components/PoolSubscriptions.tsx +++ b/apps/web/components/PoolSubscriptions.tsx @@ -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 = { 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 }) { {t("Переключения")} {o.switches.map((x, 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 ? {x.taskKey} : t("агент №{id}", { id: x.sessionId ?? "?" })} {": "} diff --git a/apps/web/components/cards.tsx b/apps/web/components/cards.tsx index 2c8ab1b7..53e1b742 100644 --- a/apps/web/components/cards.tsx +++ b/apps/web/components/cards.tsx @@ -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() }); diff --git a/openspec/changes/pep-304-limit-reason-platform-time/design.md b/openspec/changes/pep-304-limit-reason-platform-time/design.md new file mode 100644 index 00000000..17958b36 --- /dev/null +++ b/openspec/changes/pep-304-limit-reason-platform-time/design.md @@ -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}`. diff --git a/openspec/changes/pep-304-limit-reason-platform-time/proposal.md b/openspec/changes/pep-304-limit-reason-platform-time/proposal.md new file mode 100644 index 00000000..7bca98d2 --- /dev/null +++ b/openspec/changes/pep-304-limit-reason-platform-time/proposal.md @@ -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`. diff --git a/openspec/changes/pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md b/openspec/changes/pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md new file mode 100644 index 00000000..201ad2ad --- /dev/null +++ b/openspec/changes/pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md @@ -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** заметка «у проекта не подключена подписка» diff --git a/openspec/changes/pep-304-limit-reason-platform-time/specs/platform-time/spec.md b/openspec/changes/pep-304-limit-reason-platform-time/specs/platform-time/spec.md new file mode 100644 index 00000000..78e062f6 --- /dev/null +++ b/openspec/changes/pep-304-limit-reason-platform-time/specs/platform-time/spec.md @@ -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** сообщение отправляется со временем в поясе процесса diff --git a/openspec/changes/pep-304-limit-reason-platform-time/tasks.md b/openspec/changes/pep-304-limit-reason-platform-time/tasks.md new file mode 100644 index 00000000..12e0b37b --- /dev/null +++ b/openspec/changes/pep-304-limit-reason-platform-time/tasks.md @@ -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, тесты diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index b0166fc2..02da9790 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -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 { 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; } diff --git a/packages/core/src/intake.ts b/packages/core/src/intake.ts index b32dd596..6d8f7dd2 100644 --- a/packages/core/src/intake.ts +++ b/packages/core/src/intake.ts @@ -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}`; diff --git a/packages/core/src/monitor.ts b/packages/core/src/monitor.ts index ed3da5b1..99f133ee 100644 --- a/packages/core/src/monitor.ts +++ b/packages/core/src/monitor.ts @@ -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. diff --git a/packages/core/src/observe.ts b/packages/core/src/observe.ts index a2d4abed..c3a25893 100644 --- a/packages/core/src/observe.ts +++ b/packages/core/src/observe.ts @@ -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, inc: Pick, now = new Date()): string { diff --git a/packages/core/src/onboarding.ts b/packages/core/src/onboarding.ts index fd255650..820adf33 100644 --- a/packages/core/src/onboarding.ts +++ b/packages/core/src/onboarding.ts @@ -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(", ") }); } diff --git a/packages/core/src/platform-delay.ts b/packages/core/src/platform-delay.ts index cc5db392..d59eaf9d 100644 --- a/packages/core/src/platform-delay.ts +++ b/packages/core/src/platform-delay.ts @@ -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) diff --git a/packages/core/src/subscription-care.ts b/packages/core/src/subscription-care.ts index e0d2f799..68e90337 100644 --- a/packages/core/src/subscription-care.ts +++ b/packages/core/src/subscription-care.ts @@ -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 ──────────────────────────────────────────────────────────────────────── diff --git a/packages/core/src/subscriptions.ts b/packages/core/src/subscriptions.ts index 392e614a..0ba64ddd 100644 --- a/packages/core/src/subscriptions.ts +++ b/packages/core/src/subscriptions.ts @@ -414,6 +414,22 @@ export async function claudeTokenForProject(db: Db, project: Pick 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, 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 { const [row] = await db diff --git a/packages/core/src/usage.ts b/packages/core/src/usage.ts index 26b7e01a..bc55f616 100644 --- a/packages/core/src/usage.ts +++ b/packages/core/src/usage.ts @@ -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 { diff --git a/packages/runner/src/analyst-chat.ts b/packages/runner/src/analyst-chat.ts index 563075bf..3a1264e7 100644 --- a/packages/runner/src/analyst-chat.ts +++ b/packages/runner/src/analyst-chat.ts @@ -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; } diff --git a/packages/runner/src/claude-print.ts b/packages/runner/src/claude-print.ts index c56832f7..e89d7ba4 100644 --- a/packages/runner/src/claude-print.ts +++ b/packages/runner/src/claude-print.ts @@ -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, 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-")); diff --git a/packages/runner/src/intake.ts b/packages/runner/src/intake.ts index fcaa4eb7..b4e6a839 100644 --- a/packages/runner/src/intake.ts +++ b/packages/runner/src/intake.ts @@ -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 { @@ -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) { diff --git a/packages/runner/src/limit-delay.ts b/packages/runner/src/limit-delay.ts index c67021bc..39b83268 100644 --- a/packages/runner/src/limit-delay.ts +++ b/packages/runner/src/limit-delay.ts @@ -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], diff --git a/packages/runner/src/limits.ts b/packages/runner/src/limits.ts index 5c0b378e..de3c90c4 100644 --- a/packages/runner/src/limits.ts +++ b/packages/runner/src/limits.ts @@ -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 /** diff --git a/packages/runner/src/pause.ts b/packages/runner/src/pause.ts index 8b13fad2..8cff31bd 100644 --- a/packages/runner/src/pause.ts +++ b/packages/runner/src/pause.ts @@ -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 diff --git a/packages/runner/src/ready-digest.ts b/packages/runner/src/ready-digest.ts index 98311947..94167758 100644 --- a/packages/runner/src/ready-digest.ts +++ b/packages/runner/src/ready-digest.ts @@ -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 }; } diff --git a/packages/runner/src/recovery.ts b/packages/runner/src/recovery.ts index 2b240034..41233b9c 100644 --- a/packages/runner/src/recovery.ts +++ b/packages/runner/src/recovery.ts @@ -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 = { 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): 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; diff --git a/packages/runner/src/rotation.ts b/packages/runner/src/rotation.ts index 596d9195..dff3a670 100644 --- a/packages/runner/src/rotation.ts +++ b/packages/runner/src/rotation.ts @@ -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 diff --git a/packages/runner/src/story-refine.ts b/packages/runner/src/story-refine.ts index 7924a2d0..ba744129 100644 --- a/packages/runner/src/story-refine.ts +++ b/packages/runner/src/story-refine.ts @@ -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; diff --git a/packages/runner/src/subscription-request.ts b/packages/runner/src/subscription-request.ts index 18c81bbb..c9fe5ea4 100644 --- a/packages/runner/src/subscription-request.ts +++ b/packages/runner/src/subscription-request.ts @@ -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 { return getSetting(db, requestKey(projectId)); diff --git a/packages/runner/src/watchdog.ts b/packages/runner/src/watchdog.ts index 1ba6f548..0a28ee6b 100644 --- a/packages/runner/src/watchdog.ts +++ b/packages/runner/src/watchdog.ts @@ -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; diff --git a/packages/shared/package.json b/packages/shared/package.json index f4182b0d..49d50fb2 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -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 ." diff --git a/packages/shared/src/i18n/en/runner.ts b/packages/shared/src/i18n/en/runner.ts index 7639fd55..121ad568 100644 --- a/packages/shared/src/i18n/en/runner.ts +++ b/packages/shared/src/i18n/en/runner.ts @@ -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.", }; diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts index f5b4f893..9ce3e6c5 100644 --- a/packages/shared/src/i18n/kk/runner.ts +++ b/packages/shared/src/i18n/kk/runner.ts @@ -424,4 +424,12 @@ export const runner: Dict = { "Обновить и показать": "Жаңартып, көрсету", "🗂 {project}: задач ждут вашей проверки больше недели — {n}. Их изменения расходятся с основной версией, принять их сейчас нельзя.": "🗂 {project}: бір аптадан астам сіздің тексеруіңізді күтіп тұрған тапсырмалар — {n}. Олардың өзгерістері негізгі нұсқадан алшақ, оларды қазір қабылдау мүмкін емес.", "«Обновить и показать» — агент обновит изменения, и задачи снова придут к вам на проверку. «Закрыть» — задачи уйдут в архив, их изменения не попадут в продукт.": "«Жаңартып, көрсету» — агент өзгерістерді жаңартады, тапсырмалар сізге қайта тексеруге келеді. «Жабу» — тапсырмалар мұрағатқа кетеді, олардың өзгерістері өнімге түспейді.", + "{who}: подписки проекта в лимите до {time}": "{who}: жоба жазылымдары {time} дейін лимитте", + "{who}: подписки проекта в лимите": "{who}: жоба жазылымдары лимитте", + "Аналитик разберёт задачу позже: подписки проекта в лимите до {time}. После этого разбор продолжится сам.": "Аналитик тапсырманы кейінірек талдайды: жоба жазылымдары {time} дейін лимитте. Одан кейін талдау өзі жалғасады.", + "Аналитик разберёт задачу позже: подписки проекта в лимите. Когда лимит сбросится, разбор продолжится сам.": "Аналитик тапсырманы кейінірек талдайды: жоба жазылымдары лимитте. Лимит жаңарғанда талдау өзі жалғасады.", + "подписки проекта в лимите до {time}": "жоба жазылымдары {time} дейін лимитте", + "подписки проекта в лимите": "жоба жазылымдары лимитте", + "Аналитик отвечает на подписке проекта, а она сейчас в лимите до {time}. Напишите ещё раз после этого времени.": "Аналитик жоба жазылымымен жауап береді, ал ол қазір {time} дейін лимитте. Осы уақыттан кейін қайта жазыңыз.", + "Аналитик отвечает на подписке проекта, а она сейчас в лимите. Напишите ещё раз чуть позже.": "Аналитик жоба жазылымымен жауап береді, ал ол қазір лимитте. Сәл кейінірек қайта жазыңыз.", }; diff --git a/packages/shared/src/time.ts b/packages/shared/src/time.ts new file mode 100644 index 00000000..ec4961a3 --- /dev/null +++ b/packages/shared/src/time.ts @@ -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(); +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 = 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)); diff --git a/packages/testkit/test/limit-reason-time.test.ts b/packages/testkit/test/limit-reason-time.test.ts new file mode 100644 index 00000000..69c7f2a8 --- /dev/null +++ b/packages/testkit/test/limit-reason-time.test.ts @@ -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>; +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$/); + }); +}); From b52ccb46510d4fe3319f01e0ac36da4a27758de7 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Thu, 26 Nov 2026 22:56:21 +0000 Subject: [PATCH 2/2] =?UTF-8?q?PEP-304:=20=D0=B0=D1=80=D1=85=D0=B8=D0=B2?= =?UTF-8?q?=20change,=20=D0=BF=D0=B0=D0=BC=D1=8F=D1=82=D1=8C=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .peppa/memory.md | 8 +++----- .../design.md | 0 .../proposal.md | 0 .../specs/analyst-voice/spec.md | 0 .../specs/platform-time/spec.md | 0 .../tasks.md | 0 openspec/specs/analyst-voice/spec.md | 16 ++++++++++++++++ openspec/specs/platform-time/spec.md | 19 +++++++++++++++++++ 8 files changed, 38 insertions(+), 5 deletions(-) rename openspec/changes/{pep-304-limit-reason-platform-time => archive/2026-11-26-pep-304-limit-reason-platform-time}/design.md (100%) rename openspec/changes/{pep-304-limit-reason-platform-time => archive/2026-11-26-pep-304-limit-reason-platform-time}/proposal.md (100%) rename openspec/changes/{pep-304-limit-reason-platform-time => archive/2026-11-26-pep-304-limit-reason-platform-time}/specs/analyst-voice/spec.md (100%) rename openspec/changes/{pep-304-limit-reason-platform-time => archive/2026-11-26-pep-304-limit-reason-platform-time}/specs/platform-time/spec.md (100%) rename openspec/changes/{pep-304-limit-reason-platform-time => archive/2026-11-26-pep-304-limit-reason-platform-time}/tasks.md (100%) create mode 100644 openspec/specs/platform-time/spec.md diff --git a/.peppa/memory.md b/.peppa/memory.md index f8f59c81..5c78e245 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -18,14 +18,13 @@ - mock-gitea `POST /tags` ставит настоящий git-тег: нужны коммиты (`addRepo(…, { files })`) и существующий SHA (`gitea.sha(owner, repo, "main")`), иначе `deployProd`/`autoPublish` в тесте молча не срабатывают. Gitea «лежит» — `gitea.down = true`. - git-прокси релея (allowedGitPath) отклоняет %2e/%2f/%5c/%25 и `\`: fetch сворачивает %2e%2e как dot-сегмент. - Новая фраза Claude о лимите — в `parseResetTime` и limits.test.ts. Codex 0.169 без `--full-auto`: режим — `CODEX_DEFAULT_MODE` (providers.ts), срочно — `PEPPA_CODEX_MODE` в .env. -- Скорость: `apps/web/scripts/bench-pages.ts`, канал — `bench-live.ts`; правишь live.ts — перезапусти server.ts, не `pkill -f next-server`. +- Скорость: `apps/web/scripts/bench-pages.ts`/`bench-live.ts`; правишь live.ts — перезапусти server.ts. - observe.db: схема — `MIGRATIONS` по `user_version` (core/observe.ts); напоминания (PEP-223) — `remindIncidents`; в тестах «бот днём» помечай outbox `sent`, иначе напоминание заменит прежнее. - Хук грузит только лёгкий `runner/limit-delay.ts`, не flow.ts. В тесте хука PEPPA_GENERATION = поколение сессии (вставленной руками — 0). - Память ветки при мерже main склеивается построчно и разрастается дублями — после конфликта в `.peppa/memory.md` убери повторы (тест project-memory-size.test.ts). - SSRF-проверка в `lookup` — только с `agent: false` (keep-alive Node пропускает lookup, PEP-234). - QuickJS (PEP-212): строки из хост-функции читай до await; все хэндлы и deferred dispose-ить. - Настройки по префиксу — `keyPrefix(settings.key, "x:")` из @peppa/db, не `like(…"x:%")` (LIKE без индекса). Индексы — тест db-indexes. -- 530 при живом сервере — обрыв Mac → сервер (PEP-245); лечит только перенос адресов (ключ Cloudflare). - Продукт на другой docker — только `scripts/server-move/products-move.sh` (PEP-231, с данными); `peppa deploy redeploy` поднимает с пустыми томами. - Номер миграции занят соседом после мержа — взять meta из main, `pnpm db:generate`, переименовать. - Агент в контейнере не видит хост сервера, Mac и Cloudflare (PEP-231): инфраструктуру — скриптом в `scripts/server-move/` + шаги в docs/SERVER.md, выполнить просить суперадмина через `report_blocker`. @@ -34,7 +33,7 @@ - `stopSession` закрывает все вопросы сессии, и карточку «готово» с «Принять» — освобождать место без неё: `releaseReviewSession` (PEP-299). - Состояние вачдога, которое пишет не вачдог (хук, launch), — только `markWatch` (json_set): `patchWatch` перезаписывает весь watch_state (PEP-265). - Песочница раннера: нет tmux и Node 26 — `node-v26…-linux-x64.tar.gz` (не .xz) в /tmp; tmux — .deb (tmux_3.3a-3, libevent-core-2.1-7, libutempter0) → `dpkg-deb -x` + LD_LIBRARY_PATH. Падают и на main (среда): glossary-check.test, sandbox-hosts.test.ts (нет ssh). -- Сервер (PEP-230): docs/SERVER.md. Docker-клиент образа 20.10 (PEP-287). +- Сервер — docs/SERVER.md; docker-клиент образа 20.10. - Пропал `.git/worktrees/s`: создать с `HEAD`, `commondir` `../..`, `gitdir`, затем `git reset`. - Версии CLI агентов (PEP-267) — только `scripts/runner-image.sh --try <версия>` (json + оба Dockerfile), откат `--rollback`. - Codex (PEP-241): доверие папке — по корню основного репо worktree; `-c` режет ключ по точкам — пишем в config.toml CODEX_HOME (`codex-trust.ts`). @@ -44,6 +43,7 @@ - Очередь проверок (PEP-255): `checks.queue` — `projects` (своя зависшая голова) и `lanes` (`ciLane`); `requestRebase` → false = просьба не ушла. ## Соглашения +- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки». - «Готово» после выкатки (PEP-278): статус `done` не трогаем — поверх него отметка `rollout.wait:` (core/rollout.ts), экран — псевдостатус `rollout` в `TASK_STATUS`; снимает `rolloutTick`. - Специалисты (PEP-183): агент с непустым character — специалист; подбор — `runner/team-match.ts` (haiku, `PEPPA_TEAM_BIN`), результат `team.match:`, порог ожидания `platform.team.waitMin`; в `ensureSessionAgent` порядок: прежний → свободный специалист по профилю → универсал → специалист без очереди. - i18n (PEP-98): текст пользователю — ключ = русская строка в `t()`/`m()` + перевод в `i18n/en|kk/<раздел>.ts` (иначе падают i18n-check/i18n-kk). «Peppa FACTORY» не склоняется (kk: Peppa FACTORY-нің); к {плейсхолдеру} kk-окончание не клеить. Тексты агентам говорят «Пеппа» — не трогаем. @@ -71,6 +71,4 @@ - Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`. - `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect [--secrets-only]`. - Живой сайт (с PEP-230 — сервер, контейнеры) — только `scripts/platform-deploy.sh` из `~/peppa/src` на main (docs/SERVER.md); launchd/live-deploy.sh — только откат на Mac. -- Речь — свой faster-whisper (``). Google: по почте учётки не склеиваем. - Секреты (PEP-253): агенту — `agent_env` при `project.agent-secrets` (нет строки = вкл.); в тестах — `{ agent: true }`. -- Привязка Google к чужой Google-only учётке — `mergeUserInto`; с eGov/Gitea — отказ (PEP-195). diff --git a/openspec/changes/pep-304-limit-reason-platform-time/design.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/design.md similarity index 100% rename from openspec/changes/pep-304-limit-reason-platform-time/design.md rename to openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/design.md diff --git a/openspec/changes/pep-304-limit-reason-platform-time/proposal.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/proposal.md similarity index 100% rename from openspec/changes/pep-304-limit-reason-platform-time/proposal.md rename to openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/proposal.md diff --git a/openspec/changes/pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md similarity index 100% rename from openspec/changes/pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md rename to openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/specs/analyst-voice/spec.md diff --git a/openspec/changes/pep-304-limit-reason-platform-time/specs/platform-time/spec.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/specs/platform-time/spec.md similarity index 100% rename from openspec/changes/pep-304-limit-reason-platform-time/specs/platform-time/spec.md rename to openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/specs/platform-time/spec.md diff --git a/openspec/changes/pep-304-limit-reason-platform-time/tasks.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/tasks.md similarity index 100% rename from openspec/changes/pep-304-limit-reason-platform-time/tasks.md rename to openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/tasks.md diff --git a/openspec/specs/analyst-voice/spec.md b/openspec/specs/analyst-voice/spec.md index 9c140ecc..f9cebde4 100644 --- a/openspec/specs/analyst-voice/spec.md +++ b/openspec/specs/analyst-voice/spec.md @@ -103,3 +103,19 @@ TBD - created by archiving change pep-198-one-analyst. Update Purpose after arch - **WHEN** вачдог проверяет задачи - **THEN** суперадмин получает сообщение о 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** заметка «у проекта не подключена подписка» diff --git a/openspec/specs/platform-time/spec.md b/openspec/specs/platform-time/spec.md new file mode 100644 index 00000000..16a3c605 --- /dev/null +++ b/openspec/specs/platform-time/spec.md @@ -0,0 +1,19 @@ +# 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** сообщение отправляется со временем в поясе процесса