diff --git a/.peppa/memory/pep-304.md b/.peppa/memory/pep-304.md
new file mode 100644
index 00000000..08a40330
--- /dev/null
+++ b/.peppa/memory/pep-304.md
@@ -0,0 +1,4 @@
+# Память: PEP-304
+
+## Соглашения
+- Время людям (PEP-304) — только `platformTime`/`platformDayTime`/`platformZone` из `@peppa/shared/time`; `toLocale*String` для дат без `timeZone` не писать. Лимит в `claudePrint` — `limited`/`limitedUntil`, не «нет подписки».
diff --git a/apps/web/app/(app)/connections/requests/[id]/page.tsx b/apps/web/app/(app)/connections/requests/[id]/page.tsx
index 508b5b1a..b32dfd22 100644
--- a/apps/web/app/(app)/connections/requests/[id]/page.tsx
+++ b/apps/web/app/(app)/connections/requests/[id]/page.tsx
@@ -1,4 +1,4 @@
-import Link from "next/link";
+import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { ExternalLink, KeyRound } from "lucide-react";
import { accessRequestForUser, catalogService, connectionsForRequest, type AccessRequestView, type CatalogService, type ConnectionView } from "@peppa/core";
diff --git a/apps/web/app/(app)/dashboard/questions/page.tsx b/apps/web/app/(app)/dashboard/questions/page.tsx
index 6bf0f155..12723d9b 100644
--- a/apps/web/app/(app)/dashboard/questions/page.tsx
+++ b/apps/web/app/(app)/dashboard/questions/page.tsx
@@ -1,4 +1,4 @@
-import Link from "next/link";
+import Link from "@/components/Link";
import { notFound } from "next/navigation";
import { MessageCircleQuestion } from "lucide-react";
import { isSuperadmin } from "@peppa/core";
diff --git a/apps/web/app/(app)/errors/[id]/page.tsx b/apps/web/app/(app)/errors/[id]/page.tsx
index f9e50f84..070cdbc5 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 "@/components/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) })}
))}
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 32c78b61..0d90aef2 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 "@/components/Link";
import { notFound } from "next/navigation";
import { Sparkles } from "lucide-react";
@@ -109,7 +110,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 5ad427ad..f7d4afa4 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/AccessRequests.tsx b/apps/web/components/AccessRequests.tsx
index 42a4b817..5f81261a 100644
--- a/apps/web/components/AccessRequests.tsx
+++ b/apps/web/components/AccessRequests.tsx
@@ -1,4 +1,4 @@
-import Link from "next/link";
+import Link from "@/components/Link";
import { KeyRound } from "lucide-react";
import type { AccessRequestView } from "@peppa/core";
import type { Translator } from "@peppa/shared/i18n";
diff --git a/apps/web/components/Accounting.tsx b/apps/web/components/Accounting.tsx
index 1331895b..eb87a01e 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 "@/components/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 72b33a71..6493c2dd 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 "@/components/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 7235aef8..3c0697cc 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 "@/components/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 0a7dcafd..ac19e1ac 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 "@/components/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 5f65a77e..3cb2ada2 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 "@/components/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/archive/2026-11-26-pep-304-limit-reason-platform-time/design.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/design.md
new file mode 100644
index 00000000..17958b36
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-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/archive/2026-11-26-pep-304-limit-reason-platform-time/proposal.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/proposal.md
new file mode 100644
index 00000000..7bca98d2
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-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/archive/2026-11-26-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
new file mode 100644
index 00000000..201ad2ad
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-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/archive/2026-11-26-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
new file mode 100644
index 00000000..78e062f6
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-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/archive/2026-11-26-pep-304-limit-reason-platform-time/tasks.md b/openspec/changes/archive/2026-11-26-pep-304-limit-reason-platform-time/tasks.md
new file mode 100644
index 00000000..12e0b37b
--- /dev/null
+++ b/openspec/changes/archive/2026-11-26-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/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** сообщение отправляется со временем в поясе процесса
diff --git a/openspec/specs/web-auth/spec.md b/openspec/specs/web-auth/spec.md
index e1741127..79d7c7ca 100644
--- a/openspec/specs/web-auth/spec.md
+++ b/openspec/specs/web-auth/spec.md
@@ -287,6 +287,6 @@ nonce, созданные сервером для этого потока; по
| адрес | показ |
|---|---|
-| http://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 |
-| https://git.telecom.quest/avatars/1 | https://git.telecom.quest/avatars/1 |
+| http://git.vibe42.kz/avatars/1 | https://git.vibe42.kz/avatars/1 |
+| https://git.vibe42.kz/avatars/1 | https://git.vibe42.kz/avatars/1 |
| javascript:alert(1) | нет картинки |
diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts
index 2821f101..0e177187 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 94845005..5d6ff4f2 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";
@@ -301,7 +302,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 8517f6a4..773cf6ed 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";
@@ -261,6 +262,9 @@ export function observeDb(): DatabaseSync {
}
/** Tests: forget opened files. */
+/** Index of the migration whose SQL mentions `needle` (the `user_version` right before it); -1 — none. For tests that put a file back before one migration. */
+export const observeMigrationIndex = (needle: string): number => MIGRATIONS.findIndex((m) => m.some((sql) => sql.includes(needle)));
+
export function closeObserveDb(): void {
for (const db of opened.values()) db.close();
opened.clear();
@@ -662,14 +666,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 a7357057..0fb7319f 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";
@@ -121,7 +122,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 196fea12..b4131fe2 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,
@@ -58,7 +59,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 fa162282..46da53d9 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 a4a36bf6..d2d82508 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";
@@ -522,7 +523,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 3069027e..4ee21645 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 876ca568..ca6d8a27 100644
--- a/packages/shared/src/i18n/en/runner.ts
+++ b/packages/shared/src/i18n/en/runner.ts
@@ -543,4 +543,12 @@ export const runner: Dict = {
"Откройте Главную: там всё по порядку — посмотреть, принять или поправить.": "Open the Home page: everything is there in order — look, accept or ask for changes.",
"Открыть Главную": "Open Home",
"Задач: {n}": "Tasks: {n}",
+ "{who}: подписки проекта в лимите до {time}": "{who}: the project's subscriptions are in a usage limit until {time}",
+ "{who}: подписки проекта в лимите": "{who}: the project's subscriptions are in a usage limit",
+ "Аналитик разберёт задачу позже: подписки проекта в лимите до {time}. После этого разбор продолжится сам.": "The analyst will go through the task later: the project's subscriptions are in a usage limit until {time}. After that the review continues by itself.",
+ "Аналитик разберёт задачу позже: подписки проекта в лимите. Когда лимит сбросится, разбор продолжится сам.": "The analyst will go through the task later: the project's subscriptions are in a usage limit. When the limit resets, the review continues by itself.",
+ "подписки проекта в лимите до {time}": "the project's subscriptions are in a usage limit until {time}",
+ "подписки проекта в лимите": "the project's subscriptions are in a usage limit",
+ "Аналитик отвечает на подписке проекта, а она сейчас в лимите до {time}. Напишите ещё раз после этого времени.": "The analyst answers on the project's subscription, and it is in a usage limit until {time}. Please write again after that time.",
+ "Аналитик отвечает на подписке проекта, а она сейчас в лимите. Напишите ещё раз чуть позже.": "The analyst answers on the project's subscription, and it is in a usage limit right now. Please write again a little later.",
};
diff --git a/packages/shared/src/i18n/kk/runner.ts b/packages/shared/src/i18n/kk/runner.ts
index ca769ca4..f3b091e6 100644
--- a/packages/shared/src/i18n/kk/runner.ts
+++ b/packages/shared/src/i18n/kk/runner.ts
@@ -451,4 +451,12 @@ export const runner: Dict = {
"Откройте Главную: там всё по порядку — посмотреть, принять или поправить.": "Басты бетті ашыңыз: бәрі ретімен — қарау, қабылдау немесе түзету.",
"Открыть Главную": "Басты бетті ашу",
"Задач: {n}": "Тапсырмалар: {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/health-anon.test.ts b/packages/testkit/test/health-anon.test.ts
index 03694a0c..05d74a68 100644
--- a/packages/testkit/test/health-anon.test.ts
+++ b/packages/testkit/test/health-anon.test.ts
@@ -88,8 +88,8 @@ describe("PEP-272: ответы веба не раскрывают служеб
});
for (const [url, shown] of [
- ["http://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"],
- ["https://git.telecom.quest/avatars/1", "https://git.telecom.quest/avatars/1"],
+ ["http://git.vibe42.kz/avatars/1", "https://git.vibe42.kz/avatars/1"],
+ ["https://git.vibe42.kz/avatars/1", "https://git.vibe42.kz/avatars/1"],
["javascript:alert(1)", null],
["", null],
] as const) {
@@ -99,7 +99,7 @@ describe("PEP-272: ответы веба не раскрывают служеб
}
test("Аватар Gitea по http сохраняется как https", async () => {
- const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.telecom.quest/avatars/7" }, { access_token: "x" });
- assert.equal(u.avatarUrl, "https://git.telecom.quest/avatars/7");
+ const u = await core.upsertUserFromGitea(db, { id: 72001, login: "mock-avatar", avatar_url: "http://git.vibe42.kz/avatars/7" }, { access_token: "x" });
+ assert.equal(u.avatarUrl, "https://git.vibe42.kz/avatars/7");
});
});
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$/);
+ });
+});
diff --git a/packages/testkit/test/old-git-cleanup.test.ts b/packages/testkit/test/old-git-cleanup.test.ts
index 70899e5a..1dedf161 100644
--- a/packages/testkit/test/old-git-cleanup.test.ts
+++ b/packages/testkit/test/old-git-cleanup.test.ts
@@ -72,7 +72,8 @@ function oldMonitor(hosts: string[]): number {
VALUES ('Интернет', 'internet', ?, 60, 5000, 3, 2, 'system', ?, ?, ?) RETURNING id`,
)
.get(JSON.stringify({ hosts }), iso, iso, iso) as { id: number };
- raw.exec("PRAGMA user_version = 3");
+ // The version right before the PEP-281 migration — other migrations (PEP-217: web_vitals) stay applied.
+ raw.exec(`PRAGMA user_version = ${core.observeMigrationIndex(OLD_HOST)}`);
raw.close();
return row.id;
}