Merge pull request 'PEP-36 этап 1: Node 26 со снятием типов вместо tsx' (#28) from task/PEP-36-node into main

This commit is contained in:
peppa-bot 2026-11-13 16:55:38 +05:00
commit 843b0778d8
33 changed files with 124 additions and 63 deletions

View File

@ -56,7 +56,7 @@
- `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы - `peppa status` — сервисы (heartbeat), outbox, раннеры, вопросы, админы
- `peppa web login-link <login>` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea - `peppa web login-link <login>` — одноразовый вход в веб (10 мин) для проверки без пароля Gitea; `mock-pm` — тестовый пользователь без доступа к Gitea
- `pnpm typecheck` - `pnpm typecheck`
- `tsx packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера - `node packages/mcp/scripts/smoke.ts <project-dir> <task>` — смоук MCP-сервера
- `pnpm dev:web` - `pnpm dev:web`
- `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>` - `peppa session start PEP-42` / `peppa session list` / `peppa session attach <id>` / `peppa q answer <id> <text>`
- Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log` - Логи: `~/.peppa/hook.log`, `~/.peppa/watchdog.log`
@ -65,7 +65,7 @@
- **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up` - **Dev-стенд** (`peppa-dev`, PEP-6) — проверять сценарии с PM самому, без человека и боевых данных: БД `peppa_dev`, tmux `-L peppa-dev`, `~/.peppa-dev`, бот против `mock-telegram` (:3190), агенты — моки. `peppa-dev up` (поднимает и привязывает тестового PM), `peppa-dev peppa <cli…>`, `peppa-dev tg messages|click <msg> <кнопка>|reply <msg> <текст>|send <текст>`, `peppa-dev down`. Живой агент на стенде: `PEPPA_DEV_CLAUDE_BIN=claude peppa-dev up`
- Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу - Ручной прогон с моком: `PEPPA_CLAUDE_BIN=packages/testkit/bin/mock-claude peppa session start 1`; сценарий в `<workspace>/.peppa/mock-scenario.json`, лог в `.peppa/mock-log.jsonl`; промпт `!{"limit":true}` выполняет действие сразу
TypeScript запускается через tsx / Next без сборки; импорты внутри пакетов — с расширением `.ts`. TypeScript запускается прямо из исходников: `node` (Node ≥ 26, встроенное снятие типов; bin-обёртки проверяют версию через `scripts/lib/require-node.mjs`) и Next без сборки. Только стираемый синтаксис (`erasableSyntaxOnly`: без parameter properties, `enum`, `namespace`), импорты типов — `import type`, импорты внутри пакетов — с расширением `.ts`.
## Автономный режим (PEP-7) ## Автономный режим (PEP-7)
PM двигает карточки на доске (веб, `/p/<KEY>`): «В работе» запускает агента (`moveTask`), PM двигает карточки на доске (веб, `/p/<KEY>`): «В работе» запускает агента (`moveTask`),
@ -82,4 +82,4 @@ PM двигает карточки на доске (веб, `/p/<KEY>`): «В р
(`template/RULES.md`, MCP `get_rules`): proposal → `request_approval` → одобрение PM → (`template/RULES.md`, MCP `get_rules`): proposal → `request_approval` → одобрение PM →
apply → archive → PR/коммит. Работу вне задачи не делаем; новое — `create_task`. apply → archive → PR/коммит. Работу вне задачи не делаем; новое — `create_task`.
Вызов MCP-инструмента из shell (для этой сессии без tmux): Вызов MCP-инструмента из shell (для этой сессии без tmux):
`tsx packages/mcp/scripts/call.ts <tool> '<json>'`. `node packages/mcp/scripts/call.ts <tool> '<json>'`.

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash #!/usr/bin/env bash
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
. "$PEPPA_ROOT/scripts/lib/load-env.sh" . "$PEPPA_ROOT/scripts/lib/load-env.sh"
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/apps/bot/src/index.ts" "$@"

View File

@ -5,7 +5,7 @@
"type": "module", "type": "module",
"exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" }, "exports": { ".": "./src/bot.ts", "./telegram": "./src/telegram.ts" },
"bin": { "peppa-bot": "./bin/peppa-bot" }, "bin": { "peppa-bot": "./bin/peppa-bot" },
"scripts": { "start": "tsx src/index.ts", "typecheck": "tsc -p ." }, "scripts": { "start": "node src/index.ts", "typecheck": "tsc -p ." },
"dependencies": { "dependencies": {
"@peppa/core": "workspace:*", "@peppa/core": "workspace:*",
"@peppa/db": "workspace:*", "@peppa/db": "workspace:*",

View File

@ -31,21 +31,26 @@ export interface InlineButton {
} }
export class TelegramError extends Error { export class TelegramError extends Error {
constructor( readonly method: string;
readonly method: string, readonly code: number;
readonly code: number, readonly description: string;
readonly description: string, readonly retryAfter?: number;
readonly retryAfter?: number, constructor(method: string, code: number, description: string, retryAfter?: number) {
) {
super(`${method}: ${code} ${description}`); super(`${method}: ${code} ${description}`);
this.method = method;
this.code = code;
this.description = description;
this.retryAfter = retryAfter;
} }
} }
export class TelegramApi { export class TelegramApi {
constructor( private readonly token: string;
private readonly token: string, private readonly baseUrl: string;
private readonly baseUrl = "https://api.telegram.org", constructor(token: string, baseUrl = "https://api.telegram.org") {
) {} this.token = token;
this.baseUrl = baseUrl;
}
async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> { async call<T>(method: string, params: Record<string, unknown> = {}, timeoutMs = 15_000): Promise<T> {
let res: Response; let res: Response;

View File

@ -1,7 +1,7 @@
// Demo data for checking the web UI by eye (PEP-38): a user, two projects, goals, tasks on every board // Demo data for checking the web UI by eye (PEP-38): a user, two projects, goals, tasks on every board
// column, runners in every status (one hit the usage limit and resumes later), open questions, releases. // column, runners in every status (one hit the usage limit and resumes later), open questions, releases.
// Only for a throwaway database — refuses the production one: // Only for a throwaway database — refuses the production one:
// DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui tsx apps/web/scripts/mock-ui-seed.ts [login] // DATABASE_URL=postgres://peppa:peppa@127.0.0.1:5433/peppa_ui node apps/web/scripts/mock-ui-seed.ts [login]
import { mkdirSync, writeFileSync } from "node:fs"; import { mkdirSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";

View File

@ -138,8 +138,12 @@ PM выбрал Node 26 со встроенным снятием типов и `
- **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert, - **Через drizzle** (`schema-port/drizzle-check.ts`, транзакция хука update + insert,
20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс. 20 000 подряд в одном процессе): `node:sqlite` 53 мкс, `bun:sqlite` 63 мкс.
- **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против - **Старт процесса** хуже, чем у Bun: процесс бенчмарка стартует за 70–97 мс против
16–32 мс; но против tsx (0,44 с) это всё равно в 4–6 раз быстрее. Реальный старт 16–32 мс. Реальный `peppa-hook` на Node 26 без tsx (этап 1): **0,31 с против 0,44 с у
`peppa-hook` на Node без tsx замеряется в этапе 1. tsx** (Bun — 0,04 с). Почти всё время — загрузка drizzle-orm: `drizzle-orm` ~105 мс +
`pg-core` ~90 мс (сотни мелких ESM-файлов; `NODE_COMPILE_CACHE` даёт лишь ~0,03 с),
`postgres` — 10 мс, свой код — ~40 мс. С `sqlite-core` вместо `pg-core` картина та же
(~75 мс). Если 0,3 с на хук окажется заметным, в этапе 2 хук пишет через `node:sqlite`
напрямую (две-три команды SQL, без drizzle) — оценка ~0,1 с.
- `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего - `node:sqlite` в Node 26 — без предупреждения ExperimentalWarning, в stderr хуков ничего
лишнего. лишнего.
@ -157,6 +161,16 @@ better-sqlite3 под Node 26 собирается из исходников (г
атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется атомарности, как у `bun-sqlite`). При переходе на drizzle 1.0 прослойка заменяется
штатным `drizzle-orm/node-sqlite`. штатным `drizzle-orm/node-sqlite`.
### Этап 1: найденная гонка «промпт закрывает чужой вопрос»
С быстрым стартом хука на Node e2e `ci-feedback` («Три неудачи подряд») стал падать в
3 из 5 прогонов (на tsx — 0 из 5). Причина в коде, не в тесте: хук `UserPromptSubmit`
закрывал **все** открытые вопросы сессии ответом «из терминала», в том числе вопрос PM,
созданный уже после того, как Пеппа сама вставила текст (отчёт о красном CI) в терминал.
Исправлено: `sendToSession` пишет событие `input_sent` с текстом до ввода, хук, узнав
этот текст в промпте, закрывает только вопросы, созданные раньше ввода; текст,
набранный человеком, закрывает всё, как раньше. После правки — 6 из 6.
### Схема и данные на SQLite (`bench/sqlite/schema-port`) ### Схема и данные на SQLite (`bench/sqlite/schema-port`)
- Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`, - Схема переводится механически (скрипт в прототипе): `pgTable` → `sqliteTable`,

View File

@ -13,11 +13,11 @@
## 1. Этап 1 — Node 26 без tsx (без смены БД) ## 1. Этап 1 — Node 26 без tsx (без смены БД)
- [ ] 1.1 `erasableSyntaxOnly` в `tsconfig.base.json`; переписать parameter properties, `enum` и прочее, что Node не может очистить от типов; `typecheck` зелёный - [x] 1.1 `erasableSyntaxOnly` + `verbatimModuleSyntax` в `tsconfig.base.json`; parameter properties переписаны (BugsinkError, GiteaError, GiteaClient, OAuthError, TelegramError, TelegramApi, MockGitea); `typecheck` зелёный
- [ ] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx`; проверка версии Node (≥ 26) с понятной ошибкой - [x] 1.2 Bin-обёртки `packages/*/bin/*`, `apps/bot/bin/*`, моки testkit: `node` вместо `tsx` (`PEPPA_NODE` переопределяет); проверка версии Node ≥ 26 — `scripts/lib/require-node.mjs` через `node --import`
- [ ] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`.gitea/workflows/ci.yml`, `scripts/ci.sh`); `tsx` убрать из зависимостей - [x] 1.3 Скрипты `package.json` и тесты: `node --test` вместо `tsx --test`; CI (`ci.yml` уже ставит Node 26, `ci.sh` вызывает скрипт пакета — правок не потребовали); `tsx` убран из зависимостей
- [ ] 1.4 `scripts/install-launchd.sh` — без tsx; на машине не перевыкатывать (деплой — PM), в PR перечислить, что перевыкатить - [x] 1.4 `scripts/install-launchd.sh`: плисты и так вызывают bin-обёртки; добавлен закреплённый `PEPPA_NODE` (абсолютный путь, проверка версии при установке); на машине не перевыкатывал — список в PR
- [ ] 1.5 Весь e2e на своей `PEPPA_TEST_DB`; замер старта `peppa-hook` (цель < 300 мс) - [x] 1.5 Весь e2e на своей `PEPPA_TEST_DB` (`node --test`); старт `peppa-hook` 0,31 с (tsx 0,44 с) — см. design; гонка «промпт закрывает чужой вопрос» найдена и исправлена (`input_sent`)
## 2. Этап 2 — SQLite вместо Postgres ## 2. Этап 2 — SQLite вместо Postgres

View File

@ -15,7 +15,6 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "26.6.6", "@types/node": "26.6.6",
"tsx": "4.23.15",
"typescript": "6.0.3" "typescript": "6.0.3"
} }
} }

View File

@ -129,11 +129,10 @@ export function parseWebhook(body: unknown): BugsinkIssueJson | null {
} }
export class BugsinkError extends Error { export class BugsinkError extends Error {
constructor( readonly status?: number;
message: string, constructor(message: string, status?: number) {
readonly status?: number,
) {
super(message); super(message);
this.status = status;
} }
} }

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash #!/usr/bin/env bash
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
. "$PEPPA_ROOT/scripts/lib/load-env.sh" . "$PEPPA_ROOT/scripts/lib/load-env.sh"
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/cli/src/index.ts" "$@"

View File

@ -7,7 +7,7 @@
"peppa": "./bin/peppa" "peppa": "./bin/peppa"
}, },
"scripts": { "scripts": {
"start": "tsx src/index.ts", "start": "node src/index.ts",
"typecheck": "tsc -p ." "typecheck": "tsc -p ."
}, },
"dependencies": { "dependencies": {

View File

@ -62,19 +62,20 @@ export interface OAuthTokens {
} }
export class GiteaError extends PeppaError { export class GiteaError extends PeppaError {
constructor( readonly status: number;
readonly status: number, constructor(status: number, message: string) {
message: string,
) {
super(message); super(message);
this.status = status;
} }
} }
export class GiteaClient { export class GiteaClient {
constructor( readonly baseUrl: string;
readonly baseUrl: string, private readonly token: string;
private readonly token: string, constructor(baseUrl: string, token: string) {
) {} this.baseUrl = baseUrl;
this.token = token;
}
async request<T>(method: string, path: string, body?: unknown): Promise<T> { async request<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await fetch(`${this.baseUrl}/api/v1${path}`, { const res = await fetch(`${this.baseUrl}/api/v1${path}`, {

View File

@ -12,12 +12,13 @@ export const ACCESS_TTL_SEC = 3600;
const REFRESH_TTL_SEC = 30 * 86400; const REFRESH_TTL_SEC = 30 * 86400;
const CODE_TTL_MS = 10 * 60_000; const CODE_TTL_MS = 10 * 60_000;
type OAuthErrorCode = "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied";
export class OAuthError extends PeppaError { export class OAuthError extends PeppaError {
constructor( readonly error: OAuthErrorCode;
readonly error: "invalid_request" | "invalid_client" | "invalid_grant" | "unsupported_grant_type" | "invalid_redirect_uri" | "access_denied", constructor(error: OAuthErrorCode, description: string) {
description: string,
) {
super(description); super(description);
this.error = error;
} }
} }

View File

@ -1,6 +1,6 @@
import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db"; import { events, projects, questions, sessions, sessionStatus, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared"; import { formatTaskKey } from "@peppa/shared";
import { and, desc, eq, inArray, isNull, notInArray } from "drizzle-orm"; import { and, desc, eq, inArray, isNull, lte, notInArray } from "drizzle-orm";
import { PeppaError } from "./errors.ts"; import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts"; import { notify } from "./notify.ts";
import type { Question, QuestionKind } from "./tasks.ts"; import type { Question, QuestionKind } from "./tasks.ts";
@ -89,7 +89,7 @@ export async function logSessionEvent(db: Db, s: Session, type: string, payload?
export async function pendingSessionQuestions( export async function pendingSessionQuestions(
db: Db, db: Db,
sessionId: number, sessionId: number,
opts: { excludeHook?: boolean } = {}, opts: { excludeHook?: boolean; createdBefore?: Date } = {},
): Promise<Question[]> { ): Promise<Question[]> {
return db return db
.select() .select()
@ -99,10 +99,28 @@ export async function pendingSessionQuestions(
eq(questions.sessionId, sessionId), eq(questions.sessionId, sessionId),
isNull(questions.answeredAt), isNull(questions.answeredAt),
opts.excludeHook ? eq(questions.awaitingHook, false) : undefined, opts.excludeHook ? eq(questions.awaitingHook, false) : undefined,
opts.createdBefore ? lte(questions.createdAt, opts.createdBefore) : undefined,
), ),
); );
} }
const sameText = (a: string, b: string) => a.replace(/\s+/g, " ").trim() === b.replace(/\s+/g, " ").trim();
/**
* When Peppa itself typed `prompt` into the session's terminal (an `input_sent` event),
* the time it did so; null if the prompt came from a person.
*/
export async function peppaInputSentAt(db: Db, sessionId: number, prompt: string): Promise<Date | null> {
const sent = await db
.select()
.from(events)
.where(and(eq(events.sessionId, sessionId), eq(events.type, "input_sent")))
.orderBy(desc(events.id))
.limit(10);
const hit = sent.find((e) => sameText(String((e.payload as { text?: string } | null)?.text ?? ""), prompt));
return hit?.createdAt ?? null;
}
export async function getQuestion(db: Db, id: number): Promise<Question> { export async function getQuestion(db: Db, id: number): Promise<Question> {
const [row] = await db.select().from(questions).where(eq(questions.id, id)); const [row] = await db.select().from(questions).where(eq(questions.id, id));
if (!row) throw new PeppaError(`Question #${id} not found`); if (!row) throw new PeppaError(`Question #${id} not found`);

View File

@ -2,4 +2,4 @@
# Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves. # Launches the Peppa MCP server; keeps the caller's cwd so .peppa/project.json resolves.
PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
. "$PEPPA_ROOT/scripts/lib/load-env.sh" . "$PEPPA_ROOT/scripts/lib/load-env.sh"
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/mcp/src/index.ts" "$@"

View File

@ -7,7 +7,7 @@
"peppa-mcp": "./bin/peppa-mcp" "peppa-mcp": "./bin/peppa-mcp"
}, },
"scripts": { "scripts": {
"start": "tsx src/index.ts", "start": "node src/index.ts",
"typecheck": "tsc -p ." "typecheck": "tsc -p ."
}, },
"dependencies": { "dependencies": {

View File

@ -1,5 +1,5 @@
// Calls one peppa MCP tool from the current directory, as an agent would. // Calls one peppa MCP tool from the current directory, as an agent would.
// Usage: tsx packages/mcp/scripts/call.ts <tool> '<json args>' // Usage: node packages/mcp/scripts/call.ts <tool> '<json args>'
import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";

View File

@ -1,5 +1,5 @@
// Smoke test: spawns peppa-mcp in the given project dir and calls a few tools. // Smoke test: spawns peppa-mcp in the given project dir and calls a few tools.
// Usage: tsx packages/mcp/scripts/smoke.ts <project-dir> <task> // Usage: node packages/mcp/scripts/smoke.ts <project-dir> <task>
import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";

View File

@ -4,4 +4,4 @@ PEPPA_ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
[ -z "${PEPPA_SESSION_ID:-}" ] && { [ "${1:-}" = codex-notify ] || cat >/dev/null; exit 0; } [ -z "${PEPPA_SESSION_ID:-}" ] && { [ "${1:-}" = codex-notify ] || cat >/dev/null; exit 0; }
. "$PEPPA_ROOT/scripts/lib/load-env.sh" . "$PEPPA_ROOT/scripts/lib/load-env.sh"
mkdir -p "${PEPPA_HOME:-$HOME/.peppa}" mkdir -p "${PEPPA_HOME:-$HOME/.peppa}"
exec "$PEPPA_ROOT/node_modules/.bin/tsx" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@" exec "${PEPPA_NODE:-node}" --import "$PEPPA_ROOT/scripts/lib/require-node.mjs" "$PEPPA_ROOT/packages/runner/src/hook.ts" "$@"

View File

@ -10,6 +10,7 @@ import {
getQuestion, getQuestion,
getSession, getSession,
logSessionEvent, logSessionEvent,
peppaInputSentAt,
pendingSessionQuestions, pendingSessionQuestions,
raiseSessionQuestion, raiseSessionQuestion,
releaseHookQuestion, releaseHookQuestion,
@ -214,8 +215,11 @@ async function handle(event: string, input: HookInput): Promise<void> {
case "prompt": case "prompt":
// Someone typed into the terminal (or Peppa pasted an answer): anything still // Someone typed into the terminal (or Peppa pasted an answer): anything still
// pending for this session is now answered — except hook-held questions. // pending for this session is now answered — except hook-held questions, and,
for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true })) { // when Peppa typed this text itself, questions raised after it did (e.g. a CI
// failure pasted while the PM is being asked about the next one).
const sentAt = input.prompt ? await peppaInputSentAt(db, s.id, input.prompt) : null;
for (const q of await pendingSessionQuestions(db, s.id, { excludeHook: true, createdBefore: sentAt ?? undefined })) {
await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {}); await answerQuestion(db, q.id, input.prompt ?? "", "terminal").catch(() => {});
} }
await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now }); await updateSession(db, s.id, { status: "running", autoNudges: 0, lastActivityAt: now });

View File

@ -136,6 +136,8 @@ async function launch(
export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> { export async function sendToSession(db: Db, sessionId: number, text: string): Promise<void> {
const s = await getSession(db, sessionId); const s = await getSession(db, sessionId);
if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`); if (!(await tmux.hasSession(s.tmuxName))) throw new PeppaError(`Session #${s.id} (${s.tmuxName}) is not running`);
// Recorded before typing: the prompt hook answers only questions older than this input.
await logSessionEvent(db, s, "input_sent", { text });
await tmux.sendText(s.tmuxName, text); await tmux.sendText(s.tmuxName, text);
await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() }); await updateSession(db, s.id, { status: "running", lastActivityAt: new Date() });
} }

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Mock claude CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts). # Mock claude CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts).
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@" exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" claude "$@"

View File

@ -1,4 +1,4 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Mock codex CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts). # Mock codex CLI for Peppa tests and manual CJM runs (see packages/testkit/src/mock-agent.ts).
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@" exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-agent.ts" codex "$@"

View File

@ -1,3 +1,3 @@
#!/usr/bin/env bash #!/usr/bin/env bash
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-telegram-server.ts" "$@" exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-telegram-server.ts" "$@"

View File

@ -1,3 +1,3 @@
#!/usr/bin/env bash #!/usr/bin/env bash
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)" ROOT="$(cd "$(dirname "$(readlink -f "$0")")/../../.." && pwd)"
exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/mock-triage.ts" "$@" exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/mock-triage.ts" "$@"

View File

@ -53,6 +53,6 @@ case "${1:-}" in
down) "${TM[@]}" kill-server 2>/dev/null || true; echo "stand is down" ;; down) "${TM[@]}" kill-server 2>/dev/null || true; echo "stand is down" ;;
status) status ;; status) status ;;
peppa) shift; exec "$PEPPA" "$@" ;; peppa) shift; exec "$PEPPA" "$@" ;;
tg) shift; exec "$ROOT/node_modules/.bin/tsx" "$ROOT/packages/testkit/src/peppa-dev-tg.ts" "$@" ;; tg) shift; exec "${PEPPA_NODE:-node}" --import "$ROOT/scripts/lib/require-node.mjs" "$ROOT/packages/testkit/src/peppa-dev-tg.ts" "$@" ;;
*) sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;; *) sed -n '2,9p' "$0" | sed 's/^# \{0,1\}//'; exit 1 ;;
esac esac

View File

@ -5,7 +5,7 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"typecheck": "tsc -p .", "typecheck": "tsc -p .",
"test": "tsx --test --test-concurrency=1 test/*.test.ts" "test": "node --test --test-concurrency=1 test/*.test.ts"
}, },
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "1.32.2", "@modelcontextprotocol/sdk": "1.32.2",

View File

@ -50,8 +50,10 @@ export class MockGitea {
private seq = 1; private seq = 1;
private server: Server | null = null; private server: Server | null = null;
url = ""; url = "";
private readonly dir: string;
constructor(private readonly dir: string) { constructor(dir: string) {
this.dir = dir;
mkdirSync(dir, { recursive: true }); mkdirSync(dir, { recursive: true });
} }

View File

@ -219,7 +219,7 @@ describe("Без спама", () => {
describe("Сводка в CLI", () => { describe("Сводка в CLI", () => {
const cli = (...args: string[]) => const cli = (...args: string[]) =>
execFileSync(join(ROOT, "node_modules/.bin/tsx"), [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env }); execFileSync(process.execPath, [join(ROOT, "packages/cli/src/index.ts"), ...args], { encoding: "utf8", env: process.env });
test("Сводка", async () => { test("Сводка", async () => {
const now = Date.now(); const now = Date.now();

3
pnpm-lock.yaml generated
View File

@ -169,9 +169,6 @@ importers:
'@types/node': '@types/node':
specifier: 26.6.6 specifier: 26.6.6
version: 26.6.6 version: 26.6.6
tsx:
specifier: 4.23.15
version: 4.23.15
typescript: typescript:
specifier: 6.0.3 specifier: 6.0.3
version: 6.0.3 version: 6.0.3

View File

@ -9,6 +9,11 @@ set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)" ROOT="$(cd "$(dirname "$0")/.." && pwd)"
mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa" mkdir -p "$HOME/Library/LaunchAgents" "$HOME/.peppa"
PATH_ENV="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin" PATH_ENV="$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
# Bot and watchdog run TypeScript straight from source with Node's type stripping (PEP-36):
# pin the Node that was checked here, so launchd does not depend on what PATH finds later.
NODE_BIN="${PEPPA_NODE:-$(PATH="$PATH_ENV" command -v node || true)}"
[ -x "$NODE_BIN" ] || { echo "node not found (set PEPPA_NODE)" >&2; exit 1; }
"$NODE_BIN" --import "$ROOT/scripts/lib/require-node.mjs" -e 0 || exit 1
install_agent() { # label log workdir args... install_agent() { # label log workdir args...
local label=$1 log=$2 workdir=$3; shift 3 local label=$1 log=$2 workdir=$3; shift 3
@ -25,7 +30,10 @@ install_agent() { # label log workdir args...
$args </array> $args </array>
<key>WorkingDirectory</key><string>$workdir</string> <key>WorkingDirectory</key><string>$workdir</string>
<key>EnvironmentVariables</key> <key>EnvironmentVariables</key>
<dict><key>PATH</key><string>$PATH_ENV</string></dict> <dict>
<key>PATH</key><string>$PATH_ENV</string>
<key>PEPPA_NODE</key><string>$NODE_BIN</string>
</dict>
<key>RunAtLoad</key><true/> <key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/> <key>KeepAlive</key><true/>
<key>StandardOutPath</key><string>$HOME/.peppa/$log</string> <key>StandardOutPath</key><string>$HOME/.peppa/$log</string>

View File

@ -0,0 +1,9 @@
// Preloaded by Peppa's bin wrappers (`node --import`): Peppa runs its TypeScript straight
// from source with Node's built-in type stripping, which older Node versions lack — say so
// before the first .ts file fails to load with a cryptic error.
const MIN_MAJOR = 26;
const major = Number(process.versions.node.split(".")[0]);
if (major < MIN_MAJOR) {
process.stderr.write(`peppa: нужен Node ≥ ${MIN_MAJOR} (сейчас ${process.versions.node}): https://nodejs.org\n`);
process.exit(1);
}

View File

@ -8,6 +8,8 @@
"skipLibCheck": true, "skipLibCheck": true,
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"noEmit": true, "noEmit": true,
"types": ["node"] "types": ["node"]
} }