todo_service: новый сервис todo (надстройка над JobTread, REST, MCP, вебхуки, слежение Control), миграция 024, docs в proposed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -27,6 +27,7 @@ ENV NODE_ENV=production \
|
||||
# khb-sql: чтение зеркала Supabase консольным агентом (роль только для чтения, KHB_SQL_URL передаёт сервис);
|
||||
# khb-drive: работа агента с Google Drive (ключ сервисного аккаунта передаёт сервис в KHB_DRIVE_KEY: builder - строителям, полный - руководителю)
|
||||
RUN printf '#!/bin/sh\nexec node /app/packages/khbuild_assistant_prep/dist/tools/khb-sql.js "$@"\n' > /usr/local/bin/khb-sql && chmod +x /usr/local/bin/khb-sql \
|
||||
&& printf '#!/bin/sh\nexec node /app/packages/khbuild_assistant_prep/dist/tools/khb-drive.js "$@"\n' > /usr/local/bin/khb-drive && chmod +x /usr/local/bin/khb-drive
|
||||
&& printf '#!/bin/sh\nexec node /app/packages/khbuild_assistant_prep/dist/tools/khb-drive.js "$@"\n' > /usr/local/bin/khb-drive && chmod +x /usr/local/bin/khb-drive \
|
||||
&& printf '#!/bin/sh\nexec node /app/packages/todo_service/dist/tools/khb-todo.js "$@"\n' > /usr/local/bin/khb-todo && chmod +x /usr/local/bin/khb-todo
|
||||
USER node
|
||||
CMD ["node", "packages/scheduler/dist/main.js"]
|
||||
|
||||
@@ -8,7 +8,7 @@ TAG="${1:?usage: deploy.sh <image_tag>}"
|
||||
ROOT=/y/services
|
||||
IMAGE="khb-microservices:${TAG}"
|
||||
# имя сервиса : пакет : порт
|
||||
SERVICES=("khb-data-collector:data_collector:8084" "khb-assistant-prep:khbuild_assistant_prep:8085" "khb-scheduler:scheduler:8083" "khb-process-viz:khbuild_process_viz:8086" "khb-reports:reports:8087" "khb-employee-reports:employee_reports:8091" "khb-passwords-backupper:passwords_backupper:8093")
|
||||
SERVICES=("khb-data-collector:data_collector:8084" "khb-assistant-prep:khbuild_assistant_prep:8085" "khb-scheduler:scheduler:8083" "khb-process-viz:khbuild_process_viz:8086" "khb-reports:reports:8087" "khb-employee-reports:employee_reports:8091" "khb-passwords-backupper:passwords_backupper:8093" "khb-todo-service:todo_service:8094")
|
||||
|
||||
docker image inspect "$IMAGE" >/dev/null
|
||||
docker network inspect khb-net >/dev/null 2>&1 || docker network create khb-net >/dev/null
|
||||
|
||||
48
deploy/infra/todo.nginx.conf
Normal file
48
deploy/infra/todo.nginx.conf
Normal file
@@ -0,0 +1,48 @@
|
||||
# todo.khbuild.freeddns.org: публичные входы сервиса todo_service (khb-todo-service, 127.0.0.1:8094).
|
||||
# Открыты только: вебхуки JobTread (секрет в пути), MCP (JWT Keycloak или токен - проверяет сам сервис) и metadata защищённого ресурса.
|
||||
# REST API для агентов наружу не публикуется (внутри docker-сети: http://khb-todo-service:8094).
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name todo.khbuild.freeddns.org;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ { root /var/www/certbot; }
|
||||
location / { return 301 https://$host$request_uri; }
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name todo.khbuild.freeddns.org;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/khbuild-todo/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/khbuild-todo/privkey.pem;
|
||||
client_max_body_size 1m;
|
||||
|
||||
location ^~ /webhooks/jobtread/ {
|
||||
proxy_pass http://127.0.0.1:8094;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_read_timeout 30;
|
||||
}
|
||||
|
||||
location = /mcp {
|
||||
proxy_pass http://127.0.0.1:8094;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Authorization $http_authorization;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_read_timeout 120;
|
||||
}
|
||||
|
||||
location = /.well-known/oauth-protected-resource {
|
||||
proxy_pass http://127.0.0.1:8094;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
|
||||
location / { return 404; }
|
||||
}
|
||||
@@ -14,10 +14,10 @@
|
||||
|---|---|
|
||||
| Единый конфиг (секреты, не в git) | `/y/services/khb-config/settings.json5` |
|
||||
| Скрипт деплоя и шаблон compose | `/y/services/khb-deploy/` (root) |
|
||||
| Сервисы | `/y/services/khb-scheduler`, `khb-data-collector`, `khb-assistant-prep`, `khb-process-viz`, `khb-reports`, `khb-employee-reports` (compose.yaml, `.env` с `IMAGE_TAG`) |
|
||||
| Сервисы | `/y/services/khb-scheduler`, `khb-data-collector`, `khb-assistant-prep`, `khb-process-viz`, `khb-reports`, `khb-employee-reports`, `khb-todo-service` (compose.yaml, `.env` с `IMAGE_TAG`) |
|
||||
| Runner | `/y/services/khb-runner/data`, unit `khb-act-runner` |
|
||||
| Docker-сети | `khb-net` (между сервисами), `supabase_default` (доступ к `supabase-db`) |
|
||||
| Порты (127.0.0.1) | scheduler 8083, data_collector 8084, assistant_prep 8085, process_viz 8086, reports 8087, employee_reports 8091 |
|
||||
| Порты (127.0.0.1) | scheduler 8083, data_collector 8084, assistant_prep 8085, process_viz 8086, reports 8087, employee_reports 8091, todo_service 8094 |
|
||||
|
||||
## Ручные операции
|
||||
- Обновить `deploy.sh` или шаблон: скопировать от root в `/y/services/khb-deploy/` (CI этого не делает намеренно).
|
||||
@@ -50,3 +50,9 @@
|
||||
- `https://reports.khbuild.freeddns.org/employee/todo/` (To-do report) и `/employee/activity/` (Employee Activity); контейнер `khb-employee-reports`, порт 127.0.0.1:8091, в списке `SERVICES` `deploy.sh` последний. Вход - общий для хоста (Keycloak/Google, любой `@khbuild.pro`), `location /employee/` в vhost `reports`.
|
||||
- Читает только Supabase. События JobTread (`jt_event`) и зеркало наполняет `data_collector`: события загружаются после каждого снимка и заданиями планировщика `sync_events_1700`, `sync_events_2100`, `sync_events_2355` (добавлены в серверный `settings.json5`); вручную - `POST /events/sync` у data_collector (Bearer-токен). Таблицы создаёт миграция 009.
|
||||
- Методология (что считается активностью, порог, цвета дней) - [activity_methodology.md](proposed/methodology/activity_methodology.md).
|
||||
|
||||
## Сервис todo (todo_service)
|
||||
- Контейнер `khb-todo-service`, порт 127.0.0.1:8094 (внутри docker-сети - `http://khb-todo-service:8094`), в списке `SERVICES` `deploy.sh` последний (копирование `deploy.sh` на сервер - вручную, см. "Ручные операции"). Секция `todo_service` в серверном `settings.json5` (токен, секрет вебхука, `allowedJobIds`, MCP) должна быть до деплоя.
|
||||
- Публичный субхост `https://todo.khbuild.freeddns.org` (nginx `todo`, сертификат `khbuild-todo`, копия конфига - `deploy/infra/todo.nginx.conf`): наружу только `/webhooks/jobtread/<secret>`, `/mcp`, `/.well-known/oauth-protected-resource`. Вебхук в JobTread сервис регистрирует сам при старте (`webhook.autoRegister`).
|
||||
- Миграция 024 создаёт таблицы `todo_*`. Описание - [модуль](proposed/modules/todo_service.md), API - [api_objects.md](proposed/data_objects/todo_service/api_objects.md).
|
||||
- Живая проверка против JobTread (только тестовый проект): `KHB_LIVE_JT=1 npx vitest run packages/todo_service/src/live.int.test.ts`.
|
||||
|
||||
36
docs/proposed/data_objects/todo_service/api_objects.md
Normal file
36
docs/proposed/data_objects/todo_service/api_objects.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# API todo_service
|
||||
|
||||
**Границы файла.** Здесь описан HTTP-API и MCP сервиса todo: чтение, поиск и запись todo, действия над ними, события для агентов, приём вебхуков JobTread и служебные вызовы. Сюда попадают эндпоинты `todo_service`. Не сюда: сами таблицы (они в соседних файлах), промты агентов, команда `khb-todo` (описана в модуле `agent-cli`).
|
||||
|
||||
HTTP `127.0.0.1:8094` (контейнер `khb-todo-service`, во внутренней сети - `http://khb-todo-service:8094`). Наружу через nginx (`https://todo.khbuild.freeddns.org`) открыты только `/webhooks/jobtread/<secret>`, `/mcp` и `/.well-known/oauth-protected-resource`.
|
||||
|
||||
**Авторизация.** `Authorization: Bearer <todo_service.http.token>`. Права по вызывающему: заголовок `X-Caller-Person: <person id>`. CEO (`construction_manager.chat_kind = 'ceo'`) видит и меняет всё; менеджер - todo своих проектов (`assistant_project`) и назначенные ему. Без заголовка - права администратора (внутренний вызов). Запись возможна только в проекты из `todo_service.allowedJobIds`. Ответы об ошибках: `{ "error": "..." }` (401, 403, 404, 400, 502).
|
||||
|
||||
**Запись.** Идемпотентность: заголовок `Idempotency-Key` (повтор возвращает прежний результат). Ответ `200 { status: "done", id, todo }`, либо `202 { status: "queued", requestId }`, если JobTread недоступен (повтор до 5 минут, состояние - `GET /requests/:id`).
|
||||
|
||||
| Метод | Путь | Описание |
|
||||
|---|---|---|
|
||||
| GET | `/healthz` | `{ ok, db, time }` без авторизации |
|
||||
| GET | `/todos` | поиск: `assignee` (membership id или `me`), `job`, `kind`, `status` (`open` по умолчанию / `done` / `all`), `due_before`, `review_due=1`, `q` (полнотекстовый и подстрока), `limit`, `offset` |
|
||||
| GET | `/todos/:id` | одно todo с надстройкой и связями; если его нет в копии - подтягивается из JobTread |
|
||||
| POST | `/todos` | создать: `{ jobId, name, description?, due?, assigneePersonIds?, assigneeMembershipIds?, kind?, reviewDate? }`; срок по умолчанию - 3 рабочих дня; `kind: control` добавляет `Control:` |
|
||||
| PATCH | `/todos/:id` | изменить: `name`, `description`, `due`, исполнители, `kind`, `reviewDate` (null снимает) |
|
||||
| DELETE | `/todos/:id` | удалить в JobTread |
|
||||
| POST | `/todos/:id/close`, `/reopen` | закрыть / вернуть в работу |
|
||||
| POST | `/todos/:id/snooze` | отложить: `{ until }` или `{ days }` -> `review_date` (только надстройка) |
|
||||
| POST | `/todos/:id/keep` | «Keep confirmed» |
|
||||
| GET | `/todos/:id/links` | связи (Control) |
|
||||
| POST | `/control` | пара Control: `{ jobId, controllerPersonId, executor: { name, description?, due?, assigneePersonIds }, control: { name, description? } }`; срок исполнителя по умолчанию 3 рабочих дня, Control +2 дня |
|
||||
| GET | `/todos/stale` | открытые Reminder/Control старше 3 недель без «Keep confirmed» (`days`, `person` для администратора) |
|
||||
| POST | `/todos/close-batch` | `{ ids: [] }` - закрыть пачкой |
|
||||
| GET | `/events` | лента событий: `person` (администратор), `after`, `pending=1` |
|
||||
| POST | `/events/ack` | `{ ids: [] }` - отметить доставленными |
|
||||
| GET | `/requests/:id` | состояние запроса записи (`pending` / `done` / `failed`) |
|
||||
| POST | `/webhooks/jobtread/:secret` | приём вебхука JobTread (секрет в пути; неверный - 404); всегда `202` |
|
||||
| POST | `/admin/sync`, `/admin/webhook`, `/admin/tick` | только администратор: полная загрузка и опрос; регистрация вебхука; проход слежения и очереди |
|
||||
| POST | `/mcp` | MCP Streamable HTTP без сессий (JSON-RPC 2.0): `initialize`, `tools/list`, `tools/call`; `GET /mcp` - 405 |
|
||||
| GET | `/.well-known/oauth-protected-resource` | metadata защищённого ресурса (issuer Keycloak) |
|
||||
|
||||
**MCP.** Вход: внутренний токен, статический токен из `mcp.staticTokens` (привязан к person или администратор) либо JWT Keycloak (проверка по JWKS issuer; почта сопоставляется с `person.email` или `additional_emails`, неизвестная почта - 403). Инструменты: `todo_search`, `todo_get`, `todo_create`, `todo_update`, `todo_close`, `todo_reopen`, `todo_delete`, `todo_snooze`, `todo_keep`, `todo_control_create`, `todo_stale`, `todo_events`. Те же операции и права, что у REST: логика в одном ядре.
|
||||
|
||||
**Доставка событий агентам** (`notify.enabled`, по умолчанию выключена до переключения агентов): сервис шлёт `POST <notify.url>` с `Authorization: Bearer <notify.token>` и телом `{ kind: "todo_events", personId, events: [{ id, type, taskId, payload }] }`; 2xx - доставлено. События с `person_id` доставляются только в окне часов `notify.fromHour`-`toHour` по `common.timezone`; получатель с `agent_paused` и `pause_mode = 'off'` пропускается. Без push агент читает ленту `GET /events?pending=1` и подтверждает `POST /events/ack`.
|
||||
16
docs/proposed/data_objects/todo_service/todo_event.md
Normal file
16
docs/proposed/data_objects/todo_service/todo_event.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# todo_event
|
||||
|
||||
Лента событий для агентов: сервис решает, **что произошло**, агент решает, **что сказать**. Не хранит историю изменений todo в JobTread (это `jt_event`, заполняет `data_collector`).
|
||||
|
||||
| Колонка | Тип | Null | Описание |
|
||||
|---|---|---|---|
|
||||
| id | bigserial PK | нет | курсор для `GET /events?after=` |
|
||||
| created_at | timestamptz | нет | |
|
||||
| event_type | text | нет | `control_done`, `control_overdue`, `review_due`, `write_failed` |
|
||||
| task_id | text | да | todo, к которому относится событие |
|
||||
| person_id | uuid FK person | да | адресат (агент его чата); null - без адресата, читает администратор |
|
||||
| payload | jsonb | нет | данные события (`executorTaskId`, `executorName`, `controlDue`, `reviewDate`, `requestId`...) |
|
||||
| delivered_at | timestamptz | да | когда доставлено агенту (push при `notify.enabled` или `POST /events/ack`) |
|
||||
| delivery_error | text | да | последняя ошибка доставки (повтор на следующем проходе) |
|
||||
|
||||
Миграция 024, RLS включён.
|
||||
19
docs/proposed/data_objects/todo_service/todo_ext.md
Normal file
19
docs/proposed/data_objects/todo_service/todo_ext.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# todo_ext
|
||||
|
||||
Надстройка над todo JobTread: поля, которыми владеет только `todo_service`. Ключ - id задачи JobTread, строка создаётся лениво (когда todo впервые попадает под правила или к нему применяется операция сервиса). Не хранит название, срок, исполнителя и статус закрытия: это поля JobTread (`todo_item`).
|
||||
|
||||
| Колонка | Тип | Null | Описание |
|
||||
|---|---|---|---|
|
||||
| task_id | text PK | нет | id задачи JobTread |
|
||||
| kind | text | нет | `todo` / `reminder` / `control`; по умолчанию угадывается по названию (`Control:`, `Reminder:`) |
|
||||
| review_date | date | да | дата пересмотра («отложить»); в JobTread поля нет; при `defaults.reviewLine` сервис дописывает в описание «Review: ДД.ММ» |
|
||||
| keep_confirmed | boolean | нет | «Keep confirmed»: todo не попадает в проверку устаревания (в описание дописывается `Keep confirmed <дата>`) |
|
||||
| done_flag, overdue_flag | boolean | нет | Control: «выполнено» / «просрочено»; по ним сервис держит суффикс в названии |
|
||||
| base_name | text | да | название без суффикса (то, что хотел человек) |
|
||||
| created_by_kind | text | нет | `human` / `agent` / `automation` / `unknown` |
|
||||
| created_by | text | да | кто создал (имя агента или человека) |
|
||||
| review_notified_for | date | да | для какой `review_date` уже создано событие `review_due` |
|
||||
| stale_asked_at | timestamptz | да | зарезервировано: когда спрашивали про устаревание |
|
||||
| created_at, updated_at | timestamptz | нет | служебные |
|
||||
|
||||
Индекс по `review_date`. Таблица создаётся миграцией 024, RLS включён.
|
||||
20
docs/proposed/data_objects/todo_service/todo_item.md
Normal file
20
docs/proposed/data_objects/todo_service/todo_item.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# todo_item
|
||||
|
||||
Живая копия todo JobTread (`isToDo = true`): только поля, которыми владеет JobTread. Заполняет `todo_service`: вебхуки и опрос событий (одна сторона: JobTread -> Supabase), ответы на собственные записи сервиса, полная загрузка открытых todo при старте. Не хранит поля надстройки (они в `todo_ext`) и не заменяет зеркало `jt_task` (оно принадлежит `data_collector` и обновляется по снимкам).
|
||||
|
||||
| Колонка | Тип | Null | Описание |
|
||||
|---|---|---|---|
|
||||
| task_id | text PK | нет | id задачи JobTread |
|
||||
| job_id | text | да | проект (запись сервисом поддерживается только для todo с проектом) |
|
||||
| name | text | нет | название (у Control todo может содержать суффикс статуса) |
|
||||
| description | text | да | описание |
|
||||
| assignee_ids | text[] | нет | id membership JobTread исполнителей |
|
||||
| start_date, end_date | date | да | у todo JobTread всегда держит `start_date = end_date` (отдельно задать нельзя) |
|
||||
| progress | numeric | да | 0..1; `>= 1` - закрыто |
|
||||
| is_deleted | boolean | нет | todo удалено в JobTread |
|
||||
| jt_created_at | timestamptz | да | создание в JobTread |
|
||||
| last_event_at | timestamptz | да | время последнего события JobTread по задаче (для «2 дня нет действий») |
|
||||
| synced_at | timestamptz | нет | когда строка обновлена |
|
||||
| search | tsvector | нет | генерируемый, `to_tsvector('simple', name \|\| ' ' \|\| description)`, индекс GIN |
|
||||
|
||||
Индексы: по проекту, по сроку (только неудалённые), GIN по `search` и `assignee_ids`. Таблица создаётся миграцией 024, RLS включён.
|
||||
17
docs/proposed/data_objects/todo_service/todo_link.md
Normal file
17
docs/proposed/data_objects/todo_service/todo_link.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# todo_link
|
||||
|
||||
Связи между todo. Сейчас единственный вид - `control`: парное «Control:» todo контролёра к todo исполнителя (замена таблицы `control_todo`, миграция 023: после переключения агентов `control_todo` удаляется). Не хранит сами todo.
|
||||
|
||||
| Колонка | Тип | Null | Описание |
|
||||
|---|---|---|---|
|
||||
| id | uuid PK | нет | |
|
||||
| link_type | text | нет | `control` |
|
||||
| task_id | text | нет | Control todo контролёра (вместе с `link_type` уникально) |
|
||||
| linked_task_id | text | нет | todo исполнителя |
|
||||
| controller_person_id | uuid FK person | нет | контролёр: получатель событий |
|
||||
| executor_name | text | да | название todo исполнителя (для сообщения) |
|
||||
| control_due | date | да | срок Control todo (срок исполнителя + 2 дня); без него «просрочено» не ставится |
|
||||
| status | text | нет | `active` / `overdue` / `done` / `closed` (Control todo закрыл контролёр, слежение снято) |
|
||||
| created_at, updated_at | timestamptz | нет | служебные |
|
||||
|
||||
Слежение ведёт `todo_service` (см. модуль `control-watch`): `active`/`overdue` отслеживаются, `done`/`closed` - нет. Миграция 024, RLS включён.
|
||||
19
docs/proposed/data_objects/todo_service/todo_request.md
Normal file
19
docs/proposed/data_objects/todo_service/todo_request.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# todo_request
|
||||
|
||||
Запросы на запись в JobTread: идемпотентный ключ (`Idempotency-Key`) и очередь повторов. JobTread недоступен - запрос остаётся `pending`, сервис повторяет до дедлайна (по умолчанию 5 минут), агент не ждёт. Не хранит сами todo.
|
||||
|
||||
| Колонка | Тип | Null | Описание |
|
||||
|---|---|---|---|
|
||||
| id | uuid PK | нет | `requestId`, ответ 202 содержит его |
|
||||
| idem_key | text unique | да | ключ идемпотентности; повтор с тем же ключом возвращает прежний результат |
|
||||
| op | text | нет | `create` / `update` / `delete` / `control` |
|
||||
| args | jsonb | нет | подготовленные аргументы операции |
|
||||
| caller | text | да | person id или имя вызывающего (для события `write_failed`) |
|
||||
| status | text | нет | `pending` / `done` / `failed` |
|
||||
| result | jsonb | да | результат; для `control` - ход выполнения (`executorTaskId`, `controlTaskId`) для безопасного повтора |
|
||||
| error | text | да | последняя ошибка |
|
||||
| attempts | int | нет | число попыток |
|
||||
| next_attempt_at, deadline | timestamptz | нет | следующая попытка и крайний срок повторов |
|
||||
| created_at, updated_at | timestamptz | нет | служебные |
|
||||
|
||||
Миграция 024, RLS включён.
|
||||
11
docs/proposed/data_objects/todo_service/todo_sync_state.md
Normal file
11
docs/proposed/data_objects/todo_service/todo_sync_state.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# todo_sync_state
|
||||
|
||||
Служебное состояние приёма из JobTread: ключ - значение. Сейчас один ключ: `poll_cursor` (время последнего опроса событий JobTread; следующий опрос берёт события с запасом в минуту). Не хранит данные todo.
|
||||
|
||||
| Колонка | Тип | Null | Описание |
|
||||
|---|---|---|---|
|
||||
| key | text PK | нет | имя состояния |
|
||||
| value | text | да | значение |
|
||||
| updated_at | timestamptz | нет | |
|
||||
|
||||
Миграция 024, RLS включён.
|
||||
@@ -67,3 +67,8 @@
|
||||
58. **Согласованные промты установлены всем менеджерам (29.10.2026)**: владелец перенёс промты (тихий режим и recap проектных каналов, Huddle, короткие напоминания, todo-напоминания, ответ отправителю, Control, CEO) в approved; approved = proposed. В коде снято ограничение «только новая версия агента» для recap (`chat.ts`, `intake.ts`) и Control (`control.ts`): теперь они работают у всех менеджеров и в реальных проектных каналах. Долгоживущий процесс агента (`agent.live.managerIds`) по-прежнему только у тестового менеджера и Arthur - это отдельное переключение.
|
||||
59. **Служебные (fallback) сообщения агента - по-английски (29.10.2026)**: при сбое обработки в чат уходило русское «Не смог обработать сообщение - уже сообщил ИТ-команде…» (26.10 оно появилось в проектных каналах Walter). Теперь текст английский: «Sorry, I could not process your message. The IT team has been notified and will sort it out soon.» (`slack/chat.ts`). Сообщения в ИТ-канал остаются на русском (их читает команда ИТ).
|
||||
|
||||
60. **todo_service: отдельная живая копия `todo_item`, а не запись в зеркало `jt_task` (29.10.2026)**: спецификация говорит «заполнение зеркала и надстройки», но `jt_task` принадлежит `data_collector` (снимки, `_hist`, обновление дважды в сутки). Сервис ведёт свою таблицу `todo_item` (только todo, поля JobTread, обновляется вебхуками, опросом событий и ответами на собственные записи), `jt_task` не трогает. Данные для отчётов по-прежнему берутся из зеркала.
|
||||
61. **todo_service: `startDate` не используется как «review» (29.10.2026)**: проверено на тестовом проекте - у todo JobTread `startDate` всегда равен `endDate` (ставится сам, отдельное изменение игнорируется). `review_date` хранится только в `todo_ext`; по желанию (`todo_service.defaults.reviewLine`, по умолчанию выключено) в конец описания дописывается «Review: ДД.ММ».
|
||||
62. **todo_service: вебхуки JobTread проверены (29.10.2026)**: вебхук организации (`createWebhook`: только `organizationId` и `url`) доставляет события `taskCreated` / `taskUpdated` / `taskDeleted` за доли секунды; при изменении в `data.next` и `data.previous` только изменённые поля, id задачи - в `createdEvent.task.id`; подписи нет (секрет в пути адреса), выбора типов событий нет. Опрос `organization.events` оставлен страховкой (раз в 5 минут).
|
||||
63. **todo_service: новый субхост `todo.khbuild.freeddns.org` (29.10.2026)**: публичны только `/webhooks/jobtread/<secret>`, `/mcp` и `/.well-known/oauth-protected-resource`; REST для агентов - только во внутренней сети (`http://khb-todo-service:8094`). Новая миграция 024 (таблицы `todo_item`, `todo_ext`, `todo_link`, `todo_event`, `todo_request`, `todo_sync_state`); `control_todo` (миграция 023, сейчас пуста) остаётся до переключения агентов. В общий `Dockerfile` добавлена обёртка `khb-todo`.
|
||||
64. **todo_service: слежение за Control включено, доставка агентам выключена (29.10.2026)**: сервис следит за своими парами (`todo_link`) и пишет события в `todo_event`, но push агентам (`notify.enabled`) выключен до переключения агентов; пока агенты читают ленту `GET /events`. Старый `ControlWatcher` работает только по `control_todo` - пересечения пар нет.
|
||||
|
||||
3
docs/proposed/modules/todo_service.md
Normal file
3
docs/proposed/modules/todo_service.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# todo_service
|
||||
|
||||
микросервис todo (задачи и напоминания) поверх JobTread и Supabase: JobTread остаётся главным для самих todo, недостающее (review_date, связи Control, тип, флаги) хранится в надстройке в Supabase. Входная спецификация: `input_specs/todo_service/todo_service_initial.md`.
|
||||
3
docs/proposed/modules/todo_service/agent-cli.md
Normal file
3
docs/proposed/modules/todo_service/agent-cli.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# todo_service / agent-cli
|
||||
|
||||
команда `khb-todo` для консольных агентов в Bash поверх REST (как `khb-sql` и `khb-drive`): `packages/todo_service/dist/tools/khb-todo.js`, обёртка `/usr/local/bin/khb-todo` в общем образе. Окружение, которое выставляет сервис агентов: `KHB_TODO_URL` (`http://khb-todo-service:8094`), `KHB_TODO_TOKEN`, `KHB_TODO_CALLER` (person id менеджера: права по вызывающему). Вывод - JSON, `khb-todo help` - список команд.
|
||||
3
docs/proposed/modules/todo_service/control-watch.md
Normal file
3
docs/proposed/modules/todo_service/control-watch.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# todo_service / control-watch
|
||||
|
||||
слежение (переехало из `ControlWatcher` агентов) за парами Control и датами пересмотра. Раз в `control.tickSeconds` (10 минут): исполнитель закрыл todo -> статус `done`, к названию Control todo «(выполнено)», событие `control_done` контролёру; срок Control наступил и по todo исполнителя `control.quietDays` (2) дня нет событий -> `overdue`, «(просрочено)», событие `control_overdue` (если исполнитель закроет позже - снова `done` и событие); Control todo закрыл контролёр - слежение снимается без события; без срока «просрочено» не ставится. Control todo сервис не закрывает. Раз в 5 минут: `review_date` наступила -> одно событие `review_due` на каждую дату. Доставка событий агентам: см. `api_objects.md`.
|
||||
3
docs/proposed/modules/todo_service/http-api.md
Normal file
3
docs/proposed/modules/todo_service/http-api.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# todo_service / http-api
|
||||
|
||||
REST API сервиса, приём вебхуков и служебные вызовы; авторизация токеном и заголовком `X-Caller-Person`. Описание: `data_objects/todo_service/api_objects.md`.
|
||||
5
docs/proposed/modules/todo_service/jt-intake.md
Normal file
5
docs/proposed/modules/todo_service/jt-intake.md
Normal file
@@ -0,0 +1,5 @@
|
||||
# todo_service / jt-intake
|
||||
|
||||
приём изменений из JobTread в Supabase (только в одну сторону): вебхуки (`createWebhook`, адрес с секретом в пути), опрос событий `organization.events` как страховка (по умолчанию раз в 5 минут, с курсором), полная загрузка открытых todo при старте, ленивая подгрузка неизвестного todo. Люди пишут в JobTread напрямую - любая правка подхватывается этим же путём.
|
||||
|
||||
Проверено на тестовом проекте (29.10.2026): вебхук организации доставляет событие через доли секунды после изменения; типы задач `taskCreated`, `taskUpdated`, `taskDeleted` (приходят и события других типов, сервис их игнорирует); тело - `createdEvent` с `task.id`, `data.next` и `data.previous`: при создании `next` содержит полное состояние, при изменении - только изменённые поля, при удалении `next = null`; подписи в заголовках нет (защита - секрет в пути); у вебхука нет выбора типов событий. Поведение `startDate`: у todo он всегда равен `endDate` (при создании с одним `endDate` ставится сам, отдельное изменение игнорируется), поэтому как `review` его использовать нельзя.
|
||||
3
docs/proposed/modules/todo_service/mcp.md
Normal file
3
docs/proposed/modules/todo_service/mcp.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# todo_service / mcp
|
||||
|
||||
тонкий адаптер MCP (Streamable HTTP без сессий, JSON-RPC 2.0, реализован без внешних SDK) над тем же ядром, что и REST: другие Claude и инструменты получают те же операции и те же права. Вход: Keycloak (JWT по JWKS), статический токен или внутренний токен. Две отдельные реализации логики не делаются.
|
||||
3
docs/proposed/modules/todo_service/todo-core.md
Normal file
3
docs/proposed/modules/todo_service/todo-core.md
Normal file
@@ -0,0 +1,3 @@
|
||||
# todo_service / todo-core
|
||||
|
||||
единое ядро: чтение (копия `todo_item` + надстройка `todo_ext`), поиск (фильтры и полнотекстовый `tsvector`), запись и правила в одном месте. Запись в поля JobTread - сначала в JobTread, затем в копию (read-your-writes); запись в поля надстройки - только в Supabase. Права по вызывающему (CEO - всё, менеджер - свои проекты и назначенные). Идемпотентные ключи и очередь повторов (`todo_request`, до 5 минут). Правила: срок по умолчанию 3 рабочих дня (`calendar_day`), префикс `Control:` и срок Control +2 дня, «Keep confirmed», вопрос про todo старше 3 недель (`/todos/stale`), суффиксы «(выполнено)» / «(просрочено)» сервис приводит к состоянию надстройки после каждой правки названия (эхо-петель нет: запись происходит только при расхождении).
|
||||
104
packages/khb_common/migrations/024_todo_service.sql
Normal file
104
packages/khb_common/migrations/024_todo_service.sql
Normal file
@@ -0,0 +1,104 @@
|
||||
-- todo_service: живая копия todo JobTread (поля принадлежат JobTread), надстройка (поля принадлежат сервису),
|
||||
-- связи (Control), лента событий для агентов, очередь запросов (идемпотентность и повторы записи в JobTread).
|
||||
|
||||
-- Поля JobTread; обновляются только из JobTread (вебхуки, опрос) и из ответов на собственные записи сервиса.
|
||||
create table todo_item (
|
||||
task_id text primary key,
|
||||
job_id text,
|
||||
name text not null,
|
||||
description text,
|
||||
assignee_ids text[] not null default '{}',
|
||||
start_date date,
|
||||
end_date date,
|
||||
progress numeric,
|
||||
is_deleted boolean not null default false,
|
||||
jt_created_at timestamptz,
|
||||
last_event_at timestamptz, -- последнее событие JobTread по задаче (для "2 дня нет действий")
|
||||
synced_at timestamptz not null default now(),
|
||||
search tsvector generated always as (to_tsvector('simple', coalesce(name, '') || ' ' || coalesce(description, ''))) stored
|
||||
);
|
||||
create index todo_item_job_idx on todo_item (job_id) where not is_deleted;
|
||||
create index todo_item_end_idx on todo_item (end_date) where not is_deleted;
|
||||
create index todo_item_search_idx on todo_item using gin (search);
|
||||
create index todo_item_assignee_idx on todo_item using gin (assignee_ids);
|
||||
|
||||
-- Поля только сервиса.
|
||||
create table todo_ext (
|
||||
task_id text primary key,
|
||||
kind text not null default 'todo' check (kind in ('todo', 'reminder', 'control')),
|
||||
review_date date,
|
||||
keep_confirmed boolean not null default false,
|
||||
done_flag boolean not null default false, -- Control: исполнитель закрыл ("(выполнено)")
|
||||
overdue_flag boolean not null default false, -- Control: срок наступил, действий нет ("(просрочено)")
|
||||
base_name text, -- желаемое название без суффикса статуса
|
||||
created_by_kind text not null default 'unknown' check (created_by_kind in ('human', 'agent', 'automation', 'unknown')),
|
||||
created_by text,
|
||||
review_notified_for date, -- для какого review_date уже создано событие review_due
|
||||
stale_asked_at timestamptz,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
create index todo_ext_review_idx on todo_ext (review_date) where review_date is not null;
|
||||
|
||||
-- Связи между todo. Сейчас единственный вид - control (замена control_todo).
|
||||
create table todo_link (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
link_type text not null default 'control' check (link_type in ('control')),
|
||||
task_id text not null, -- Control todo контролёра
|
||||
linked_task_id text not null, -- todo исполнителя
|
||||
controller_person_id uuid not null references person(id),
|
||||
executor_name text,
|
||||
control_due date,
|
||||
status text not null default 'active' check (status in ('active', 'overdue', 'done', 'closed')),
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now(),
|
||||
unique (link_type, task_id)
|
||||
);
|
||||
create index todo_link_open_idx on todo_link (status) where status in ('active', 'overdue');
|
||||
create index todo_link_linked_idx on todo_link (linked_task_id);
|
||||
|
||||
-- События для агентов: сервис решает, что произошло; агент решает, что сказать.
|
||||
create table todo_event (
|
||||
id bigserial primary key,
|
||||
created_at timestamptz not null default now(),
|
||||
event_type text not null, -- control_done, control_overdue, review_due, write_failed, ...
|
||||
task_id text,
|
||||
person_id uuid references person(id),
|
||||
payload jsonb not null default '{}',
|
||||
delivered_at timestamptz,
|
||||
delivery_error text
|
||||
);
|
||||
create index todo_event_person_idx on todo_event (person_id, id);
|
||||
create index todo_event_pending_idx on todo_event (id) where delivered_at is null;
|
||||
|
||||
-- Запросы на запись в JobTread: идемпотентный ключ и очередь повторов (до 5 минут).
|
||||
create table todo_request (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
idem_key text unique,
|
||||
op text not null, -- create / update / delete / control
|
||||
args jsonb not null,
|
||||
caller text,
|
||||
status text not null default 'pending' check (status in ('pending', 'done', 'failed')),
|
||||
result jsonb,
|
||||
error text,
|
||||
attempts int not null default 0,
|
||||
next_attempt_at timestamptz not null default now(),
|
||||
deadline timestamptz not null,
|
||||
created_at timestamptz not null default now(),
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
create index todo_request_pending_idx on todo_request (next_attempt_at) where status = 'pending';
|
||||
|
||||
-- Состояние приёма из JobTread (курсор опроса событий, регистрация вебхука).
|
||||
create table todo_sync_state (
|
||||
key text primary key,
|
||||
value text,
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
|
||||
alter table todo_item enable row level security;
|
||||
alter table todo_ext enable row level security;
|
||||
alter table todo_link enable row level security;
|
||||
alter table todo_event enable row level security;
|
||||
alter table todo_request enable row level security;
|
||||
alter table todo_sync_state enable row level security;
|
||||
23
packages/todo_service/docs/service.md
Normal file
23
packages/todo_service/docs/service.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# todo_service
|
||||
Статус: в разработке/приёмке (khb-todo-service, 127.0.0.1:8094). Владелец: ИТ-команда. Назначение: вести todo (задачи и напоминания) поверх JobTread и Supabase: приём изменений JobTread, надстройка (review_date, Control, флаги), REST API, MCP, слежение за Control, события для агентов.
|
||||
|
||||
## Endpoints и доступ
|
||||
Внутренний REST с Bearer-токеном `todo_service.http.token` и заголовком `X-Caller-Person`; наружу через nginx `https://todo.khbuild.freeddns.org` открыты только `/webhooks/jobtread/<secret>`, `/mcp` (JWT Keycloak или статический токен) и `/.well-known/oauth-protected-resource`. Подробно: [api_objects.md](../../../docs/proposed/data_objects/todo_service/api_objects.md).
|
||||
|
||||
## Запуск и зависимости
|
||||
Docker Compose `/y/services/khb-todo-service`, образ `khb-microservices:<tag>`, сети `khb-net` и `supabase_default`. Зависит от БД (Supabase), JobTread Pave API (grant key из секции `jobtread`), Keycloak (JWKS для MCP). Сервис агентов обращается к нему командой `khb-todo`.
|
||||
|
||||
## Конфигурация и секреты
|
||||
`/y/services/khb-config/settings.json5`, секции `common`, `jobtread` и `todo_service` (`http`, `allowedJobIds`, `webhook`, `poll`, `control`, `notify`, `mcp`, `defaults`; схема - `src/settings.ts`). Секрет вебхука, токен сервиса и статические токены MCP - только в этом файле.
|
||||
|
||||
## Данные
|
||||
Таблицы `todo_item`, `todo_ext`, `todo_link`, `todo_event`, `todo_request`, `todo_sync_state` (миграция 024). Backup - вместе с БД Supabase. JobTread остаётся источником todo: копию можно перестроить `POST /admin/sync`.
|
||||
|
||||
## Логи и healthcheck
|
||||
`docker logs khb-todo-service` (json-file, 5x10 МБ); healthcheck `GET /healthz` в compose.
|
||||
|
||||
## Обновление и rollback
|
||||
Автодеплой из Gitea Actions, откат - `docs/deploy.md`. Сервис включён в `SERVICES` скрипта `deploy.sh` (копируется на сервер вручную).
|
||||
|
||||
## Отклонения от стандарта
|
||||
См. `docs/deploy.md` и `docs/proposed/deviations.md`.
|
||||
19
packages/todo_service/package.json
Normal file
19
packages/todo_service/package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "todo_service",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.json",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"start": "node dist/main.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"fastify": "^5.2.0",
|
||||
"jose": "^5.9.6",
|
||||
"khb_common": "workspace:*",
|
||||
"zod": "3.25.76"
|
||||
}
|
||||
}
|
||||
54
packages/todo_service/src/access.ts
Normal file
54
packages/todo_service/src/access.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { Pool } from "khb_common";
|
||||
|
||||
/** Вызывающий и его права. admin - внутренний вызов без person (все todo); person - агент или человек. */
|
||||
export interface Caller {
|
||||
kind: "admin" | "person";
|
||||
name: string;
|
||||
personId?: string;
|
||||
all: boolean;
|
||||
jobIds: ReadonlySet<string>;
|
||||
membershipId: string | null;
|
||||
}
|
||||
|
||||
export const ADMIN: Caller = { kind: "admin", name: "service", all: true, jobIds: new Set(), membershipId: null };
|
||||
|
||||
export class AccessError extends Error {
|
||||
constructor(message: string, readonly status = 403) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Права по person: CEO видит и меняет всё, менеджер - todo своих проектов (assistant_project) и назначенные ему. */
|
||||
export async function resolveCaller(pool: Pool, personId: string): Promise<Caller> {
|
||||
const { rows } = await pool.query(
|
||||
`select p.id, p.display_name, p.jt_membership_id, cm.chat_kind
|
||||
from person p left join construction_manager cm on cm.person_id = p.id
|
||||
where p.id = $1 and p.is_active`,
|
||||
[personId],
|
||||
);
|
||||
const p = rows[0];
|
||||
if (!p) throw new AccessError("неизвестный или неактивный person", 401);
|
||||
if (p.chat_kind === "ceo") return { kind: "person", name: p.display_name, personId, all: true, jobIds: new Set(), membershipId: p.jt_membership_id ?? null };
|
||||
const jobs = await pool.query("select jt_job_id from assistant_project where manager_person_id = $1 and is_enabled", [personId]);
|
||||
return {
|
||||
kind: "person", name: p.display_name, personId, all: false,
|
||||
jobIds: new Set(jobs.rows.map((r) => String(r.jt_job_id))), membershipId: p.jt_membership_id ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Видит ли вызывающий todo (проект или назначение). */
|
||||
export function canRead(c: Caller, t: { jobId: string | null; assigneeIds: string[] }): boolean {
|
||||
if (c.all) return true;
|
||||
if (t.jobId && c.jobIds.has(t.jobId)) return true;
|
||||
return !!c.membershipId && t.assigneeIds.includes(c.membershipId);
|
||||
}
|
||||
|
||||
/** Условие SQL для списков: возвращает фрагмент и добавляет параметры. */
|
||||
export function scopeSql(c: Caller, params: unknown[], alias = "i"): string {
|
||||
if (c.all) return "true";
|
||||
params.push([...c.jobIds]);
|
||||
const jobs = `${alias}.job_id = any($${params.length}::text[])`;
|
||||
if (!c.membershipId) return `(${jobs})`;
|
||||
params.push(c.membershipId);
|
||||
return `(${jobs} or $${params.length} = any(${alias}.assignee_ids))`;
|
||||
}
|
||||
54
packages/todo_service/src/auth.ts
Normal file
54
packages/todo_service/src/auth.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { createRemoteJWKSet, jwtVerify } from "jose";
|
||||
import type { Pool } from "khb_common";
|
||||
import { ADMIN, AccessError, resolveCaller, type Caller } from "./access.js";
|
||||
import type { TodoServiceSettings } from "./settings.js";
|
||||
|
||||
export const safeEqual = (a: string, b: string): boolean => {
|
||||
const x = Buffer.from(a);
|
||||
const y = Buffer.from(b);
|
||||
return x.length === y.length && timingSafeEqual(x, y);
|
||||
};
|
||||
|
||||
const bearer = (h: string | undefined): string | null => (h && h.startsWith("Bearer ") ? h.slice(7).trim() : null);
|
||||
|
||||
/** Права по токену: внутренний токен сервиса (+ X-Caller-Person), статические токены и JWT Keycloak (для MCP). */
|
||||
export class Auth {
|
||||
private jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
|
||||
constructor(private readonly pool: Pool, private readonly s: TodoServiceSettings) {}
|
||||
|
||||
/** REST: только внутренний токен; person передаётся заголовком X-Caller-Person. */
|
||||
async internal(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
|
||||
const t = bearer(authorization);
|
||||
if (!t || !safeEqual(t, this.s.http.token)) throw new AccessError("unauthorized", 401);
|
||||
return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
|
||||
}
|
||||
|
||||
/** MCP: внутренний токен, статический токен или JWT Keycloak; JWT без известного person отклоняется. */
|
||||
async mcp(authorization: string | undefined, callerPerson: string | undefined): Promise<Caller> {
|
||||
const t = bearer(authorization);
|
||||
if (!t) throw new AccessError("unauthorized", 401);
|
||||
if (safeEqual(t, this.s.http.token)) return callerPerson ? resolveCaller(this.pool, callerPerson) : ADMIN;
|
||||
const st = this.s.mcp.staticTokens.find((x) => safeEqual(t, x.token));
|
||||
if (st) return st.personId ? resolveCaller(this.pool, st.personId) : { ...ADMIN, name: st.name ?? "mcp-token" };
|
||||
if (!this.s.mcp.issuer) throw new AccessError("unauthorized", 401);
|
||||
this.jwks ??= createRemoteJWKSet(new URL(`${this.s.mcp.issuer.replace(/\/$/, "")}/protocol/openid-connect/certs`));
|
||||
let email: string | undefined;
|
||||
try {
|
||||
const { payload } = await jwtVerify(t, this.jwks, { issuer: this.s.mcp.issuer, ...(this.s.mcp.audience ? { audience: this.s.mcp.audience } : {}) });
|
||||
if (payload.email_verified === false) throw new Error("email не подтверждён");
|
||||
email = typeof payload.email === "string" ? payload.email : undefined;
|
||||
} catch {
|
||||
throw new AccessError("unauthorized", 401);
|
||||
}
|
||||
if (!email) throw new AccessError("в токене нет email", 401);
|
||||
const p = (
|
||||
await this.pool.query(
|
||||
"select id from person where is_active and (lower(email) = lower($1) or position(lower($1) in lower(coalesce(additional_emails, ''))) > 0) limit 1",
|
||||
[email],
|
||||
)
|
||||
).rows[0];
|
||||
if (!p) throw new AccessError(`для ${email} нет person: доступ запрещён`, 403);
|
||||
return resolveCaller(this.pool, String(p.id));
|
||||
}
|
||||
}
|
||||
646
packages/todo_service/src/core.ts
Normal file
646
packages/todo_service/src/core.ts
Normal file
@@ -0,0 +1,646 @@
|
||||
import { addDays, localDate, type Logger, type Pool } from "khb_common";
|
||||
import { ADMIN, AccessError, canRead, resolveCaller, scopeSql, type Caller } from "./access.js";
|
||||
import { PaveError, type JtApi, type JtTask, type TaskWrite } from "./jt.js";
|
||||
import {
|
||||
ageDate, controlDue, defaultDue, desiredName, ensureControlPrefix, guessKind, isClosed, stripStatusSuffix,
|
||||
withKeepConfirmed, withReviewLine, type TodoKind,
|
||||
} from "./rules.js";
|
||||
import type { TodoServiceSettings } from "./settings.js";
|
||||
|
||||
export interface CoreDeps {
|
||||
pool: Pool;
|
||||
jt: JtApi;
|
||||
settings: TodoServiceSettings;
|
||||
tz: string;
|
||||
log: Logger;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
export class HttpError extends Error {
|
||||
constructor(readonly status: number, message: string) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface TodoView {
|
||||
id: string;
|
||||
jobId: string | null;
|
||||
jobName: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
assignees: { id: string; name: string | null }[];
|
||||
dueDate: string | null;
|
||||
progress: number | null;
|
||||
status: "open" | "done" | "deleted";
|
||||
kind: TodoKind;
|
||||
reviewDate: string | null;
|
||||
keepConfirmed: boolean;
|
||||
doneFlag: boolean;
|
||||
overdueFlag: boolean;
|
||||
createdByKind: string;
|
||||
createdBy: string | null;
|
||||
createdAt: string | null;
|
||||
links: { id: string; type: string; role: "control" | "executor"; taskId: string; status: string; controlDue: string | null }[];
|
||||
}
|
||||
|
||||
export type WriteResult =
|
||||
| { status: "done"; id?: string; todo?: TodoView | null; result?: unknown }
|
||||
| { status: "queued"; requestId: string };
|
||||
|
||||
export interface ListFilters {
|
||||
assignee?: string; // membership id или "me"
|
||||
job?: string;
|
||||
kind?: TodoKind;
|
||||
status?: "open" | "done" | "all";
|
||||
dueBefore?: string;
|
||||
reviewDue?: boolean;
|
||||
q?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}
|
||||
|
||||
const SELECT_VIEW = `
|
||||
select i.task_id, i.job_id, j.name as job_name, i.name, i.description, i.assignee_ids,
|
||||
to_char(i.end_date, 'YYYY-MM-DD') as due_date, i.progress::float8 as progress, i.is_deleted,
|
||||
to_char(i.jt_created_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') as created_at,
|
||||
coalesce(e.kind, 'todo') as kind, to_char(e.review_date, 'YYYY-MM-DD') as review_date,
|
||||
coalesce(e.keep_confirmed, false) as keep_confirmed, coalesce(e.done_flag, false) as done_flag,
|
||||
coalesce(e.overdue_flag, false) as overdue_flag, coalesce(e.created_by_kind, 'unknown') as created_by_kind, e.created_by
|
||||
from todo_item i
|
||||
left join todo_ext e on e.task_id = i.task_id
|
||||
left join jt_job j on j.id = i.job_id`;
|
||||
|
||||
export class TodoCore {
|
||||
constructor(private readonly d: CoreDeps) {}
|
||||
|
||||
now(): Date {
|
||||
return (this.d.now ?? (() => new Date()))();
|
||||
}
|
||||
today(): string {
|
||||
return localDate(this.now(), this.d.tz);
|
||||
}
|
||||
|
||||
async nonWorkdays(): Promise<ReadonlySet<string>> {
|
||||
const { rows } = await this.d.pool.query("select to_char(day, 'YYYY-MM-DD') as d from calendar_day where not is_workday");
|
||||
return new Set(rows.map((r) => String(r.d)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- приём из JobTread (одна сторона: JobTread -> Supabase)
|
||||
|
||||
/** Сохраняет состояние задачи JobTread. Не-todo пропускаются (и снимаются, если были). */
|
||||
async upsertTask(t: JtTask, eventAt?: string | null): Promise<void> {
|
||||
if (!t.isToDo) {
|
||||
await this.markDeleted(t.id);
|
||||
return;
|
||||
}
|
||||
await this.d.pool.query(
|
||||
`insert into todo_item (task_id, job_id, name, description, assignee_ids, start_date, end_date, progress, is_deleted, jt_created_at, last_event_at, synced_at)
|
||||
values ($1,$2,$3,$4,$5,$6,$7,$8,false,$9,$10,now())
|
||||
on conflict (task_id) do update set job_id = $2, name = $3, description = $4, assignee_ids = $5, start_date = $6, end_date = $7,
|
||||
progress = $8, is_deleted = false, jt_created_at = coalesce(todo_item.jt_created_at, $9),
|
||||
last_event_at = coalesce($10, todo_item.last_event_at), synced_at = now()`,
|
||||
[t.id, t.jobId, t.name, t.description, t.assigneeIds, t.startDate, t.endDate, t.progress, t.createdAt, eventAt ?? null],
|
||||
);
|
||||
await this.reconcile(t.id);
|
||||
}
|
||||
|
||||
async markDeleted(id: string): Promise<void> {
|
||||
await this.d.pool.query("update todo_item set is_deleted = true, synced_at = now() where task_id = $1", [id]);
|
||||
}
|
||||
|
||||
/** Подтягивает задачу из JobTread (по требованию или после пропущенных событий). */
|
||||
async syncTask(id: string): Promise<boolean> {
|
||||
const t = await this.d.jt.getTask(id);
|
||||
if (!t) {
|
||||
await this.markDeleted(id);
|
||||
return false;
|
||||
}
|
||||
await this.upsertTask(t);
|
||||
return t.isToDo;
|
||||
}
|
||||
|
||||
/** Тело вебхука JobTread (createdEvent с data.next / data.previous; при изменении - только изменённые поля). */
|
||||
async applyWebhook(body: unknown): Promise<{ handled: boolean; taskId?: string; type?: string }> {
|
||||
const ev = (body as { createdEvent?: { type?: string; createdAt?: string; task?: { id?: string } | null; data?: { next?: Record<string, unknown> | null; previous?: Record<string, unknown> | null } } })?.createdEvent;
|
||||
const type = ev?.type;
|
||||
if (!ev || !type || !type.startsWith("task")) return { handled: false, type };
|
||||
const next = ev.data?.next ?? null;
|
||||
const prev = ev.data?.previous ?? null;
|
||||
const taskId = String(ev.task?.id ?? next?.id ?? prev?.id ?? "");
|
||||
if (!taskId) return { handled: false, type };
|
||||
if (type === "taskDeleted") {
|
||||
await this.markDeleted(taskId);
|
||||
return { handled: true, taskId, type };
|
||||
}
|
||||
const at = ev.createdAt ?? null;
|
||||
const known = await this.d.pool.query("select *, to_char(start_date, 'YYYY-MM-DD') as sd, to_char(end_date, 'YYYY-MM-DD') as ed from todo_item where task_id = $1", [taskId]);
|
||||
if (type === "taskCreated" && next) {
|
||||
await this.upsertTask({ ...fromEventState(next), createdAt: at }, at);
|
||||
} else if (known.rows[0] && next) {
|
||||
const r = known.rows[0];
|
||||
const merged: JtTask = {
|
||||
id: taskId, jobId: r.job_id, name: r.name, description: r.description, assigneeIds: r.assignee_ids,
|
||||
startDate: (r.sd as string | null) ?? null, endDate: (r.ed as string | null) ?? null, progress: r.progress == null ? null : Number(r.progress), isToDo: true,
|
||||
createdAt: r.jt_created_at ? new Date(r.jt_created_at).toISOString() : null,
|
||||
};
|
||||
const p = fromEventState({ ...next, id: taskId }, merged);
|
||||
await this.upsertTask(p, at);
|
||||
} else {
|
||||
await this.syncTask(taskId); // события об неизвестной задаче: берём полное состояние
|
||||
}
|
||||
return { handled: true, taskId, type };
|
||||
}
|
||||
|
||||
/** Полная загрузка открытых todo (старт сервиса, ручной запуск). */
|
||||
async backfill(): Promise<number> {
|
||||
const open = await this.d.jt.listOpenTodos();
|
||||
for (const t of open) await this.upsertTask(t);
|
||||
return open.length;
|
||||
}
|
||||
|
||||
/** Страховка к вебхукам: события JobTread с последней отметки, затем перечитывание задач. */
|
||||
async pollEvents(): Promise<number> {
|
||||
const cur = (await this.d.pool.query("select value from todo_sync_state where key = 'poll_cursor'")).rows[0]?.value as string | undefined;
|
||||
const since = cur ?? new Date(this.now().getTime() - 3600_000).toISOString();
|
||||
const started = this.now().toISOString();
|
||||
const events = await this.d.jt.recentTaskEvents(new Date(new Date(since).getTime() - 60_000).toISOString());
|
||||
const ids = new Set(events.map((e) => e.taskId).filter((x): x is string => !!x));
|
||||
for (const id of ids) await this.syncTask(id);
|
||||
await this.d.pool.query(
|
||||
`insert into todo_sync_state (key, value) values ('poll_cursor', $1)
|
||||
on conflict (key) do update set value = $1, updated_at = now()`,
|
||||
[started],
|
||||
);
|
||||
return ids.size;
|
||||
}
|
||||
|
||||
/** Вебхук JobTread на наш адрес: если нет - создаёт. */
|
||||
async ensureWebhook(): Promise<string | null> {
|
||||
const w = this.d.settings.webhook;
|
||||
if (!w.autoRegister || !w.publicBaseUrl || !w.secret) return null;
|
||||
const url = `${w.publicBaseUrl.replace(/\/$/, "")}/webhooks/jobtread/${w.secret}`;
|
||||
const have = (await this.d.jt.listWebhooks()).find((x) => x.url === url);
|
||||
return have ? have.id : this.d.jt.createWebhook(url);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- надстройка
|
||||
|
||||
async ensureExt(taskId: string, init: Partial<{ kind: TodoKind; createdByKind: string; createdBy: string | null }> = {}): Promise<void> {
|
||||
const item = (await this.d.pool.query("select name from todo_item where task_id = $1", [taskId])).rows[0];
|
||||
const name = String(item?.name ?? "");
|
||||
await this.d.pool.query(
|
||||
`insert into todo_ext (task_id, kind, base_name, created_by_kind, created_by) values ($1,$2,$3,$4,$5) on conflict (task_id) do nothing`,
|
||||
[taskId, init.kind ?? guessKind(name), stripStatusSuffix(name), init.createdByKind ?? "unknown", init.createdBy ?? null],
|
||||
);
|
||||
}
|
||||
|
||||
/** Приводит название Control todo к состоянию надстройки (суффиксы статуса). Человек поправил название - суффикс восстанавливается. */
|
||||
async reconcile(taskId: string): Promise<void> {
|
||||
const r = (
|
||||
await this.d.pool.query(
|
||||
`select i.name, e.kind, e.base_name, e.done_flag, e.overdue_flag from todo_item i join todo_ext e on e.task_id = i.task_id where i.task_id = $1 and e.kind = 'control' and not i.is_deleted`,
|
||||
[taskId],
|
||||
)
|
||||
).rows[0];
|
||||
if (!r) return;
|
||||
const base = stripStatusSuffix(String(r.name));
|
||||
if (base !== r.base_name) await this.d.pool.query("update todo_ext set base_name = $2, updated_at = now() where task_id = $1", [taskId, base]);
|
||||
const want = desiredName(base, { done: !!r.done_flag, overdue: !!r.overdue_flag });
|
||||
if (want !== r.name) {
|
||||
try {
|
||||
await this.d.jt.updateTask(taskId, { name: want });
|
||||
await this.d.pool.query("update todo_item set name = $2, synced_at = now() where task_id = $1", [taskId, want]);
|
||||
} catch (e) {
|
||||
this.d.log.warn({ taskId, err: String(e) }, "не удалось привести название Control todo");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- чтение
|
||||
|
||||
private async views(rows: Record<string, unknown>[]): Promise<TodoView[]> {
|
||||
if (!rows.length) return [];
|
||||
const memberIds = [...new Set(rows.flatMap((r) => r.assignee_ids as string[]))];
|
||||
const names = new Map<string, string>();
|
||||
if (memberIds.length) for (const m of (await this.d.pool.query("select id, user_name from jt_membership where id = any($1)", [memberIds])).rows) names.set(String(m.id), String(m.user_name));
|
||||
const ids = rows.map((r) => String(r.task_id));
|
||||
const links = (
|
||||
await this.d.pool.query(
|
||||
`select id, link_type, task_id, linked_task_id, status, to_char(control_due, 'YYYY-MM-DD') as control_due from todo_link where task_id = any($1) or linked_task_id = any($1)`,
|
||||
[ids],
|
||||
)
|
||||
).rows;
|
||||
return rows.map((r) => {
|
||||
const id = String(r.task_id);
|
||||
const progress = r.progress == null ? null : Number(r.progress);
|
||||
return {
|
||||
id, jobId: (r.job_id as string | null) ?? null, jobName: (r.job_name as string | null) ?? null, name: String(r.name),
|
||||
description: (r.description as string | null) ?? null,
|
||||
assignees: (r.assignee_ids as string[]).map((a) => ({ id: a, name: names.get(a) ?? null })),
|
||||
dueDate: (r.due_date as string | null) ?? null, progress,
|
||||
status: r.is_deleted ? "deleted" : isClosed(progress) ? "done" : "open",
|
||||
kind: r.kind as TodoKind, reviewDate: (r.review_date as string | null) ?? null, keepConfirmed: !!r.keep_confirmed,
|
||||
doneFlag: !!r.done_flag, overdueFlag: !!r.overdue_flag, createdByKind: String(r.created_by_kind), createdBy: (r.created_by as string | null) ?? null,
|
||||
createdAt: (r.created_at as string | null) ?? null,
|
||||
links: links
|
||||
.filter((l) => l.task_id === id || l.linked_task_id === id)
|
||||
.map((l) => ({
|
||||
id: String(l.id), type: String(l.link_type), role: l.task_id === id ? ("control" as const) : ("executor" as const),
|
||||
taskId: String(l.task_id === id ? l.linked_task_id : l.task_id), status: String(l.status), controlDue: (l.control_due as string | null) ?? null,
|
||||
})),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async list(caller: Caller, f: ListFilters = {}): Promise<TodoView[]> {
|
||||
const params: unknown[] = [];
|
||||
const where: string[] = ["not i.is_deleted", scopeSql(caller, params)];
|
||||
const add = (sql: string, v: unknown): void => {
|
||||
params.push(v);
|
||||
where.push(sql.replace("?", `$${params.length}`));
|
||||
};
|
||||
const status = f.status ?? "open";
|
||||
if (status === "open") where.push("(i.progress is null or i.progress < 1)");
|
||||
if (status === "done") where.push("i.progress >= 1");
|
||||
if (f.assignee) {
|
||||
const m = f.assignee === "me" ? caller.membershipId : f.assignee;
|
||||
if (!m) return [];
|
||||
add("? = any(i.assignee_ids)", m);
|
||||
}
|
||||
if (f.job) add("i.job_id = ?", f.job);
|
||||
if (f.kind) add("coalesce(e.kind, 'todo') = ?", f.kind);
|
||||
if (f.dueBefore) add("i.end_date <= ?::date", f.dueBefore);
|
||||
if (f.reviewDue) add("e.review_date <= ?::date", this.today());
|
||||
if (f.q) {
|
||||
params.push(f.q);
|
||||
const n = params.length;
|
||||
where.push(`(i.search @@ websearch_to_tsquery('simple', $${n}) or i.name ilike '%' || $${n} || '%' or i.description ilike '%' || $${n} || '%')`);
|
||||
}
|
||||
const limit = Math.min(Math.max(f.limit ?? 100, 1), 500);
|
||||
params.push(limit, Math.max(f.offset ?? 0, 0));
|
||||
const { rows } = await this.d.pool.query(
|
||||
`${SELECT_VIEW} where ${where.join(" and ")} order by i.end_date nulls last, i.task_id limit $${params.length - 1} offset $${params.length}`,
|
||||
params,
|
||||
);
|
||||
return this.views(rows);
|
||||
}
|
||||
|
||||
/** Одно todo; если его нет в копии - подтягивается из JobTread (ленивое создание). */
|
||||
async get(caller: Caller, id: string): Promise<TodoView> {
|
||||
let rows = (await this.d.pool.query(`${SELECT_VIEW} where i.task_id = $1`, [id])).rows;
|
||||
if (!rows[0]) {
|
||||
if (!(await this.syncTask(id).catch(() => false))) throw new HttpError(404, "todo не найдено");
|
||||
rows = (await this.d.pool.query(`${SELECT_VIEW} where i.task_id = $1`, [id])).rows;
|
||||
}
|
||||
const [v] = await this.views(rows);
|
||||
if (!v) throw new HttpError(404, "todo не найдено");
|
||||
if (!canRead(caller, { jobId: v.jobId, assigneeIds: v.assignees.map((a) => a.id) })) throw new HttpError(404, "todo не найдено");
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Открытые todo-напоминания и Control старше staleDays (дата замечания из описания, иначе создания) без "Keep confirmed". */
|
||||
async stale(caller: Caller, opts: { days?: number; personId?: string } = {}): Promise<(TodoView & { ageDate: string })[]> {
|
||||
const target = opts.personId && caller.all ? await resolveCaller(this.d.pool, opts.personId) : caller;
|
||||
const days = opts.days ?? this.d.settings.defaults.staleDays;
|
||||
const limit = addDays(this.today(), -days);
|
||||
const mine = (await this.list(target, { status: "open", assignee: target.membershipId ? "me" : undefined, limit: 500 })).filter((t) => (t.kind === "reminder" || t.kind === "control") && !t.keepConfirmed);
|
||||
return mine
|
||||
.map((t) => ({ ...t, ageDate: ageDate(t.description, t.createdAt) ?? "" }))
|
||||
.filter((t) => t.ageDate && t.ageDate <= limit);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- запись (JobTread - главный; очередь повторов до 5 минут)
|
||||
|
||||
private assertWritable(caller: Caller, jobId: string | null): void {
|
||||
if (!jobId) throw new HttpError(400, "у todo нет проекта: запись не поддерживается");
|
||||
if (!this.d.settings.allowedJobIds.includes(jobId)) throw new AccessError(`запись в проект ${jobId} не разрешена настройками сервиса`);
|
||||
if (!caller.all && !caller.jobIds.has(jobId)) throw new AccessError("нет доступа к проекту");
|
||||
}
|
||||
|
||||
/** Назначение: membership id и/или person id (через person.jt_membership_id). */
|
||||
private async membershipIds(input: { assigneeMembershipIds?: string[]; assigneePersonIds?: string[] }): Promise<string[] | undefined> {
|
||||
if (!input.assigneeMembershipIds && !input.assigneePersonIds) return undefined;
|
||||
const out = new Set(input.assigneeMembershipIds ?? []);
|
||||
if (input.assigneePersonIds?.length) {
|
||||
const { rows } = await this.d.pool.query("select id, jt_membership_id from person where id = any($1::uuid[])", [input.assigneePersonIds]);
|
||||
for (const id of input.assigneePersonIds) {
|
||||
const m = rows.find((r) => r.id === id)?.jt_membership_id as string | undefined;
|
||||
if (!m) throw new HttpError(400, `у person ${id} нет membership JobTread`);
|
||||
out.add(m);
|
||||
}
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** Идемпотентная запись: ключ, запись запроса, одна попытка сразу, при недоступности JobTread - в очередь. */
|
||||
private async runWrite(op: string, args: Record<string, unknown>, caller: Caller, key?: string): Promise<WriteResult> {
|
||||
if (key) {
|
||||
const ex = (await this.d.pool.query("select id, status, result, error from todo_request where idem_key = $1", [key])).rows[0];
|
||||
if (ex) {
|
||||
if (ex.status === "done") return { status: "done", ...(ex.result as object) } as WriteResult;
|
||||
if (ex.status === "failed") throw new HttpError(502, String(ex.error ?? "запрос не выполнен"));
|
||||
return { status: "queued", requestId: String(ex.id) };
|
||||
}
|
||||
}
|
||||
const deadline = new Date(this.now().getTime() + this.d.settings.defaults.requestDeadlineSeconds * 1000);
|
||||
const ins = await this.d.pool.query(
|
||||
`insert into todo_request (idem_key, op, args, caller, deadline, next_attempt_at) values ($1,$2,$3,$4,$5, now() + interval '30 seconds')
|
||||
on conflict (idem_key) do nothing returning id`,
|
||||
[key ?? null, op, args, caller.personId ?? caller.name, deadline],
|
||||
);
|
||||
if (!ins.rows[0]) return this.runWrite(op, args, caller, key); // гонка по ключу
|
||||
const id = String(ins.rows[0].id);
|
||||
return this.attempt(id, op, args, null);
|
||||
}
|
||||
|
||||
private async attempt(id: string, op: string, args: Record<string, unknown>, partial: unknown): Promise<WriteResult> {
|
||||
try {
|
||||
const result = await this.exec(id, op, args, partial);
|
||||
await this.d.pool.query("update todo_request set status = 'done', result = $2, attempts = attempts + 1, updated_at = now() where id = $1", [id, result]);
|
||||
return { status: "done", ...(result as object) } as WriteResult;
|
||||
} catch (e) {
|
||||
if (e instanceof PaveError && e.retryable) {
|
||||
await this.d.pool.query(
|
||||
"update todo_request set attempts = attempts + 1, error = $2, next_attempt_at = now() + interval '5 seconds', updated_at = now() where id = $1",
|
||||
[id, e.message],
|
||||
);
|
||||
return { status: "queued", requestId: id };
|
||||
}
|
||||
await this.d.pool.query("update todo_request set status = 'failed', error = $2, attempts = attempts + 1, updated_at = now() where id = $1", [id, e instanceof Error ? e.message : String(e)]);
|
||||
throw e instanceof HttpError || e instanceof AccessError ? e : new HttpError(502, e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
/** Фоновая обработка очереди: повтор до дедлайна, после - failed и событие write_failed автору. */
|
||||
async processRequests(): Promise<number> {
|
||||
const { rows } = await this.d.pool.query(
|
||||
`update todo_request set next_attempt_at = now() + interval '30 seconds'
|
||||
where id in (select id from todo_request where status = 'pending' and next_attempt_at <= now() order by next_attempt_at limit 10 for update skip locked)
|
||||
returning id, op, args, result, deadline, caller`,
|
||||
);
|
||||
for (const r of rows) {
|
||||
if (new Date(r.deadline) < this.now()) {
|
||||
await this.d.pool.query("update todo_request set status = 'failed', error = coalesce(error, '') || ' (истёк срок повторов)', updated_at = now() where id = $1", [r.id]);
|
||||
const person = /^[0-9a-f-]{36}$/.test(String(r.caller)) ? String(r.caller) : null;
|
||||
await this.d.pool.query("insert into todo_event (event_type, person_id, payload) values ('write_failed', $1, $2)", [person, { requestId: r.id, op: r.op }]);
|
||||
continue;
|
||||
}
|
||||
await this.attempt(String(r.id), String(r.op), r.args as Record<string, unknown>, r.result).catch((e) => this.d.log.warn({ id: r.id, err: String(e) }, "запрос не выполнен"));
|
||||
}
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
async request(caller: Caller, id: string): Promise<{ id: string; op: string; status: string; result: unknown; error: string | null }> {
|
||||
const r = (await this.d.pool.query("select id, op, status, result, error, caller from todo_request where id = $1", [id])).rows[0];
|
||||
if (!r || (!caller.all && r.caller !== caller.personId)) throw new HttpError(404, "запрос не найден");
|
||||
return { id: String(r.id), op: String(r.op), status: String(r.status), result: r.result, error: r.error };
|
||||
}
|
||||
|
||||
private async exec(requestId: string, op: string, a: Record<string, unknown>, partial: unknown): Promise<unknown> {
|
||||
switch (op) {
|
||||
case "create": return this.execCreate(a);
|
||||
case "update": return this.execUpdate(a);
|
||||
case "delete": {
|
||||
await this.d.jt.deleteTask(String(a.id));
|
||||
await this.markDeleted(String(a.id));
|
||||
return { id: String(a.id) };
|
||||
}
|
||||
case "control": return this.execControl(requestId, a, (partial ?? {}) as { executorTaskId?: string; controlTaskId?: string });
|
||||
default: throw new Error(`неизвестная операция ${op}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async execCreate(a: Record<string, unknown>): Promise<{ id: string }> {
|
||||
const t = await this.d.jt.createTask({
|
||||
jobId: String(a.jobId), name: String(a.name), description: (a.description as string | undefined) ?? undefined,
|
||||
endDate: String(a.due), assignedMembershipIds: a.assignees as string[] | undefined,
|
||||
});
|
||||
await this.upsertTask(t, null);
|
||||
await this.ensureExt(t.id, { kind: a.kind as TodoKind, createdByKind: String(a.createdByKind ?? "unknown"), createdBy: (a.createdBy as string | undefined) ?? null });
|
||||
if (a.reviewDate) await this.d.pool.query("update todo_ext set review_date = $2 where task_id = $1", [t.id, a.reviewDate]);
|
||||
return { id: t.id };
|
||||
}
|
||||
|
||||
private async execUpdate(a: Record<string, unknown>): Promise<{ id: string }> {
|
||||
const id = String(a.id);
|
||||
const patch = a.patch as TaskWrite;
|
||||
if (Object.keys(patch).length) {
|
||||
await this.d.jt.updateTask(id, patch);
|
||||
const fresh = await this.d.jt.getTask(id);
|
||||
if (fresh) await this.upsertTask(fresh, null);
|
||||
}
|
||||
return { id };
|
||||
}
|
||||
|
||||
private async execControl(requestId: string, a: Record<string, unknown>, done: { executorTaskId?: string; controlTaskId?: string }): Promise<unknown> {
|
||||
const save = (): Promise<unknown> => this.d.pool.query("update todo_request set result = $2 where id = $1", [requestId, done]);
|
||||
const ex = a.executor as { name: string; description?: string; assignees?: string[]; due: string; kind: TodoKind };
|
||||
const ct = a.controller as { name: string; description?: string; personId: string; membershipId: string; due: string };
|
||||
const jobId = String(a.jobId);
|
||||
if (!done.executorTaskId) {
|
||||
const t = await this.d.jt.createTask({ jobId, name: ex.name, description: ex.description, endDate: ex.due, assignedMembershipIds: ex.assignees });
|
||||
await this.upsertTask(t, null);
|
||||
await this.ensureExt(t.id, { kind: ex.kind, createdByKind: String(a.createdByKind ?? "agent"), createdBy: (a.createdBy as string | undefined) ?? null });
|
||||
done.executorTaskId = t.id;
|
||||
await save();
|
||||
}
|
||||
if (!done.controlTaskId) {
|
||||
const t = await this.d.jt.createTask({ jobId, name: ct.name, description: ct.description, endDate: ct.due, assignedMembershipIds: [ct.membershipId] });
|
||||
await this.upsertTask(t, null);
|
||||
await this.ensureExt(t.id, { kind: "control", createdByKind: String(a.createdByKind ?? "agent"), createdBy: (a.createdBy as string | undefined) ?? null });
|
||||
done.controlTaskId = t.id;
|
||||
await save();
|
||||
}
|
||||
await this.d.pool.query(
|
||||
`insert into todo_link (task_id, linked_task_id, controller_person_id, executor_name, control_due)
|
||||
values ($1,$2,$3,$4,$5) on conflict (link_type, task_id) do nothing`,
|
||||
[done.controlTaskId, done.executorTaskId, ct.personId, ex.name, ct.due],
|
||||
);
|
||||
return { id: done.controlTaskId, controlTaskId: done.controlTaskId, executorTaskId: done.executorTaskId, executorDue: ex.due, controlDue: ct.due };
|
||||
}
|
||||
|
||||
async create(
|
||||
caller: Caller,
|
||||
i: {
|
||||
jobId: string; name: string; description?: string; due?: string; assigneeMembershipIds?: string[]; assigneePersonIds?: string[];
|
||||
kind?: TodoKind; reviewDate?: string; createdBy?: string; createdByKind?: "human" | "agent" | "automation";
|
||||
},
|
||||
key?: string,
|
||||
): Promise<WriteResult> {
|
||||
if (!i.name?.trim()) throw new HttpError(400, "нужно name");
|
||||
this.assertWritable(caller, i.jobId);
|
||||
const kind = i.kind ?? guessKind(i.name);
|
||||
const name = kind === "control" ? ensureControlPrefix(i.name) : i.name.trim();
|
||||
const due = i.due ?? defaultDue(this.today(), this.d.settings.defaults.dueWorkdays, await this.nonWorkdays());
|
||||
const assignees = await this.membershipIds(i);
|
||||
return this.runWrite(
|
||||
"create",
|
||||
{ jobId: i.jobId, name, description: i.description, due, assignees, kind, reviewDate: i.reviewDate, createdByKind: i.createdByKind ?? (caller.kind === "person" ? "agent" : "automation"), createdBy: i.createdBy ?? caller.name },
|
||||
caller,
|
||||
key,
|
||||
);
|
||||
}
|
||||
|
||||
/** Пара Control: todo исполнителю (срок по умолчанию 3 рабочих дня) и Control todo контролёру (срок + 2 дня, название с "Control:"). */
|
||||
async createControl(
|
||||
caller: Caller,
|
||||
i: {
|
||||
jobId: string; controllerPersonId: string;
|
||||
executor: { name: string; description?: string; due?: string; assigneeMembershipIds?: string[]; assigneePersonIds?: string[] };
|
||||
control: { name: string; description?: string };
|
||||
createdBy?: string;
|
||||
},
|
||||
key?: string,
|
||||
): Promise<WriteResult> {
|
||||
if (!i.executor?.name?.trim() || !i.control?.name?.trim()) throw new HttpError(400, "нужны executor.name и control.name");
|
||||
this.assertWritable(caller, i.jobId);
|
||||
const ctl = (await this.d.pool.query("select jt_membership_id from person where id = $1 and is_active", [i.controllerPersonId])).rows[0];
|
||||
if (!ctl?.jt_membership_id) throw new HttpError(400, "у контролёра нет person или membership JobTread");
|
||||
const execDue = i.executor.due ?? defaultDue(this.today(), this.d.settings.defaults.dueWorkdays, await this.nonWorkdays());
|
||||
const assignees = await this.membershipIds(i.executor);
|
||||
if (!assignees?.length) throw new HttpError(400, "нужен исполнитель (assigneeMembershipIds или assigneePersonIds)");
|
||||
const exName = i.executor.name.trim();
|
||||
return this.runWrite(
|
||||
"control",
|
||||
{
|
||||
jobId: i.jobId, createdBy: i.createdBy ?? caller.name, createdByKind: caller.kind === "person" ? "agent" : "automation",
|
||||
executor: { name: exName, description: i.executor.description, assignees, due: execDue, kind: guessKind(exName) === "reminder" ? "reminder" : "todo" },
|
||||
controller: {
|
||||
name: ensureControlPrefix(i.control.name), description: i.control.description, personId: i.controllerPersonId,
|
||||
membershipId: String(ctl.jt_membership_id), due: controlDue(execDue, this.d.settings.defaults.controlOffsetDays),
|
||||
},
|
||||
},
|
||||
caller,
|
||||
key,
|
||||
);
|
||||
}
|
||||
|
||||
async update(
|
||||
caller: Caller,
|
||||
id: string,
|
||||
p: { name?: string; description?: string | null; due?: string | null; assigneeMembershipIds?: string[]; assigneePersonIds?: string[]; kind?: TodoKind; reviewDate?: string | null },
|
||||
key?: string,
|
||||
): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
const patch: TaskWrite = {};
|
||||
const ext: { kind?: TodoKind; reviewDate?: string | null } = {};
|
||||
if (p.kind !== undefined) ext.kind = p.kind;
|
||||
if (p.reviewDate !== undefined) ext.reviewDate = p.reviewDate;
|
||||
const jtTouched = p.name !== undefined || p.description !== undefined || p.due !== undefined || p.assigneeMembershipIds || p.assigneePersonIds;
|
||||
if (jtTouched || ext.reviewDate !== undefined) this.assertWritable(caller, cur.jobId);
|
||||
if (p.name !== undefined) {
|
||||
if (!p.name.trim()) throw new HttpError(400, "пустое name");
|
||||
patch.name = cur.kind === "control" || p.kind === "control" ? desiredName(ensureControlPrefix(p.name), { done: cur.doneFlag, overdue: cur.overdueFlag }) : p.name.trim();
|
||||
}
|
||||
if (p.description !== undefined) patch.description = p.description;
|
||||
if (p.due !== undefined) patch.endDate = p.due;
|
||||
const assignees = await this.membershipIds(p);
|
||||
if (assignees) patch.assignedMembershipIds = assignees;
|
||||
await this.ensureExt(id);
|
||||
if (ext.kind) await this.d.pool.query("update todo_ext set kind = $2, updated_at = now() where task_id = $1", [id, ext.kind]);
|
||||
if (ext.reviewDate !== undefined) {
|
||||
await this.d.pool.query("update todo_ext set review_date = $2, review_notified_for = null, updated_at = now() where task_id = $1", [id, ext.reviewDate]);
|
||||
if (this.d.settings.defaults.reviewLine && patch.description === undefined) patch.description = withReviewLine(cur.description, ext.reviewDate);
|
||||
}
|
||||
if (!Object.keys(patch).length) return { status: "done", id, todo: await this.get(caller, id) };
|
||||
const r = await this.runWrite("update", { id, patch }, caller, key);
|
||||
return r.status === "done" ? { ...r, id, todo: await this.get(caller, id) } : r;
|
||||
}
|
||||
|
||||
async close(caller: Caller, id: string, key?: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
return this.runWrite("update", { id, patch: { progress: 1 } }, caller, key).then(async (r) => (r.status === "done" ? { ...r, id, todo: await this.get(caller, id) } : r));
|
||||
}
|
||||
|
||||
async reopen(caller: Caller, id: string, key?: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
return this.runWrite("update", { id, patch: { progress: 0 } }, caller, key).then(async (r) => (r.status === "done" ? { ...r, id, todo: await this.get(caller, id) } : r));
|
||||
}
|
||||
|
||||
async remove(caller: Caller, id: string, key?: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
return this.runWrite("delete", { id }, caller, key);
|
||||
}
|
||||
|
||||
/** Отложить: review_date - до даты (until) или через days календарных дней. Только надстройка (и строка Review в описании, если включена). */
|
||||
async snooze(caller: Caller, id: string, o: { until?: string; days?: number }): Promise<WriteResult> {
|
||||
const until = o.until ?? (o.days != null ? addDays(this.today(), o.days) : null);
|
||||
if (!until || !/^\d{4}-\d{2}-\d{2}$/.test(until)) throw new HttpError(400, "нужен until (YYYY-MM-DD) или days");
|
||||
return this.update(caller, id, { reviewDate: until });
|
||||
}
|
||||
|
||||
/** "Keep confirmed": флаг в надстройке и строка в описании. */
|
||||
async keep(caller: Caller, id: string): Promise<WriteResult> {
|
||||
const cur = await this.get(caller, id);
|
||||
this.assertWritable(caller, cur.jobId);
|
||||
await this.ensureExt(id);
|
||||
await this.d.pool.query("update todo_ext set keep_confirmed = true, updated_at = now() where task_id = $1", [id]);
|
||||
const desc = withKeepConfirmed(cur.description, this.today());
|
||||
if (desc === cur.description) return { status: "done", id, todo: await this.get(caller, id) };
|
||||
const r = await this.runWrite("update", { id, patch: { description: desc } }, caller);
|
||||
return r.status === "done" ? { ...r, id, todo: await this.get(caller, id) } : r;
|
||||
}
|
||||
|
||||
/** Закрыть пачкой (ответ "close" на вопрос про todo старше 3 недель). */
|
||||
async closeMany(caller: Caller, ids: string[]): Promise<{ id: string; status: string; error?: string }[]> {
|
||||
const out: { id: string; status: string; error?: string }[] = [];
|
||||
for (const id of ids.slice(0, 50)) {
|
||||
try {
|
||||
out.push({ id, status: (await this.close(caller, id)).status });
|
||||
} catch (e) {
|
||||
out.push({ id, status: "error", error: e instanceof Error ? e.message : String(e) });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- события для агентов
|
||||
|
||||
async events(caller: Caller, o: { personId?: string; afterId?: number; pending?: boolean; limit?: number }): Promise<Record<string, unknown>[]> {
|
||||
const person = caller.all ? o.personId : caller.personId;
|
||||
const params: unknown[] = [o.afterId ?? 0];
|
||||
let sql = "select id, created_at, event_type, task_id, person_id, payload, delivered_at from todo_event where id > $1";
|
||||
if (person) {
|
||||
params.push(person);
|
||||
sql += ` and person_id = $${params.length}`;
|
||||
} else if (!caller.all) return [];
|
||||
if (o.pending) sql += " and delivered_at is null";
|
||||
params.push(Math.min(o.limit ?? 100, 500));
|
||||
sql += ` order by id limit $${params.length}`;
|
||||
return (await this.d.pool.query(sql, params)).rows;
|
||||
}
|
||||
|
||||
async ackEvents(caller: Caller, ids: number[]): Promise<number> {
|
||||
const r = caller.all
|
||||
? await this.d.pool.query("update todo_event set delivered_at = now() where id = any($1::bigint[]) and delivered_at is null", [ids])
|
||||
: await this.d.pool.query("update todo_event set delivered_at = now() where id = any($1::bigint[]) and delivered_at is null and person_id = $2", [ids, caller.personId]);
|
||||
return r.rowCount ?? 0;
|
||||
}
|
||||
|
||||
async links(caller: Caller, id: string): Promise<TodoView["links"]> {
|
||||
return (await this.get(caller, id)).links;
|
||||
}
|
||||
}
|
||||
|
||||
/** Состояние задачи из события JobTread; при изменении приходят только изменённые поля - остальные берутся из base. */
|
||||
function fromEventState(s: Record<string, unknown>, base?: JtTask): JtTask {
|
||||
const has = (k: string): boolean => Object.prototype.hasOwnProperty.call(s, k);
|
||||
const pick = <T>(k: string, fallback: T): T => (has(k) ? (s[k] as T) : fallback);
|
||||
return {
|
||||
id: String(s.id ?? base?.id ?? ""),
|
||||
jobId: pick<string | null>("jobId", base?.jobId ?? null),
|
||||
name: pick<string>("name", base?.name ?? ""),
|
||||
description: pick<string | null>("description", base?.description ?? null),
|
||||
assigneeIds: pick<string[]>("assignedMembershipIds", base?.assigneeIds ?? []),
|
||||
startDate: pick<string | null>("startDate", base?.startDate ?? null),
|
||||
endDate: pick<string | null>("endDate", base?.endDate ?? null),
|
||||
progress: pick<number | null>("progress", base?.progress ?? null),
|
||||
isToDo: pick<boolean>("isToDo", base?.isToDo ?? true),
|
||||
createdAt: base?.createdAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export { ADMIN };
|
||||
159
packages/todo_service/src/http-api.ts
Normal file
159
packages/todo_service/src/http-api.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import Fastify, { type FastifyInstance, type FastifyRequest } from "fastify";
|
||||
import type { Pool } from "khb_common";
|
||||
import { AccessError, type Caller } from "./access.js";
|
||||
import { Auth, safeEqual } from "./auth.js";
|
||||
import { HttpError, type ListFilters, type TodoCore, type WriteResult } from "./core.js";
|
||||
import { handleMcpMessage } from "./mcp.js";
|
||||
import type { TodoServiceSettings } from "./settings.js";
|
||||
import type { Watchers } from "./watchers.js";
|
||||
|
||||
export interface ApiDeps {
|
||||
pool: Pool;
|
||||
core: TodoCore;
|
||||
watchers: Watchers;
|
||||
settings: TodoServiceSettings;
|
||||
auth: Auth;
|
||||
}
|
||||
|
||||
type Q = Record<string, string | undefined>;
|
||||
type B = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
const { core, settings } = deps;
|
||||
const app = Fastify({ bodyLimit: 1_000_000 });
|
||||
|
||||
const caller = (req: FastifyRequest): Promise<Caller> => deps.auth.internal(req.headers.authorization, one(req.headers["x-caller-person"]));
|
||||
const one = (h: string | string[] | undefined): string | undefined => (Array.isArray(h) ? h[0] : h);
|
||||
const key = (req: FastifyRequest): string | undefined => one(req.headers["idempotency-key"]);
|
||||
const reply202 = (r: WriteResult): { code: number; body: WriteResult } => ({ code: r.status === "queued" ? 202 : 200, body: r });
|
||||
|
||||
app.setErrorHandler((e: Error & { statusCode?: number }, _req, reply) => {
|
||||
if (e instanceof AccessError || e instanceof HttpError) return reply.code(e instanceof AccessError ? e.status : e.status).send({ error: e.message });
|
||||
if (e.statusCode && e.statusCode < 500) return reply.code(e.statusCode).send({ error: e.message });
|
||||
return reply.code(500).send({ error: e.message });
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => {
|
||||
let db = false;
|
||||
try {
|
||||
await deps.pool.query("select 1");
|
||||
db = true;
|
||||
} catch {
|
||||
/* db=false */
|
||||
}
|
||||
return { ok: db, db, time: new Date().toISOString() };
|
||||
});
|
||||
|
||||
// --- приём вебхуков JobTread: секрет в пути (подписи у JobTread нет)
|
||||
app.post<{ Params: { secret: string }; Body: unknown }>("/webhooks/jobtread/:secret", async (req, reply) => {
|
||||
const secret = settings.webhook.secret;
|
||||
if (!secret || !safeEqual(req.params.secret, secret)) return reply.code(404).send({ error: "not found" });
|
||||
try {
|
||||
const r = await core.applyWebhook(req.body);
|
||||
return reply.code(202).send(r);
|
||||
} catch (e) {
|
||||
req.log.error({ err: String(e) }, "вебхук не обработан (опрос подберёт изменение)");
|
||||
return reply.code(202).send({ handled: false });
|
||||
}
|
||||
});
|
||||
|
||||
// --- todo
|
||||
app.get<{ Querystring: Q }>("/todos", async (req) => {
|
||||
const q = req.query;
|
||||
const f: ListFilters = {
|
||||
assignee: q.assignee, job: q.job, kind: q.kind as ListFilters["kind"], status: q.status as ListFilters["status"], dueBefore: q.due_before,
|
||||
reviewDue: q.review_due === "1" || q.review_due === "true", q: q.q, limit: q.limit ? Number(q.limit) : undefined, offset: q.offset ? Number(q.offset) : undefined,
|
||||
};
|
||||
return core.list(await caller(req), f);
|
||||
});
|
||||
app.get<{ Querystring: Q }>("/todos/stale", async (req) => core.stale(await caller(req), { personId: req.query.person, days: req.query.days ? Number(req.query.days) : undefined }));
|
||||
app.post<{ Body: B }>("/todos/close-batch", async (req) => core.closeMany(await caller(req), (req.body?.ids as string[]) ?? []));
|
||||
app.get<{ Params: { id: string } }>("/todos/:id", async (req) => core.get(await caller(req), req.params.id));
|
||||
app.get<{ Params: { id: string } }>("/todos/:id/links", async (req) => core.links(await caller(req), req.params.id));
|
||||
|
||||
app.post<{ Body: B }>("/todos", async (req, reply) => {
|
||||
const r = reply202(await core.create(await caller(req), req.body as never, key(req)));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.patch<{ Params: { id: string }; Body: B }>("/todos/:id", async (req, reply) => {
|
||||
const r = reply202(await core.update(await caller(req), req.params.id, (req.body ?? {}) as never, key(req)));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.delete<{ Params: { id: string } }>("/todos/:id", async (req, reply) => {
|
||||
const r = reply202(await core.remove(await caller(req), req.params.id, key(req)));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.post<{ Params: { id: string } }>("/todos/:id/close", async (req, reply) => {
|
||||
const r = reply202(await core.close(await caller(req), req.params.id, key(req)));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.post<{ Params: { id: string } }>("/todos/:id/reopen", async (req, reply) => {
|
||||
const r = reply202(await core.reopen(await caller(req), req.params.id, key(req)));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.post<{ Params: { id: string }; Body: B }>("/todos/:id/snooze", async (req, reply) => {
|
||||
const r = reply202(await core.snooze(await caller(req), req.params.id, { until: req.body?.until, days: req.body?.days }));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.post<{ Params: { id: string } }>("/todos/:id/keep", async (req, reply) => {
|
||||
const r = reply202(await core.keep(await caller(req), req.params.id));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
app.post<{ Body: B }>("/control", async (req, reply) => {
|
||||
const r = reply202(await core.createControl(await caller(req), req.body as never, key(req)));
|
||||
return reply.code(r.code).send(r.body);
|
||||
});
|
||||
|
||||
app.get<{ Params: { id: string } }>("/requests/:id", async (req) => core.request(await caller(req), req.params.id));
|
||||
|
||||
// --- события для агентов
|
||||
app.get<{ Querystring: Q }>("/events", async (req) =>
|
||||
core.events(await caller(req), { personId: req.query.person, afterId: req.query.after ? Number(req.query.after) : undefined, pending: req.query.pending === "1" }),
|
||||
);
|
||||
app.post<{ Body: B }>("/events/ack", async (req) => ({ acked: await core.ackEvents(await caller(req), ((req.body?.ids as number[]) ?? []).map(Number)) }));
|
||||
|
||||
// --- служебное (только внутренний токен без person)
|
||||
app.post("/admin/sync", async (req) => {
|
||||
const c = await caller(req);
|
||||
if (!c.all || c.kind !== "admin") throw new AccessError("только администратор");
|
||||
return { backfilled: await core.backfill(), polled: await core.pollEvents() };
|
||||
});
|
||||
app.post("/admin/webhook", async (req) => {
|
||||
const c = await caller(req);
|
||||
if (!c.all || c.kind !== "admin") throw new AccessError("только администратор");
|
||||
return { webhookId: await core.ensureWebhook() };
|
||||
});
|
||||
app.post("/admin/tick", async (req) => {
|
||||
const c = await caller(req);
|
||||
if (!c.all || c.kind !== "admin") throw new AccessError("только администратор");
|
||||
return { control: await deps.watchers.controlTick(), review: await deps.watchers.reviewTick(), requests: await core.processRequests(), delivered: await deps.watchers.deliverEvents() };
|
||||
});
|
||||
|
||||
// --- MCP (Streamable HTTP, без сессий)
|
||||
if (settings.mcp.enabled) {
|
||||
const base = settings.mcp.publicUrl?.replace(/\/$/, "");
|
||||
app.get("/.well-known/oauth-protected-resource", async (_req, reply) => {
|
||||
if (!base) return reply.code(404).send({ error: "not configured" });
|
||||
return { resource: `${base}/mcp`, ...(settings.mcp.issuer ? { authorization_servers: [settings.mcp.issuer] } : {}), bearer_methods_supported: ["header"] };
|
||||
});
|
||||
app.get("/mcp", async (_req, reply) => reply.code(405).header("allow", "POST").send({ error: "use POST" }));
|
||||
app.delete("/mcp", async (_req, reply) => reply.code(405).send({ error: "no sessions" }));
|
||||
app.post<{ Body: unknown }>("/mcp", async (req, reply) => {
|
||||
let c: Caller;
|
||||
try {
|
||||
c = await deps.auth.mcp(req.headers.authorization, one(req.headers["x-caller-person"]));
|
||||
} catch (e) {
|
||||
if (e instanceof AccessError && e.status === 401 && base) reply.header("www-authenticate", `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource"`);
|
||||
throw e;
|
||||
}
|
||||
const body = req.body;
|
||||
if (Array.isArray(body)) {
|
||||
const out = (await Promise.all(body.map((m) => handleMcpMessage(core, c, m as never)))).filter((x) => x);
|
||||
return out.length ? out : reply.code(202).send();
|
||||
}
|
||||
const res = await handleMcpMessage(core, c, (body ?? {}) as never);
|
||||
return res ?? reply.code(202).send();
|
||||
});
|
||||
}
|
||||
return app;
|
||||
}
|
||||
200
packages/todo_service/src/jt.ts
Normal file
200
packages/todo_service/src/jt.ts
Normal file
@@ -0,0 +1,200 @@
|
||||
/** Клиент JobTread Pave API для todo: чтение, создание, изменение, удаление задач, вебхуки. */
|
||||
|
||||
export class PaveError extends Error {
|
||||
constructor(message: string, readonly retryable = false) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface JtTask {
|
||||
id: string;
|
||||
jobId: string | null;
|
||||
name: string;
|
||||
description: string | null;
|
||||
assigneeIds: string[];
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
progress: number | null;
|
||||
isToDo: boolean;
|
||||
createdAt: string | null;
|
||||
}
|
||||
|
||||
export interface JtClientOpts {
|
||||
grantKey: string;
|
||||
organizationId: string;
|
||||
endpoint?: string;
|
||||
fetchFn?: typeof fetch;
|
||||
}
|
||||
|
||||
const TASK_FIELDS = {
|
||||
id: {}, name: {}, description: {}, startDate: {}, endDate: {}, progress: {}, isToDo: {}, createdAt: {},
|
||||
job: { id: {} }, assignedMemberships: { nodes: { id: {} } },
|
||||
};
|
||||
|
||||
interface RawTask {
|
||||
id: string; name: string; description: string | null; startDate: string | null; endDate: string | null;
|
||||
progress: number | null; isToDo: boolean; createdAt: string | null;
|
||||
job: { id: string } | null; assignedMemberships?: { nodes: { id: string }[] };
|
||||
}
|
||||
|
||||
export function mapRawTask(t: RawTask): JtTask {
|
||||
return {
|
||||
id: t.id, jobId: t.job?.id ?? null, name: t.name, description: t.description ?? null,
|
||||
assigneeIds: (t.assignedMemberships?.nodes ?? []).map((m) => m.id), startDate: t.startDate ?? null, endDate: t.endDate ?? null,
|
||||
progress: t.progress ?? null, isToDo: !!t.isToDo, createdAt: t.createdAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface TaskWrite {
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
/** Срок (YYYY-MM-DD). У todo startDate всегда равен endDate: JobTread не даёт задать их отдельно. */
|
||||
endDate?: string | null;
|
||||
progress?: number | null;
|
||||
assignedMembershipIds?: string[];
|
||||
}
|
||||
|
||||
export interface JtEventRef {
|
||||
id: string;
|
||||
type: string;
|
||||
createdAt: string;
|
||||
taskId: string | null;
|
||||
}
|
||||
|
||||
/** Что нужно сервису от JobTread; в тестах подменяется. */
|
||||
export interface JtApi {
|
||||
organizationId: string;
|
||||
getTask(id: string): Promise<JtTask | null>;
|
||||
listOpenTodos(): Promise<JtTask[]>;
|
||||
createTask(args: { jobId: string; name: string } & TaskWrite): Promise<JtTask>;
|
||||
updateTask(id: string, patch: TaskWrite): Promise<void>;
|
||||
deleteTask(id: string): Promise<void>;
|
||||
recentTaskEvents(sinceIso: string): Promise<JtEventRef[]>;
|
||||
listWebhooks(): Promise<{ id: string; url: string }[]>;
|
||||
createWebhook(url: string): Promise<string>;
|
||||
deleteWebhook(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
export class PaveJt implements JtApi {
|
||||
private readonly endpoint: string;
|
||||
private readonly fetchFn: typeof fetch;
|
||||
constructor(private readonly opts: JtClientOpts) {
|
||||
this.endpoint = opts.endpoint ?? "https://api.jobtread.com/pave";
|
||||
this.fetchFn = opts.fetchFn ?? fetch;
|
||||
}
|
||||
get organizationId(): string {
|
||||
return this.opts.organizationId;
|
||||
}
|
||||
|
||||
/** Один запрос: сеть, 429 и 5xx - retryable; прочие 4xx и ошибки разбора запроса - нет. */
|
||||
async query<T = Record<string, unknown>>(query: Record<string, unknown>): Promise<T> {
|
||||
let res: Response;
|
||||
let text: string;
|
||||
try {
|
||||
res = await this.fetchFn(this.endpoint, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ query: { $: { grantKey: this.opts.grantKey }, ...query } }),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
text = await res.text();
|
||||
} catch (e) {
|
||||
throw new PaveError(`JobTread недоступен: ${e instanceof Error ? e.message : String(e)}`, true);
|
||||
}
|
||||
if (res.status === 429 || res.status >= 500) throw new PaveError(`JobTread HTTP ${res.status}: ${text.slice(0, 200)}`, true);
|
||||
if (!res.ok) throw new PaveError(`JobTread HTTP ${res.status}: ${text.slice(0, 500)}`);
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
throw new PaveError(`JobTread: ответ не JSON: ${text.slice(0, 200)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getTask(id: string): Promise<JtTask | null> {
|
||||
try {
|
||||
const r = await this.query<{ task: RawTask | null }>({ task: { $: { id }, ...TASK_FIELDS } });
|
||||
return r.task ? mapRawTask(r.task) : null;
|
||||
} catch (e) {
|
||||
if (e instanceof PaveError && !e.retryable && /not found|does not exist|no .* found/i.test(e.message)) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private async page<N>(field: string, args: Record<string, unknown>, nodes: Record<string, unknown>, size = 100): Promise<N[]> {
|
||||
const out: N[] = [];
|
||||
let page: string | null = null;
|
||||
do {
|
||||
const r: { organization: Record<string, { nodes: N[]; nextPage: string | null }> } = await this.query({
|
||||
organization: { $: { id: this.opts.organizationId }, [field]: { $: { ...args, size, ...(page ? { page } : {}) }, nodes, nextPage: {} } },
|
||||
});
|
||||
const c = r.organization[field]!;
|
||||
out.push(...c.nodes);
|
||||
page = c.nextPage;
|
||||
} while (page);
|
||||
return out;
|
||||
}
|
||||
|
||||
async listOpenTodos(): Promise<JtTask[]> {
|
||||
const notStarted = await this.page<RawTask>("tasks", { where: { and: [["isToDo", "=", true], ["progress", "=", null]] } }, TASK_FIELDS);
|
||||
const partial = await this.page<RawTask>("tasks", { where: { and: [["isToDo", "=", true], ["progress", "<", 1]] } }, TASK_FIELDS);
|
||||
const seen = new Map<string, RawTask>();
|
||||
for (const t of [...notStarted, ...partial]) seen.set(t.id, t);
|
||||
return [...seen.values()].map(mapRawTask);
|
||||
}
|
||||
|
||||
private fields(w: TaskWrite): Record<string, unknown> {
|
||||
const o: Record<string, unknown> = {};
|
||||
if (w.name !== undefined) o.name = w.name;
|
||||
if (w.description !== undefined) o.description = w.description;
|
||||
if (w.endDate !== undefined) o.endDate = w.endDate;
|
||||
if (w.progress !== undefined) o.progress = w.progress;
|
||||
if (w.assignedMembershipIds !== undefined) o.assignedMembershipIds = w.assignedMembershipIds;
|
||||
return o;
|
||||
}
|
||||
|
||||
async createTask(args: { jobId: string; name: string } & TaskWrite): Promise<JtTask> {
|
||||
const { jobId, ...rest } = args;
|
||||
const r = await this.query<{ createTask: { createdTask: RawTask } }>({
|
||||
createTask: { $: { targetId: jobId, targetType: "job", isToDo: true, ...this.fields(rest) }, createdTask: TASK_FIELDS },
|
||||
});
|
||||
return mapRawTask(r.createTask.createdTask);
|
||||
}
|
||||
|
||||
async updateTask(id: string, patch: TaskWrite): Promise<void> {
|
||||
await this.query({ updateTask: { $: { id, ...this.fields(patch) } } });
|
||||
}
|
||||
|
||||
async deleteTask(id: string): Promise<void> {
|
||||
await this.query({ deleteTask: { $: { id } } });
|
||||
}
|
||||
|
||||
async recentTaskEvents(sinceIso: string): Promise<JtEventRef[]> {
|
||||
const raw = await this.page<{
|
||||
id: string; type: string; createdAt: string; data?: { previous?: { id?: string } | null; next?: { id?: string } | null } | null;
|
||||
task?: { id?: string } | null;
|
||||
}>(
|
||||
"events",
|
||||
{ where: { and: [["createdAt", ">=", sinceIso], { or: ["taskCreated", "taskUpdated", "taskDeleted"].map((t) => ["type", "=", t]) }] } },
|
||||
{ id: {}, type: {}, createdAt: {}, data: {}, task: { _on_task: { id: {} } } },
|
||||
);
|
||||
return raw.map((e) => ({ id: e.id, type: e.type, createdAt: e.createdAt, taskId: e.task?.id ?? e.data?.next?.id ?? e.data?.previous?.id ?? null }));
|
||||
}
|
||||
|
||||
async listWebhooks(): Promise<{ id: string; url: string }[]> {
|
||||
const r = await this.query<{ organization: { webhooks: { nodes: { id: string; url: string }[] } } }>({
|
||||
organization: { $: { id: this.opts.organizationId }, webhooks: { nodes: { id: {}, url: {} } } },
|
||||
});
|
||||
return r.organization.webhooks.nodes;
|
||||
}
|
||||
|
||||
async createWebhook(url: string): Promise<string> {
|
||||
const r = await this.query<{ createWebhook: { createdWebhook: { id: string } } }>({
|
||||
createWebhook: { $: { organizationId: this.opts.organizationId, url }, createdWebhook: { id: {} } },
|
||||
});
|
||||
return r.createWebhook.createdWebhook.id;
|
||||
}
|
||||
|
||||
async deleteWebhook(id: string): Promise<void> {
|
||||
await this.query({ deleteWebhook: { $: { id } } });
|
||||
}
|
||||
}
|
||||
64
packages/todo_service/src/live.int.test.ts
Normal file
64
packages/todo_service/src/live.int.test.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, jobtreadSchema, readSettingsFile, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { ADMIN } from "./access.js";
|
||||
import { TodoCore } from "./core.js";
|
||||
import { PaveJt } from "./jt.js";
|
||||
import { todoServiceSchema } from "./settings.js";
|
||||
|
||||
/**
|
||||
* Живая проверка против JobTread: только тестовый проект 22PdjKPJvzbk, названия с префиксом llmtest-, созданное удаляется.
|
||||
* Запуск: KHB_LIVE_JT=1 npx vitest run packages/todo_service/src/live.int.test.ts (нужны settings.json5 и туннель к БД).
|
||||
*/
|
||||
const TEST_JOB = "22PdjKPJvzbk";
|
||||
const live = process.env.KHB_LIVE_JT === "1" && !!testDatabaseUrl();
|
||||
const d = live ? describe : describe.skip;
|
||||
|
||||
d("todo_service: живой JobTread (тестовый проект)", () => {
|
||||
const jtCfg = live ? jobtreadSchema.parse(readSettingsFile().jobtread) : { grantKey: "", organizationId: "" };
|
||||
const jt = new PaveJt(jtCfg);
|
||||
const created: string[] = [];
|
||||
let db: TestDb | undefined;
|
||||
|
||||
afterAll(async () => {
|
||||
for (const id of created) await jt.deleteTask(id).catch(() => undefined);
|
||||
await db?.drop();
|
||||
});
|
||||
|
||||
it("создать, прочитать, изменить, закрыть и удалить todo; startDate всегда равен endDate", async () => {
|
||||
const t = await jt.createTask({ jobId: TEST_JOB, name: "llmtest-todo-service live", description: "live", endDate: "2026-12-01" });
|
||||
created.push(t.id);
|
||||
expect(t).toMatchObject({ jobId: TEST_JOB, isToDo: true, endDate: "2026-12-01", startDate: "2026-12-01", progress: null });
|
||||
await jt.updateTask(t.id, { name: "llmtest-todo-service live 2", endDate: "2026-12-03", progress: 1 });
|
||||
const g = await jt.getTask(t.id);
|
||||
expect(g).toMatchObject({ name: "llmtest-todo-service live 2", endDate: "2026-12-03", startDate: "2026-12-03", progress: 1 });
|
||||
await jt.deleteTask(t.id);
|
||||
created.pop();
|
||||
expect(await jt.getTask(t.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("ядро поверх JobTread: create / snooze / close, чтение через копию, события опроса", async () => {
|
||||
db = await createTestDb(testDatabaseUrl()!);
|
||||
const settings = todoServiceSchema.parse({ http: { token: "x" }, allowedJobIds: [TEST_JOB] });
|
||||
const core = new TodoCore({ pool: db.pool, jt, settings, tz: "America/New_York", log: createLogger("t", "silent") });
|
||||
const r = (await core.create(ADMIN, { jobId: TEST_JOB, name: "llmtest-todo-service core", kind: "reminder" }, "live-key")) as { id: string };
|
||||
created.push(r.id);
|
||||
const v = await core.get(ADMIN, r.id);
|
||||
expect(v).toMatchObject({ kind: "reminder", status: "open", jobId: TEST_JOB });
|
||||
await core.snooze(ADMIN, r.id, { until: "2026-12-10" });
|
||||
expect((await core.get(ADMIN, r.id)).reviewDate).toBe("2026-12-10");
|
||||
await core.close(ADMIN, r.id);
|
||||
expect((await core.get(ADMIN, r.id)).status).toBe("done");
|
||||
const ids = await jt.recentTaskEvents(new Date(Date.now() - 10 * 60_000).toISOString());
|
||||
expect(ids.some((e) => e.taskId === r.id)).toBe(true);
|
||||
expect(await core.pollEvents()).toBeGreaterThan(0);
|
||||
await core.remove(ADMIN, r.id);
|
||||
created.pop();
|
||||
expect((await core.get(ADMIN, r.id).catch(() => ({ status: "deleted" }))).status).toBe("deleted");
|
||||
});
|
||||
|
||||
it("открытые todo читаются постранично", async () => {
|
||||
const open = await jt.listOpenTodos();
|
||||
expect(open.length).toBeGreaterThan(10);
|
||||
expect(open.every((t) => t.isToDo && (t.progress ?? 0) < 1)).toBe(true);
|
||||
});
|
||||
});
|
||||
65
packages/todo_service/src/main.ts
Normal file
65
packages/todo_service/src/main.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { createLogger, createPool, jobtreadSchema, loadServiceSettings } from "khb_common";
|
||||
import { Auth } from "./auth.js";
|
||||
import { TodoCore } from "./core.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { PaveJt } from "./jt.js";
|
||||
import { todoServiceSchema } from "./settings.js";
|
||||
import { Watchers } from "./watchers.js";
|
||||
|
||||
const { common, service, raw } = loadServiceSettings("todo_service", todoServiceSchema);
|
||||
const jt = jobtreadSchema.parse(raw.jobtread);
|
||||
const log = createLogger("todo_service", common.logLevel);
|
||||
const pool = createPool(common.database.url);
|
||||
const pave = new PaveJt({ grantKey: jt.grantKey, organizationId: jt.organizationId });
|
||||
const core = new TodoCore({ pool, jt: pave, settings: service, tz: common.timezone, log });
|
||||
const watchers = new Watchers(core, pool, pave, service, common.timezone, log);
|
||||
|
||||
const app = buildApi({ pool, core, watchers, settings: service, auth: new Auth(pool, service) });
|
||||
await app.listen({ host: service.http.host, port: service.http.port });
|
||||
log.info({ port: service.http.port, allowedJobs: service.allowedJobIds.length }, "todo_service запущен");
|
||||
|
||||
/** Периодическое задание: не накладывается само на себя, ошибки логируются. */
|
||||
function every(name: string, seconds: number, fn: () => Promise<unknown>): NodeJS.Timeout {
|
||||
let busy = false;
|
||||
return setInterval(async () => {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
await fn();
|
||||
} catch (e) {
|
||||
log.error({ job: name, err: e instanceof Error ? e.message : String(e) }, "ошибка периодического задания");
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}, seconds * 1000);
|
||||
}
|
||||
|
||||
const timers = [
|
||||
every("requests", 5, () => core.processRequests()),
|
||||
every("poll", service.poll.intervalSeconds, () => core.pollEvents()),
|
||||
every("review", 300, () => watchers.reviewTick()),
|
||||
every("deliver", 60, () => watchers.deliverEvents()),
|
||||
...(service.control.enabled ? [every("control", service.control.tickSeconds, () => watchers.controlTick())] : []),
|
||||
];
|
||||
|
||||
// Стартовые действия не блокируют запуск: вебхук, полная загрузка открытых todo
|
||||
void (async () => {
|
||||
try {
|
||||
const id = await core.ensureWebhook();
|
||||
if (id) log.info({ webhookId: id }, "вебхук JobTread зарегистрирован");
|
||||
} catch (e) {
|
||||
log.error({ err: String(e) }, "не удалось зарегистрировать вебхук JobTread");
|
||||
}
|
||||
if (service.poll.backfillOnStart) {
|
||||
try {
|
||||
log.info({ todos: await core.backfill() }, "открытые todo загружены");
|
||||
} catch (e) {
|
||||
log.error({ err: String(e) }, "стартовая загрузка todo не удалась");
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
for (const t of timers) clearInterval(t);
|
||||
void app.close();
|
||||
});
|
||||
112
packages/todo_service/src/mcp.ts
Normal file
112
packages/todo_service/src/mcp.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import { HttpError, type TodoCore } from "./core.js";
|
||||
import type { Caller } from "./access.js";
|
||||
|
||||
/** MCP (Streamable HTTP, без сессий): тонкий адаптер над тем же ядром, что и REST. Реализация JSON-RPC 2.0 вручную. */
|
||||
|
||||
type Json = Record<string, unknown>;
|
||||
|
||||
interface Tool {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: Json;
|
||||
run: (core: TodoCore, caller: Caller, a: Json) => Promise<unknown>;
|
||||
}
|
||||
|
||||
const str = { type: "string" };
|
||||
const strArr = { type: "array", items: { type: "string" } };
|
||||
const kind = { type: "string", enum: ["todo", "reminder", "control"] };
|
||||
const obj = (properties: Json, required: string[] = []): Json => ({ type: "object", properties, required, additionalProperties: false });
|
||||
const s = (a: Json, k: string): string | undefined => (typeof a[k] === "string" ? (a[k] as string) : undefined);
|
||||
const need = (a: Json, k: string): string => {
|
||||
const v = s(a, k);
|
||||
if (!v) throw new HttpError(400, `нужно поле ${k}`);
|
||||
return v;
|
||||
};
|
||||
|
||||
export const TOOLS: Tool[] = [
|
||||
{
|
||||
name: "todo_search",
|
||||
description: "Найти todo: фильтры по исполнителю (membership id или me), проекту, виду, сроку, review_date<=сегодня, статусу, текст по названию и описанию.",
|
||||
inputSchema: obj({ q: str, assignee: str, job: str, kind, status: { type: "string", enum: ["open", "done", "all"] }, dueBefore: str, reviewDue: { type: "boolean" }, limit: { type: "number" } }),
|
||||
run: (c, caller, a) =>
|
||||
c.list(caller, { q: s(a, "q"), assignee: s(a, "assignee"), job: s(a, "job"), kind: s(a, "kind") as never, status: s(a, "status") as never, dueBefore: s(a, "dueBefore"), reviewDue: a.reviewDue === true, limit: typeof a.limit === "number" ? a.limit : undefined }),
|
||||
},
|
||||
{ name: "todo_get", description: "Одно todo со связями и флагами надстройки.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.get(caller, need(a, "id")) },
|
||||
{
|
||||
name: "todo_create",
|
||||
description: "Создать todo в проекте JobTread (срок по умолчанию - 3 рабочих дня). kind=control добавляет префикс 'Control:'.",
|
||||
inputSchema: obj({ jobId: str, name: str, description: str, due: str, assigneeMembershipIds: strArr, assigneePersonIds: strArr, kind, reviewDate: str, idempotencyKey: str }, ["jobId", "name"]),
|
||||
run: (c, caller, a) =>
|
||||
c.create(caller, { jobId: need(a, "jobId"), name: need(a, "name"), description: s(a, "description"), due: s(a, "due"), assigneeMembershipIds: a.assigneeMembershipIds as string[] | undefined, assigneePersonIds: a.assigneePersonIds as string[] | undefined, kind: s(a, "kind") as never, reviewDate: s(a, "reviewDate") }, s(a, "idempotencyKey")),
|
||||
},
|
||||
{
|
||||
name: "todo_update",
|
||||
description: "Изменить todo: название, описание, срок (due), исполнителей, вид, review_date (null снимает).",
|
||||
inputSchema: obj({ id: str, name: str, description: str, due: str, assigneeMembershipIds: strArr, assigneePersonIds: strArr, kind, reviewDate: { type: ["string", "null"] } }, ["id"]),
|
||||
run: (c, caller, a) =>
|
||||
c.update(caller, need(a, "id"), { name: s(a, "name"), description: s(a, "description"), due: s(a, "due"), assigneeMembershipIds: a.assigneeMembershipIds as string[] | undefined, assigneePersonIds: a.assigneePersonIds as string[] | undefined, kind: s(a, "kind") as never, reviewDate: "reviewDate" in a ? (a.reviewDate as string | null) : undefined }),
|
||||
},
|
||||
{ name: "todo_close", description: "Закрыть todo.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.close(caller, need(a, "id")) },
|
||||
{ name: "todo_reopen", description: "Вернуть закрытое todo в работу.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.reopen(caller, need(a, "id")) },
|
||||
{ name: "todo_delete", description: "Удалить todo.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.remove(caller, need(a, "id")) },
|
||||
{
|
||||
name: "todo_snooze",
|
||||
description: "Отложить todo: review_date = until (YYYY-MM-DD) или сегодня + days.",
|
||||
inputSchema: obj({ id: str, until: str, days: { type: "number" } }, ["id"]),
|
||||
run: (c, caller, a) => c.snooze(caller, need(a, "id"), { until: s(a, "until"), days: typeof a.days === "number" ? a.days : undefined }),
|
||||
},
|
||||
{ name: "todo_keep", description: "Отметить 'Keep confirmed': todo больше не попадает в проверку устаревания.", inputSchema: obj({ id: str }, ["id"]), run: (c, caller, a) => c.keep(caller, need(a, "id")) },
|
||||
{
|
||||
name: "todo_control_create",
|
||||
description: "Создать пару Control: todo исполнителю и Control todo контролёру (срок +2 дня, префикс 'Control:').",
|
||||
inputSchema: obj(
|
||||
{
|
||||
jobId: str, controllerPersonId: str, idempotencyKey: str,
|
||||
executor: obj({ name: str, description: str, due: str, assigneeMembershipIds: strArr, assigneePersonIds: strArr }, ["name"]),
|
||||
control: obj({ name: str, description: str }, ["name"]),
|
||||
},
|
||||
["jobId", "controllerPersonId", "executor", "control"],
|
||||
),
|
||||
run: (c, caller, a) => c.createControl(caller, { jobId: need(a, "jobId"), controllerPersonId: need(a, "controllerPersonId"), executor: a.executor as never, control: a.control as never }, s(a, "idempotencyKey")),
|
||||
},
|
||||
{ name: "todo_stale", description: "Открытые напоминания и Control старше 3 недель без 'Keep confirmed' (для пакетного вопроса).", inputSchema: obj({ personId: str, days: { type: "number" } }), run: (c, caller, a) => c.stale(caller, { personId: s(a, "personId"), days: typeof a.days === "number" ? a.days : undefined }) },
|
||||
{
|
||||
name: "todo_events",
|
||||
description: "Лента событий (control_done, control_overdue, review_due, write_failed).",
|
||||
inputSchema: obj({ personId: str, afterId: { type: "number" }, pending: { type: "boolean" } }),
|
||||
run: (c, caller, a) => c.events(caller, { personId: s(a, "personId"), afterId: typeof a.afterId === "number" ? a.afterId : undefined, pending: a.pending === true }),
|
||||
},
|
||||
];
|
||||
|
||||
const rpcError = (id: unknown, code: number, message: string): Json => ({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
|
||||
|
||||
/** Обрабатывает одно JSON-RPC сообщение; null - уведомление (ответа нет). */
|
||||
export async function handleMcpMessage(core: TodoCore, caller: Caller, msg: Json): Promise<Json | null> {
|
||||
const id = msg.id;
|
||||
const method = msg.method;
|
||||
if (typeof method !== "string") return rpcError(id, -32600, "invalid request");
|
||||
if (id === undefined) return null; // notifications/*
|
||||
switch (method) {
|
||||
case "initialize": {
|
||||
const asked = (msg.params as Json | undefined)?.protocolVersion;
|
||||
return { jsonrpc: "2.0", id, result: { protocolVersion: typeof asked === "string" ? asked : "2025-03-26", capabilities: { tools: {} }, serverInfo: { name: "khb-todo", version: "0.1.0" } } };
|
||||
}
|
||||
case "ping":
|
||||
return { jsonrpc: "2.0", id, result: {} };
|
||||
case "tools/list":
|
||||
return { jsonrpc: "2.0", id, result: { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) } };
|
||||
case "tools/call": {
|
||||
const p = (msg.params ?? {}) as { name?: string; arguments?: Json };
|
||||
const tool = TOOLS.find((t) => t.name === p.name);
|
||||
if (!tool) return rpcError(id, -32602, `неизвестный инструмент ${p.name}`);
|
||||
try {
|
||||
const out = await tool.run(core, caller, p.arguments ?? {});
|
||||
return { jsonrpc: "2.0", id, result: { content: [{ type: "text", text: JSON.stringify(out) }] } };
|
||||
} catch (e) {
|
||||
return { jsonrpc: "2.0", id, result: { isError: true, content: [{ type: "text", text: e instanceof Error ? e.message : String(e) }] } };
|
||||
}
|
||||
}
|
||||
default:
|
||||
return rpcError(id, -32601, `метод не поддерживается: ${method}`);
|
||||
}
|
||||
}
|
||||
54
packages/todo_service/src/rules.test.ts
Normal file
54
packages/todo_service/src/rules.test.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ageDate, controlDue, defaultDue, desiredName, ensureControlPrefix, guessKind, noticedDate, stripStatusSuffix, withKeepConfirmed, withReviewLine,
|
||||
} from "./rules.js";
|
||||
|
||||
describe("правила todo", () => {
|
||||
it("срок по умолчанию - 3 рабочих дня, выходные пропускаются", () => {
|
||||
expect(defaultDue("2026-10-29", 3, new Set())).toBe("2026-11-03"); // чт: пт, пн, вт
|
||||
});
|
||||
|
||||
it("срок Control на 2 дня позже срока исполнителя", () => {
|
||||
expect(controlDue("2026-11-03", 2)).toBe("2026-11-05");
|
||||
});
|
||||
|
||||
it("префикс Control: добавляется один раз, независимо от регистра", () => {
|
||||
expect(ensureControlPrefix("Ask Walter if X was fixed")).toBe("Control: Ask Walter if X was fixed");
|
||||
expect(ensureControlPrefix("Control: Ask")).toBe("Control: Ask");
|
||||
expect(ensureControlPrefix("control: Ask")).toBe("control: Ask");
|
||||
});
|
||||
|
||||
it("суффиксы статуса: снимаются все, выполнено важнее просрочено", () => {
|
||||
expect(stripStatusSuffix("Control: Ask (просрочено) (выполнено)")).toBe("Control: Ask");
|
||||
expect(desiredName("Control: Ask (просрочено)", { done: true, overdue: false })).toBe("Control: Ask (выполнено)");
|
||||
expect(desiredName("Control: Ask", { done: false, overdue: true })).toBe("Control: Ask (просрочено)");
|
||||
expect(desiredName("Control: Ask (выполнено)", { done: false, overdue: false })).toBe("Control: Ask");
|
||||
});
|
||||
|
||||
it("строка Review добавляется в конец описания и заменяется, а не дублируется", () => {
|
||||
const a = withReviewLine("Описание", "2026-11-05");
|
||||
expect(a).toBe("Описание\n\nReview: 05.11");
|
||||
expect(withReviewLine(a, "2026-11-09")).toBe("Описание\n\nReview: 09.11");
|
||||
expect(withReviewLine(a, null)).toBe("Описание");
|
||||
expect(withReviewLine(null, "2026-11-05")).toBe("Review: 05.11");
|
||||
});
|
||||
|
||||
it("Keep confirmed дописывается один раз", () => {
|
||||
const a = withKeepConfirmed("Текст", "2026-10-29");
|
||||
expect(a).toBe("Текст\n\nKeep confirmed 2026-10-29");
|
||||
expect(withKeepConfirmed(a, "2026-11-01")).toBe(a);
|
||||
});
|
||||
|
||||
it("дата замечания: из описания, иначе дата создания", () => {
|
||||
expect(noticedDate("Arthur noticed on 2026-09-30 at site")).toBe("2026-09-30");
|
||||
expect(noticedDate("noticed 9/3/2026")).toBe("2026-09-03");
|
||||
expect(ageDate("без даты", "2026-10-01T10:00:00Z")).toBe("2026-10-01");
|
||||
expect(ageDate("2026-09-01", "2026-10-01T10:00:00Z")).toBe("2026-09-01");
|
||||
});
|
||||
|
||||
it("вид по названию", () => {
|
||||
expect(guessKind("Control: x")).toBe("control");
|
||||
expect(guessKind("Reminder: Did x get fixed?")).toBe("reminder");
|
||||
expect(guessKind("Order tile")).toBe("todo");
|
||||
});
|
||||
});
|
||||
86
packages/todo_service/src/rules.ts
Normal file
86
packages/todo_service/src/rules.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { addDays, addWorkDays } from "khb_common";
|
||||
|
||||
/** Правила todo в одном месте: сроки, префикс и суффиксы Control, строка Review, давность. */
|
||||
|
||||
export const CONTROL_PREFIX = "Control:";
|
||||
export const SUFFIX_DONE = "(выполнено)";
|
||||
export const SUFFIX_OVERDUE = "(просрочено)";
|
||||
const SUFFIX_RE = /\s*\((?:выполнено|просрочено)\)\s*$/;
|
||||
|
||||
/** Срок по умолчанию: dueWorkdays рабочих дней от даты сообщения. */
|
||||
export function defaultDue(from: string, workdays: number, nonWorkdays: ReadonlySet<string>): string {
|
||||
return addWorkDays(from, workdays, nonWorkdays);
|
||||
}
|
||||
|
||||
/** Срок Control todo: срок исполнителя + offset календарных дней. */
|
||||
export function controlDue(executorDue: string, offsetDays: number): string {
|
||||
return addDays(executorDue, offsetDays);
|
||||
}
|
||||
|
||||
/** Название без суффикса статуса (всех подряд). */
|
||||
export function stripStatusSuffix(name: string): string {
|
||||
let n = name;
|
||||
while (SUFFIX_RE.test(n)) n = n.replace(SUFFIX_RE, "");
|
||||
return n.trim();
|
||||
}
|
||||
|
||||
/** Название Control todo всегда начинается с "Control:". */
|
||||
export function ensureControlPrefix(name: string): string {
|
||||
const n = name.trim();
|
||||
return n.toLowerCase().startsWith(CONTROL_PREFIX.toLowerCase()) ? n : `${CONTROL_PREFIX} ${n}`;
|
||||
}
|
||||
|
||||
/** Желаемое название по состоянию надстройки: суффикс "(выполнено)" важнее "(просрочено)". */
|
||||
export function desiredName(baseName: string, flags: { done: boolean; overdue: boolean }): string {
|
||||
const base = stripStatusSuffix(baseName);
|
||||
if (flags.done) return `${base} ${SUFFIX_DONE}`;
|
||||
if (flags.overdue) return `${base} ${SUFFIX_OVERDUE}`;
|
||||
return base;
|
||||
}
|
||||
|
||||
const REVIEW_LINE_RE = /(?:\r?\n)*Review: \d{2}\.\d{2}\s*$/;
|
||||
|
||||
/** Описание с одной строкой "Review: ДД.ММ" в конце (до 4096 знаков); until=null убирает строку. */
|
||||
export function withReviewLine(description: string | null, until: string | null): string {
|
||||
const base = (description ?? "").replace(REVIEW_LINE_RE, "");
|
||||
if (!until) return base;
|
||||
const [, m, d] = until.match(/^\d{4}-(\d{2})-(\d{2})$/) ?? [];
|
||||
if (!m || !d) return base;
|
||||
const line = `Review: ${d}.${m}`;
|
||||
return (base ? `${base}\n\n${line}` : line).slice(-4096);
|
||||
}
|
||||
|
||||
/** Дописывает "Keep confirmed <дата>" к описанию (один раз). */
|
||||
export function withKeepConfirmed(description: string | null, date: string): string {
|
||||
const base = description ?? "";
|
||||
if (/Keep confirmed \d{4}-\d{2}-\d{2}/.test(base)) return base;
|
||||
return (base ? `${base}\n\n` : "") + `Keep confirmed ${date}`;
|
||||
}
|
||||
|
||||
/** Дата замечания из описания (YYYY-MM-DD или M/D/YYYY), иначе null. */
|
||||
export function noticedDate(description: string | null): string | null {
|
||||
const text = description ?? "";
|
||||
const iso = text.match(/\b(20\d{2})-(\d{2})-(\d{2})\b/);
|
||||
if (iso) return `${iso[1]}-${iso[2]}-${iso[3]}`;
|
||||
const us = text.match(/\b(\d{1,2})\/(\d{1,2})\/(20\d{2})\b/);
|
||||
if (us) return `${us[3]}-${us[1]!.padStart(2, "0")}-${us[2]!.padStart(2, "0")}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Дата для проверки давности: дата замечания из описания, иначе дата создания (YYYY-MM-DD). */
|
||||
export function ageDate(description: string | null, createdAtIso: string | null): string | null {
|
||||
return noticedDate(description) ?? (createdAtIso ? createdAtIso.slice(0, 10) : null);
|
||||
}
|
||||
|
||||
/** Закрыто: progress >= 1. */
|
||||
export const isClosed = (progress: number | null): boolean => progress != null && progress >= 1;
|
||||
|
||||
export type TodoKind = "todo" | "reminder" | "control";
|
||||
|
||||
/** Вид по названию, когда надстройки ещё нет: "Control:" - control, "Reminder:" - reminder. */
|
||||
export function guessKind(name: string): TodoKind {
|
||||
const n = name.trim().toLowerCase();
|
||||
if (n.startsWith("control:")) return "control";
|
||||
if (n.startsWith("reminder:")) return "reminder";
|
||||
return "todo";
|
||||
}
|
||||
329
packages/todo_service/src/service.int.test.ts
Normal file
329
packages/todo_service/src/service.int.test.ts
Normal file
@@ -0,0 +1,329 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createLogger, createTestDb, testDatabaseUrl, type TestDb } from "khb_common";
|
||||
import { AccessError, ADMIN, resolveCaller } from "./access.js";
|
||||
import { Auth } from "./auth.js";
|
||||
import { TodoCore } from "./core.js";
|
||||
import { buildApi } from "./http-api.js";
|
||||
import { todoServiceSchema } from "./settings.js";
|
||||
import { FakeJt } from "./testing.js";
|
||||
import { Watchers } from "./watchers.js";
|
||||
|
||||
const url = testDatabaseUrl();
|
||||
const d = url ? describe : describe.skip;
|
||||
const log = createLogger("test", "silent");
|
||||
|
||||
const JOB = "JOBtest0001";
|
||||
const OTHER_JOB = "JOBother001";
|
||||
const CEO = "11111111-1111-4111-8111-111111111111";
|
||||
const MGR = "22222222-2222-4222-8222-222222222222";
|
||||
const MGR2 = "33333333-3333-4333-8333-333333333333";
|
||||
|
||||
d("todo_service (временная БД, JobTread подменён)", () => {
|
||||
let db: TestDb;
|
||||
let jt: FakeJt;
|
||||
let core: TodoCore;
|
||||
let watchers: Watchers;
|
||||
let clock = new Date("2026-10-29T15:00:00Z"); // чт 11:00 по Тампе
|
||||
const settings = todoServiceSchema.parse({
|
||||
http: { token: "internal-token", port: 0 },
|
||||
allowedJobIds: [JOB],
|
||||
webhook: { secret: "hooksecret123", publicBaseUrl: "https://todo.example.org", autoRegister: true },
|
||||
mcp: { staticTokens: [{ token: "static-mcp-token-0001", personId: MGR }] },
|
||||
notify: { enabled: true, url: "http://agents.test/chat/todo", token: "t" },
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
db = await createTestDb(url!);
|
||||
await db.pool.query(
|
||||
`insert into person (id, display_name, email, jt_membership_id) values
|
||||
($1,'CEO test','ceo@test.org','MEMceo'), ($2,'Manager test','mgr@test.org','MEMmgr'), ($3,'Manager2 test','mgr2@test.org','MEMmgr2')`,
|
||||
[CEO, MGR, MGR2],
|
||||
);
|
||||
await db.pool.query(
|
||||
`insert into construction_manager (person_id, chat_kind) values ($1,'ceo'), ($2,'manager'), ($3,'manager')`,
|
||||
[CEO, MGR, MGR2],
|
||||
);
|
||||
await db.pool.query("insert into assistant_project (jt_job_id, manager_person_id) values ($1,$2), ($3,$4)", [JOB, MGR, OTHER_JOB, MGR2]);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await db?.drop();
|
||||
});
|
||||
|
||||
const mk = (): void => {
|
||||
jt = new FakeJt();
|
||||
core = new TodoCore({ pool: db.pool, jt, settings, tz: "America/New_York", log, now: () => clock });
|
||||
watchers = new Watchers(core, db.pool, jt, settings, "America/New_York", log, () => clock);
|
||||
};
|
||||
beforeAll(() => mk());
|
||||
|
||||
it("создание: срок по умолчанию 3 рабочих дня, надстройка, идемпотентность", async () => {
|
||||
const a = await core.create(ADMIN, { jobId: JOB, name: "Order tile", assigneeMembershipIds: ["MEMmgr"] }, "key-1");
|
||||
expect(a.status).toBe("done");
|
||||
const todo = (await core.get(ADMIN, (a as { id: string }).id));
|
||||
expect(todo.dueDate).toBe("2026-11-03");
|
||||
expect(todo.kind).toBe("todo");
|
||||
expect(todo.assignees[0]?.id).toBe("MEMmgr");
|
||||
const again = await core.create(ADMIN, { jobId: JOB, name: "Order tile", assigneeMembershipIds: ["MEMmgr"] }, "key-1");
|
||||
expect((again as { id: string }).id).toBe((a as { id: string }).id);
|
||||
expect([...jt.tasks.values()].filter((t) => t.name === "Order tile")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("запись только в разрешённые проекты", async () => {
|
||||
await expect(core.create(ADMIN, { jobId: OTHER_JOB, name: "x" })).rejects.toBeInstanceOf(AccessError);
|
||||
});
|
||||
|
||||
it("JobTread недоступен: запрос в очереди, потом выполняется; ключ не дублирует", async () => {
|
||||
jt.failWrites = 1;
|
||||
const r = await core.create(ADMIN, { jobId: JOB, name: "Queued todo" }, "key-q");
|
||||
expect(r.status).toBe("queued");
|
||||
const again = await core.create(ADMIN, { jobId: JOB, name: "Queued todo" }, "key-q");
|
||||
expect(again.status).toBe("queued");
|
||||
await db.pool.query("update todo_request set next_attempt_at = now() - interval '1 second' where status = 'pending'");
|
||||
expect(await core.processRequests()).toBe(1);
|
||||
const st = await core.request(ADMIN, (r as { requestId: string }).requestId);
|
||||
expect(st.status).toBe("done");
|
||||
expect([...jt.tasks.values()].filter((t) => t.name === "Queued todo")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("просроченная очередь: failed и событие write_failed", async () => {
|
||||
jt.failWrites = 100;
|
||||
const r = await core.create(ADMIN, { jobId: JOB, name: "Never" }, "key-never");
|
||||
expect(r.status).toBe("queued");
|
||||
await db.pool.query("update todo_request set next_attempt_at = now() - interval '1 second', deadline = now() - interval '1 second' where id = $1", [(r as { requestId: string }).requestId]);
|
||||
await core.processRequests();
|
||||
jt.failWrites = 0;
|
||||
expect((await core.request(ADMIN, (r as { requestId: string }).requestId)).status).toBe("failed");
|
||||
expect((await db.pool.query("select count(*)::int n from todo_event where event_type = 'write_failed'")).rows[0].n).toBe(1);
|
||||
});
|
||||
|
||||
it("вебхук: создание, изменение (только изменённые поля), закрытие, удаление", async () => {
|
||||
const ev = (type: string, next: unknown, previous: unknown, at: string) => ({ createdEvent: { type, createdAt: at, task: { id: "WH00000001x" }, data: { next, previous } } });
|
||||
const base = { id: "WH00000001x", name: "Hook todo", jobId: JOB, isToDo: true, endDate: "2026-11-05", startDate: "2026-11-05", progress: null, description: "d", assignedMembershipIds: ["MEMmgr"] };
|
||||
await core.applyWebhook(ev("taskCreated", base, null, "2026-10-29T15:00:00.000Z"));
|
||||
expect((await core.get(ADMIN, "WH00000001x")).name).toBe("Hook todo");
|
||||
await core.applyWebhook(ev("taskUpdated", { name: "Hook todo 2", description: "d2" }, { name: "Hook todo", description: "d" }, "2026-10-29T15:01:00.000Z"));
|
||||
const upd = await core.get(ADMIN, "WH00000001x");
|
||||
expect(upd).toMatchObject({ name: "Hook todo 2", description: "d2", dueDate: "2026-11-05", jobId: JOB });
|
||||
await core.applyWebhook(ev("taskUpdated", { progress: 1 }, { progress: null }, "2026-10-29T15:02:00.000Z"));
|
||||
expect((await core.get(ADMIN, "WH00000001x")).status).toBe("done");
|
||||
await core.applyWebhook(ev("taskDeleted", null, { ...base, progress: 1 }, "2026-10-29T15:03:00.000Z"));
|
||||
await expect(core.get(ADMIN, "WH00000001x")).resolves.toMatchObject({ status: "deleted" });
|
||||
expect(await core.applyWebhook({ createdEvent: { type: "dailyLogCreated", data: {} } })).toMatchObject({ handled: false });
|
||||
});
|
||||
|
||||
it("права: менеджер видит только свои проекты и назначенные ему, CEO - всё", async () => {
|
||||
await db.pool.query(
|
||||
"insert into todo_item (task_id, job_id, name, assignee_ids) values ('ACC0000001x', $1, 'other project todo', '{}'), ('ACC0000002x', $2, 'assigned to mgr', '{MEMmgr}'), ('ACC0000003x', $2, 'foreign', '{}')",
|
||||
[JOB, OTHER_JOB],
|
||||
);
|
||||
const mgr = await resolveCaller(db.pool, MGR);
|
||||
const ceo = await resolveCaller(db.pool, CEO);
|
||||
const names = (await core.list(mgr, { q: "assigned" })).map((t) => t.name);
|
||||
expect(names).toEqual(["assigned to mgr"]);
|
||||
expect((await core.list(mgr, { q: "other project" })).length).toBe(1);
|
||||
expect((await core.list(mgr, { q: "foreign" })).length).toBe(0);
|
||||
expect((await core.list(ceo, { q: "foreign" })).length).toBe(1);
|
||||
await expect(core.get(mgr, "ACC0000003x")).rejects.toMatchObject({ status: 404 });
|
||||
await expect(core.update(mgr, "ACC0000002x", { name: "x" })).rejects.toBeInstanceOf(AccessError); // проект не в allowedJobIds
|
||||
});
|
||||
|
||||
it("поиск: по тексту, исполнителю me, сроку и виду", async () => {
|
||||
const mgr = await resolveCaller(db.pool, MGR);
|
||||
expect((await core.list(mgr, { assignee: "me", q: "tile" })).map((t) => t.name)).toContain("Order tile");
|
||||
expect((await core.list(ADMIN, { dueBefore: "2026-11-03", q: "Order tile" })).length).toBe(1);
|
||||
expect((await core.list(ADMIN, { dueBefore: "2026-11-02", q: "Order tile" })).length).toBe(0);
|
||||
expect((await core.list(ADMIN, { kind: "control" })).length).toBe(0);
|
||||
});
|
||||
|
||||
it("snooze: review_date в надстройке (JobTread не трогается), событие review_due один раз", async () => {
|
||||
const t = (await core.create(ADMIN, { jobId: JOB, name: "Snooze me" })) as { id: string };
|
||||
const before = jt.calls.length;
|
||||
await core.snooze(ADMIN, t.id, { days: 2 });
|
||||
expect(jt.calls.length).toBe(before);
|
||||
expect((await core.get(ADMIN, t.id)).reviewDate).toBe("2026-10-31");
|
||||
expect((await core.list(ADMIN, { reviewDue: true })).length).toBe(0);
|
||||
expect(await watchers.reviewTick()).toBe(0);
|
||||
clock = new Date("2026-10-31T15:00:00Z");
|
||||
expect((await core.list(ADMIN, { reviewDue: true })).map((x) => x.id)).toContain(t.id);
|
||||
expect(await watchers.reviewTick()).toBe(1);
|
||||
expect(await watchers.reviewTick()).toBe(0);
|
||||
expect((await db.pool.query("select count(*)::int n from todo_event where event_type = 'review_due' and task_id = $1", [t.id])).rows[0].n).toBe(1);
|
||||
clock = new Date("2026-10-29T15:00:00Z");
|
||||
});
|
||||
|
||||
it("Keep confirmed: флаг и строка в описании; устаревание берёт дату замечания из описания", async () => {
|
||||
const t = (await core.create(ADMIN, { jobId: JOB, name: "Reminder: Did X get fixed?", description: "Arthur noticed on 2026-09-01", assigneePersonIds: [MGR] })) as { id: string };
|
||||
expect((await core.get(ADMIN, t.id)).kind).toBe("reminder");
|
||||
const mgr = await resolveCaller(db.pool, MGR);
|
||||
expect((await core.stale(mgr)).map((x) => x.id)).toContain(t.id);
|
||||
await core.keep(ADMIN, t.id);
|
||||
const after = await core.get(ADMIN, t.id);
|
||||
expect(after.keepConfirmed).toBe(true);
|
||||
expect(after.description).toContain("Keep confirmed 2026-10-29");
|
||||
expect((await core.stale(mgr)).map((x) => x.id)).not.toContain(t.id);
|
||||
});
|
||||
|
||||
describe("Control", () => {
|
||||
let pair: { controlTaskId: string; executorTaskId: string; controlDue: string; executorDue: string };
|
||||
const mkPair = async (name: string, execDue?: string): Promise<typeof pair> =>
|
||||
(await core.createControl(ADMIN, {
|
||||
jobId: JOB, controllerPersonId: CEO,
|
||||
executor: { name: `Reminder: Did ${name} get fixed?`, description: "noticed", assigneePersonIds: [MGR], due: execDue },
|
||||
control: { name: `Ask Walter if ${name} was fixed` },
|
||||
})) as never as typeof pair;
|
||||
|
||||
it("создание пары: префикс Control:, срок +2 дня, связь и виды", async () => {
|
||||
pair = await mkPair("A");
|
||||
expect(pair.executorDue).toBe("2026-11-03");
|
||||
expect(pair.controlDue).toBe("2026-11-05");
|
||||
const c = await core.get(ADMIN, pair.controlTaskId);
|
||||
expect(c.name).toBe("Control: Ask Walter if A was fixed");
|
||||
expect(c.kind).toBe("control");
|
||||
expect(c.assignees[0]?.id).toBe("MEMceo");
|
||||
expect(c.links[0]).toMatchObject({ role: "control", taskId: pair.executorTaskId, status: "active" });
|
||||
expect((await core.get(ADMIN, pair.executorTaskId)).kind).toBe("reminder");
|
||||
});
|
||||
|
||||
it("исполнитель закрыл: (выполнено) в названии, событие control_done, Control todo не закрывается", async () => {
|
||||
jt.tasks.get(pair.executorTaskId)!.progress = 1;
|
||||
await core.syncTask(pair.executorTaskId);
|
||||
expect(await watchers.controlTick()).toBe(1);
|
||||
const c = await core.get(ADMIN, pair.controlTaskId);
|
||||
expect(c.name).toBe("Control: Ask Walter if A was fixed (выполнено)");
|
||||
expect(jt.tasks.get(pair.controlTaskId)!.name).toBe(c.name);
|
||||
expect(c.status).toBe("open");
|
||||
const ev = (await db.pool.query("select event_type, person_id, payload from todo_event where task_id = $1", [pair.controlTaskId])).rows;
|
||||
expect(ev).toHaveLength(1);
|
||||
expect(ev[0]).toMatchObject({ event_type: "control_done", person_id: CEO });
|
||||
expect(await watchers.controlTick()).toBe(0); // статус done больше не отслеживается: повторов нет
|
||||
});
|
||||
|
||||
it("человек поправил название: суффикс восстанавливается без петли", async () => {
|
||||
await core.applyWebhook({ createdEvent: { type: "taskUpdated", createdAt: "2026-10-29T16:00:00Z", task: { id: pair.controlTaskId }, data: { next: { id: pair.controlTaskId, name: "Control: Ask W. if A was fixed" }, previous: {} } } });
|
||||
expect(jt.tasks.get(pair.controlTaskId)!.name).toBe("Control: Ask W. if A was fixed (выполнено)");
|
||||
const calls = jt.calls.length;
|
||||
await core.applyWebhook({ createdEvent: { type: "taskUpdated", createdAt: "2026-10-29T16:00:01Z", task: { id: pair.controlTaskId }, data: { next: { id: pair.controlTaskId, name: "Control: Ask W. if A was fixed (выполнено)" }, previous: {} } } });
|
||||
expect(jt.calls.length).toBe(calls);
|
||||
});
|
||||
|
||||
it("срок наступил и 2 дня нет действий: (просрочено) и событие; потом закрыл - снова выполнено", async () => {
|
||||
const p = await mkPair("B", "2026-10-29");
|
||||
clock = new Date("2026-11-02T15:00:00Z"); // control_due 10-31 уже прошёл
|
||||
await db.pool.query("update todo_item set last_event_at = '2026-10-20T00:00:00Z' where task_id = $1", [p.executorTaskId]);
|
||||
expect(await watchers.controlTick()).toBe(1);
|
||||
expect((await core.get(ADMIN, p.controlTaskId)).name).toBe("Control: Ask Walter if B was fixed (просрочено)");
|
||||
expect((await db.pool.query("select event_type from todo_event where task_id = $1", [p.controlTaskId])).rows.map((r) => r.event_type)).toEqual(["control_overdue"]);
|
||||
jt.tasks.get(p.executorTaskId)!.progress = 1;
|
||||
await core.syncTask(p.executorTaskId);
|
||||
expect(await watchers.controlTick()).toBe(1);
|
||||
expect((await core.get(ADMIN, p.controlTaskId)).name).toBe("Control: Ask Walter if B was fixed (выполнено)");
|
||||
expect((await db.pool.query("select event_type from todo_event where task_id = $1 order by id", [p.controlTaskId])).rows.map((r) => r.event_type)).toEqual(["control_overdue", "control_done"]);
|
||||
clock = new Date("2026-10-29T15:00:00Z");
|
||||
});
|
||||
|
||||
it("недавние действия исполнителя не дают просрочки; без срока просрочено не ставится; контролёр закрыл - слежение снято молча", async () => {
|
||||
const recent = await mkPair("C", "2026-10-28");
|
||||
clock = new Date("2026-11-02T15:00:00Z");
|
||||
await db.pool.query("update todo_item set last_event_at = '2026-11-01T12:00:00Z' where task_id = $1", [recent.executorTaskId]);
|
||||
const nodue = await mkPair("D", "2026-10-28");
|
||||
await db.pool.query("update todo_link set control_due = null where task_id = $1", [nodue.controlTaskId]);
|
||||
await db.pool.query("update todo_item set last_event_at = '2026-10-01T00:00:00Z' where task_id = $1", [nodue.executorTaskId]);
|
||||
const closed = await mkPair("E", "2026-10-28");
|
||||
jt.tasks.get(closed.controlTaskId)!.progress = 1;
|
||||
await core.syncTask(closed.controlTaskId);
|
||||
jt.tasks.get(closed.executorTaskId)!.progress = 1;
|
||||
await core.syncTask(closed.executorTaskId);
|
||||
const events = (await db.pool.query("select count(*)::int n from todo_event")).rows[0].n;
|
||||
await watchers.controlTick();
|
||||
expect((await db.pool.query("select status from todo_link where task_id = $1", [recent.controlTaskId])).rows[0].status).toBe("active");
|
||||
expect((await db.pool.query("select status from todo_link where task_id = $1", [nodue.controlTaskId])).rows[0].status).toBe("active");
|
||||
expect((await db.pool.query("select status from todo_link where task_id = $1", [closed.controlTaskId])).rows[0].status).toBe("closed");
|
||||
expect((await db.pool.query("select count(*)::int n from todo_event")).rows[0].n).toBe(events);
|
||||
clock = new Date("2026-10-29T15:00:00Z");
|
||||
});
|
||||
|
||||
it("доставка событий агенту: в окне 7-19, один раз; режим off не получает", async () => {
|
||||
const sent: { url: string; body: { personId: string; events: { type: string }[] } }[] = [];
|
||||
const fakeFetch = (async (u: string, init: { body: string }) => {
|
||||
sent.push({ url: u, body: JSON.parse(init.body) });
|
||||
return { ok: true, status: 200 } as Response;
|
||||
}) as unknown as typeof fetch;
|
||||
clock = new Date("2026-10-29T03:00:00Z"); // 23:00 по Тампе: вне окна
|
||||
expect(await watchers.deliverEvents(fakeFetch)).toBe(0);
|
||||
clock = new Date("2026-10-29T15:00:00Z");
|
||||
await db.pool.query("update construction_manager set agent_paused = true, pause_mode = 'off' where person_id = $1", [CEO]);
|
||||
expect(await watchers.deliverEvents(fakeFetch)).toBe(0);
|
||||
await db.pool.query("update construction_manager set agent_paused = false, pause_mode = 'passive' where person_id = $1", [CEO]);
|
||||
const n = await watchers.deliverEvents(fakeFetch);
|
||||
expect(n).toBeGreaterThan(0);
|
||||
expect(sent[0]!.body.personId).toBe(CEO);
|
||||
expect(sent[0]!.body.events.map((e) => e.type)).toContain("control_done");
|
||||
expect(await watchers.deliverEvents(fakeFetch)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it("регистрация вебхука: создаётся один раз", async () => {
|
||||
const id1 = await core.ensureWebhook();
|
||||
const id2 = await core.ensureWebhook();
|
||||
expect(id1).toBe(id2);
|
||||
expect(jt.webhooks[0]!.url).toBe("https://todo.example.org/webhooks/jobtread/hooksecret123");
|
||||
});
|
||||
|
||||
describe("HTTP и MCP", () => {
|
||||
const mkApp = () => buildApi({ pool: db.pool, core, watchers, settings, auth: new Auth(db.pool, settings) });
|
||||
const H = { authorization: "Bearer internal-token" };
|
||||
|
||||
it("авторизация и healthz", async () => {
|
||||
const app = mkApp();
|
||||
expect((await app.inject({ method: "GET", url: "/healthz" })).json()).toMatchObject({ ok: true });
|
||||
expect((await app.inject({ method: "GET", url: "/todos" })).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "GET", url: "/todos", headers: { authorization: "Bearer bad" } })).statusCode).toBe(401);
|
||||
expect((await app.inject({ method: "GET", url: "/todos?q=tile", headers: H })).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("REST: создание с Idempotency-Key, get, patch, close, snooze, права по X-Caller-Person", async () => {
|
||||
const app = mkApp();
|
||||
const cr = await app.inject({ method: "POST", url: "/todos", headers: { ...H, "idempotency-key": "http-1" }, payload: { jobId: JOB, name: "HTTP todo", assigneePersonIds: [MGR] } });
|
||||
expect(cr.statusCode).toBe(200);
|
||||
const id = cr.json().id as string;
|
||||
expect((await app.inject({ method: "POST", url: "/todos", headers: { ...H, "idempotency-key": "http-1" }, payload: { jobId: JOB, name: "HTTP todo" } })).json().id).toBe(id);
|
||||
expect((await app.inject({ method: "PATCH", url: `/todos/${id}`, headers: H, payload: { description: "новое описание" } })).json().todo.description).toBe("новое описание");
|
||||
expect((await app.inject({ method: "POST", url: `/todos/${id}/snooze`, headers: H, payload: { days: 5 } })).json().todo.reviewDate).toBe("2026-11-03");
|
||||
const asMgr2 = await app.inject({ method: "GET", url: `/todos/${id}`, headers: { ...H, "x-caller-person": MGR2 } });
|
||||
expect(asMgr2.statusCode).toBe(404);
|
||||
const asMgr = await app.inject({ method: "GET", url: `/todos/${id}`, headers: { ...H, "x-caller-person": MGR } });
|
||||
expect(asMgr.statusCode).toBe(200);
|
||||
expect((await app.inject({ method: "POST", url: `/todos/${id}/close`, headers: H })).json().todo.status).toBe("done");
|
||||
expect((await app.inject({ method: "POST", url: "/todos", headers: H, payload: { jobId: OTHER_JOB, name: "x" } })).statusCode).toBe(403);
|
||||
expect((await app.inject({ method: "POST", url: "/todos", headers: H, payload: { jobId: JOB } })).statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it("вебхук: неверный секрет - 404, верный - обработка", async () => {
|
||||
const app = mkApp();
|
||||
const body = { createdEvent: { type: "taskCreated", createdAt: "2026-10-29T15:00:00Z", data: { previous: null, next: { id: "HK00000009x", name: "via http hook", jobId: JOB, isToDo: true, progress: null, endDate: "2026-11-09", assignedMembershipIds: [] } } } };
|
||||
expect((await app.inject({ method: "POST", url: "/webhooks/jobtread/wrong", payload: body })).statusCode).toBe(404);
|
||||
expect((await app.inject({ method: "POST", url: "/webhooks/jobtread/hooksecret123", payload: body })).statusCode).toBe(202);
|
||||
expect((await core.get(ADMIN, "HK00000009x")).name).toBe("via http hook");
|
||||
});
|
||||
|
||||
it("MCP: initialize, tools/list, tools/call, ошибки и авторизация", async () => {
|
||||
const app = mkApp();
|
||||
const rpc = async (payload: unknown, headers: Record<string, string> = { authorization: "Bearer static-mcp-token-0001" }) =>
|
||||
app.inject({ method: "POST", url: "/mcp", headers, payload });
|
||||
expect((await app.inject({ method: "POST", url: "/mcp", payload: {} })).statusCode).toBe(401);
|
||||
const init = (await rpc({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26" } })).json();
|
||||
expect(init.result.serverInfo.name).toBe("khb-todo");
|
||||
expect((await rpc({ jsonrpc: "2.0", method: "notifications/initialized" })).statusCode).toBe(202);
|
||||
const list = (await rpc({ jsonrpc: "2.0", id: 2, method: "tools/list" })).json();
|
||||
expect(list.result.tools.map((t: { name: string }) => t.name)).toEqual(expect.arrayContaining(["todo_search", "todo_create", "todo_snooze", "todo_control_create", "todo_stale"]));
|
||||
const search = (await rpc({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "todo_search", arguments: { q: "tile" } } })).json();
|
||||
expect(JSON.parse(search.result.content[0].text).map((t: { name: string }) => t.name)).toContain("Order tile");
|
||||
const created = (await rpc({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "todo_create", arguments: { jobId: JOB, name: "Via MCP" } } })).json();
|
||||
expect(JSON.parse(created.result.content[0].text).status).toBe("done");
|
||||
const denied = (await rpc({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "todo_create", arguments: { jobId: OTHER_JOB, name: "no" } } })).json();
|
||||
expect(denied.result.isError).toBe(true); // токен привязан к менеджеру MGR: чужой проект недоступен
|
||||
expect((await rpc({ jsonrpc: "2.0", id: 6, method: "nope" })).json().error.code).toBe(-32601);
|
||||
expect((await app.inject({ method: "GET", url: "/mcp" })).statusCode).toBe(405);
|
||||
});
|
||||
});
|
||||
});
|
||||
51
packages/todo_service/src/settings.ts
Normal file
51
packages/todo_service/src/settings.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const todoServiceSchema = z.object({
|
||||
http: z.object({ host: z.string().default("127.0.0.1"), port: z.number().default(8094), token: z.string().min(1) }),
|
||||
/** Проекты JobTread, куда сервису разрешено писать (создавать, менять, закрывать). Пусто - запись запрещена. */
|
||||
allowedJobIds: z.array(z.string()).default([]),
|
||||
webhook: z
|
||||
.object({
|
||||
/** Публичный базовый адрес (https://todo.khbuild.freeddns.org); с secret образует адрес вебхука JobTread. */
|
||||
publicBaseUrl: z.string().optional(),
|
||||
secret: z.string().min(8).optional(),
|
||||
/** Регистрировать вебхук в JobTread при старте, если его нет. */
|
||||
autoRegister: z.boolean().default(false),
|
||||
})
|
||||
.default({}),
|
||||
poll: z.object({ intervalSeconds: z.number().default(300), backfillOnStart: z.boolean().default(true) }).default({}),
|
||||
control: z.object({ enabled: z.boolean().default(true), tickSeconds: z.number().default(600), quietDays: z.number().default(2) }).default({}),
|
||||
/** Доставка событий агентам (POST на сервис агентов). Выключено, пока агенты не переключены; события доступны через GET /events. */
|
||||
notify: z
|
||||
.object({
|
||||
enabled: z.boolean().default(false),
|
||||
url: z.string().optional(),
|
||||
token: z.string().optional(),
|
||||
fromHour: z.number().default(7),
|
||||
toHour: z.number().default(19),
|
||||
})
|
||||
.default({}),
|
||||
mcp: z
|
||||
.object({
|
||||
enabled: z.boolean().default(true),
|
||||
/** Публичный адрес сервиса (для metadata защищённого ресурса). */
|
||||
publicUrl: z.string().optional(),
|
||||
/** Keycloak: issuer realm (https://keycloak.../realms/khbuild); JWT проверяется по JWKS. */
|
||||
issuer: z.string().optional(),
|
||||
audience: z.string().optional(),
|
||||
/** Статические токены (боты, проверки): токен -> person (необязателен: без person - права администратора). */
|
||||
staticTokens: z.array(z.object({ token: z.string().min(16), personId: z.string().uuid().optional(), name: z.string().optional() })).default([]),
|
||||
})
|
||||
.default({}),
|
||||
defaults: z
|
||||
.object({
|
||||
dueWorkdays: z.number().default(3),
|
||||
controlOffsetDays: z.number().default(2),
|
||||
staleDays: z.number().default(21),
|
||||
/** Дописывать в конец описания строку "Review: ДД.ММ" при отложении. */
|
||||
reviewLine: z.boolean().default(false),
|
||||
requestDeadlineSeconds: z.number().default(300),
|
||||
})
|
||||
.default({}),
|
||||
});
|
||||
export type TodoServiceSettings = z.infer<typeof todoServiceSchema>;
|
||||
65
packages/todo_service/src/testing.ts
Normal file
65
packages/todo_service/src/testing.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { PaveError, type JtApi, type JtEventRef, type JtTask, type TaskWrite } from "./jt.js";
|
||||
|
||||
/** Подмена JobTread для тестов: задачи в памяти, имитация недоступности и журнал вызовов. */
|
||||
export class FakeJt implements JtApi {
|
||||
organizationId = "org";
|
||||
tasks = new Map<string, JtTask>();
|
||||
calls: string[] = [];
|
||||
/** Сколько следующих запросов записи завершатся ошибкой "JobTread недоступен" (retryable). */
|
||||
failWrites = 0;
|
||||
webhooks: { id: string; url: string }[] = [];
|
||||
private seq = 0;
|
||||
|
||||
private guard(call: string): void {
|
||||
this.calls.push(call);
|
||||
if (this.failWrites > 0) {
|
||||
this.failWrites--;
|
||||
throw new PaveError("JobTread недоступен: test", true);
|
||||
}
|
||||
}
|
||||
|
||||
async getTask(id: string): Promise<JtTask | null> {
|
||||
return this.tasks.get(id) ?? null;
|
||||
}
|
||||
async listOpenTodos(): Promise<JtTask[]> {
|
||||
return [...this.tasks.values()].filter((t) => t.isToDo && (t.progress ?? 0) < 1);
|
||||
}
|
||||
async createTask(a: { jobId: string; name: string } & TaskWrite): Promise<JtTask> {
|
||||
this.guard("createTask");
|
||||
const id = `T${String(++this.seq).padStart(7, "0")}x`;
|
||||
const t: JtTask = {
|
||||
id, jobId: a.jobId, name: a.name, description: a.description ?? null, assigneeIds: a.assignedMembershipIds ?? [],
|
||||
startDate: a.endDate ?? null, endDate: a.endDate ?? null, progress: null, isToDo: true, createdAt: new Date().toISOString(),
|
||||
};
|
||||
this.tasks.set(id, t);
|
||||
return { ...t };
|
||||
}
|
||||
async updateTask(id: string, p: TaskWrite): Promise<void> {
|
||||
this.guard("updateTask");
|
||||
const t = this.tasks.get(id);
|
||||
if (!t) throw new PaveError("not found");
|
||||
if (p.name !== undefined) t.name = p.name;
|
||||
if (p.description !== undefined) t.description = p.description;
|
||||
if (p.endDate !== undefined) t.endDate = t.startDate = p.endDate;
|
||||
if (p.progress !== undefined) t.progress = p.progress;
|
||||
if (p.assignedMembershipIds !== undefined) t.assigneeIds = p.assignedMembershipIds;
|
||||
}
|
||||
async deleteTask(id: string): Promise<void> {
|
||||
this.guard("deleteTask");
|
||||
this.tasks.delete(id);
|
||||
}
|
||||
async recentTaskEvents(): Promise<JtEventRef[]> {
|
||||
return [];
|
||||
}
|
||||
async listWebhooks(): Promise<{ id: string; url: string }[]> {
|
||||
return this.webhooks;
|
||||
}
|
||||
async createWebhook(url: string): Promise<string> {
|
||||
const id = `W${this.webhooks.length + 1}`;
|
||||
this.webhooks.push({ id, url });
|
||||
return id;
|
||||
}
|
||||
async deleteWebhook(id: string): Promise<void> {
|
||||
this.webhooks = this.webhooks.filter((w) => w.id !== id);
|
||||
}
|
||||
}
|
||||
129
packages/todo_service/src/tools/khb-todo.ts
Normal file
129
packages/todo_service/src/tools/khb-todo.ts
Normal file
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* khb-todo: команда для консольных агентов (как khb-sql и khb-drive) поверх REST todo_service.
|
||||
* Окружение: KHB_TODO_URL, KHB_TODO_TOKEN, KHB_TODO_CALLER (person id вызывающего; без него - права администратора).
|
||||
* Вывод - JSON. Подробности: khb-todo help.
|
||||
*/
|
||||
|
||||
const HELP = `khb-todo <команда> [аргументы] (вывод JSON)
|
||||
|
||||
list [--assignee me|<membership>] [--job ID] [--kind todo|reminder|control] [--status open|done|all]
|
||||
[--due-before YYYY-MM-DD] [--review-due] [--q ТЕКСТ] [--limit N]
|
||||
get <id>
|
||||
create --job ID --name ТЕКСТ [--description ТЕКСТ] [--due YYYY-MM-DD] [--assignee-person UUID]... [--assignee MEMBERSHIP]...
|
||||
[--kind todo|reminder|control] [--key ИДЕМПОТЕНТНЫЙ_КЛЮЧ]
|
||||
update <id> [--name ..] [--description ..] [--due ..] [--kind ..] [--review-date ДАТА|none]
|
||||
close <id> reopen <id> delete <id>
|
||||
snooze <id> (--until YYYY-MM-DD | --days N)
|
||||
keep <id> (Keep confirmed: больше не попадает в проверку устаревания)
|
||||
control --job ID --controller UUID --exec-name ТЕКСТ --exec-description ТЕКСТ --exec-due ДАТА
|
||||
--exec-person UUID --control-name ТЕКСТ --control-description ТЕКСТ [--key КЛЮЧ]
|
||||
stale [--days N] (открытые Reminder/Control старше 3 недель без Keep confirmed)
|
||||
close-batch <id>...
|
||||
events [--pending] [--after N] ack <id>...
|
||||
request <id> (состояние запроса, если запись поставлена в очередь)
|
||||
`;
|
||||
|
||||
function parse(argv: string[]): { pos: string[]; opt: Record<string, string[]> } {
|
||||
const pos: string[] = [];
|
||||
const opt: Record<string, string[]> = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i]!;
|
||||
if (a.startsWith("--")) {
|
||||
const k = a.slice(2);
|
||||
const next = argv[i + 1];
|
||||
if (next === undefined || next.startsWith("--")) (opt[k] ??= []).push("true");
|
||||
else (opt[k] ??= []).push(argv[++i]!);
|
||||
} else pos.push(a);
|
||||
}
|
||||
return { pos, opt };
|
||||
}
|
||||
|
||||
const base = process.env.KHB_TODO_URL;
|
||||
const token = process.env.KHB_TODO_TOKEN;
|
||||
const callerPerson = process.env.KHB_TODO_CALLER;
|
||||
|
||||
async function call(method: string, path: string, body?: unknown, key?: string): Promise<unknown> {
|
||||
if (!base || !token) throw new Error("не заданы KHB_TODO_URL и KHB_TODO_TOKEN");
|
||||
const res = await fetch(base.replace(/\/$/, "") + path, {
|
||||
method,
|
||||
headers: {
|
||||
authorization: `Bearer ${token}`,
|
||||
...(callerPerson ? { "x-caller-person": callerPerson } : {}),
|
||||
...(body !== undefined ? { "content-type": "application/json" } : {}),
|
||||
...(key ? { "idempotency-key": key } : {}),
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const text = await res.text();
|
||||
let json: unknown = text;
|
||||
try {
|
||||
json = JSON.parse(text);
|
||||
} catch {
|
||||
/* оставляем текст */
|
||||
}
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}: ${typeof json === "object" && json && "error" in json ? String((json as { error: unknown }).error) : text}`);
|
||||
return json;
|
||||
}
|
||||
|
||||
const qs = (o: Record<string, string | undefined>): string => {
|
||||
const p = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(o)) if (v !== undefined) p.set(k, v);
|
||||
const s = p.toString();
|
||||
return s ? `?${s}` : "";
|
||||
};
|
||||
|
||||
async function main(): Promise<unknown> {
|
||||
const [cmd, ...rest] = process.argv.slice(2);
|
||||
const { pos, opt } = parse(rest);
|
||||
const o = (k: string): string | undefined => opt[k]?.[0];
|
||||
const id = pos[0];
|
||||
const need = (v: string | undefined, what: string): string => {
|
||||
if (!v) throw new Error(`нужно ${what}`);
|
||||
return v;
|
||||
};
|
||||
switch (cmd) {
|
||||
case "list":
|
||||
return call("GET", `/todos${qs({ assignee: o("assignee"), job: o("job"), kind: o("kind"), status: o("status"), due_before: o("due-before"), review_due: o("review-due") ? "1" : undefined, q: o("q"), limit: o("limit") })}`);
|
||||
case "get": return call("GET", `/todos/${need(id, "id")}`);
|
||||
case "create":
|
||||
return call("POST", "/todos", { jobId: need(o("job"), "--job"), name: need(o("name"), "--name"), description: o("description"), due: o("due"), assigneePersonIds: opt["assignee-person"], assigneeMembershipIds: opt.assignee, kind: o("kind") }, o("key"));
|
||||
case "update": {
|
||||
const rd = o("review-date");
|
||||
return call("PATCH", `/todos/${need(id, "id")}`, { name: o("name"), description: o("description"), due: o("due"), kind: o("kind"), ...(rd !== undefined ? { reviewDate: rd === "none" ? null : rd } : {}) });
|
||||
}
|
||||
case "close": return call("POST", `/todos/${need(id, "id")}/close`);
|
||||
case "reopen": return call("POST", `/todos/${need(id, "id")}/reopen`);
|
||||
case "delete": return call("DELETE", `/todos/${need(id, "id")}`);
|
||||
case "snooze": return call("POST", `/todos/${need(id, "id")}/snooze`, { until: o("until"), days: o("days") ? Number(o("days")) : undefined });
|
||||
case "keep": return call("POST", `/todos/${need(id, "id")}/keep`);
|
||||
case "control":
|
||||
return call(
|
||||
"POST", "/control",
|
||||
{
|
||||
jobId: need(o("job"), "--job"), controllerPersonId: need(o("controller"), "--controller"),
|
||||
executor: { name: need(o("exec-name"), "--exec-name"), description: o("exec-description"), due: o("exec-due"), assigneePersonIds: opt["exec-person"], assigneeMembershipIds: opt["exec-assignee"] },
|
||||
control: { name: need(o("control-name"), "--control-name"), description: o("control-description") },
|
||||
},
|
||||
o("key"),
|
||||
);
|
||||
case "stale": return call("GET", `/todos/stale${qs({ days: o("days") })}`);
|
||||
case "close-batch": return call("POST", "/todos/close-batch", { ids: pos });
|
||||
case "events": return call("GET", `/events${qs({ pending: o("pending") ? "1" : undefined, after: o("after") })}`);
|
||||
case "ack": return call("POST", "/events/ack", { ids: pos.map(Number) });
|
||||
case "request": return call("GET", `/requests/${need(id, "id")}`);
|
||||
default:
|
||||
process.stdout.write(HELP);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
main().then(
|
||||
(r) => {
|
||||
if (r !== undefined) process.stdout.write(JSON.stringify(r, null, 2) + "\n");
|
||||
},
|
||||
(e) => {
|
||||
process.stderr.write(`khb-todo: ${e instanceof Error ? e.message : String(e)}\n`);
|
||||
process.exit(1);
|
||||
},
|
||||
);
|
||||
126
packages/todo_service/src/watchers.ts
Normal file
126
packages/todo_service/src/watchers.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
import { addDays, localDate, type Logger, type Pool } from "khb_common";
|
||||
import type { TodoCore } from "./core.js";
|
||||
import type { JtApi } from "./jt.js";
|
||||
import { isClosed } from "./rules.js";
|
||||
import type { TodoServiceSettings } from "./settings.js";
|
||||
|
||||
/**
|
||||
* Слежение (переехало из агентов): Control (исполнитель закрыл - "выполнено", срок наступил и действий нет - "просрочено"),
|
||||
* review_date. Сервис решает, ЧТО произошло, и пишет событие; агент решает, ЧТО сказать. Control todo сервис НЕ закрывает.
|
||||
*/
|
||||
export class Watchers {
|
||||
constructor(
|
||||
private readonly core: TodoCore,
|
||||
private readonly pool: Pool,
|
||||
private readonly jt: JtApi,
|
||||
private readonly settings: TodoServiceSettings,
|
||||
private readonly tz: string,
|
||||
private readonly log: Logger,
|
||||
private readonly now: () => Date = () => new Date(),
|
||||
) {}
|
||||
|
||||
private async item(id: string): Promise<{ progress: number | null; deleted: boolean; lastEventAt: Date | null; createdAt: Date | null; name: string; known: boolean }> {
|
||||
let r = (await this.pool.query("select progress::float8 as progress, is_deleted, last_event_at, jt_created_at, name from todo_item where task_id = $1", [id])).rows[0];
|
||||
if (!r) {
|
||||
await this.core.syncTask(id).catch(() => false);
|
||||
r = (await this.pool.query("select progress::float8 as progress, is_deleted, last_event_at, jt_created_at, name from todo_item where task_id = $1", [id])).rows[0];
|
||||
}
|
||||
if (!r) return { progress: null, deleted: false, lastEventAt: null, createdAt: null, name: "", known: false };
|
||||
return { progress: r.progress, deleted: !!r.is_deleted, lastEventAt: r.last_event_at, createdAt: r.jt_created_at, name: String(r.name), known: true };
|
||||
}
|
||||
|
||||
/** Одна проверка пар Control. Возвращает число изменений статуса. */
|
||||
async controlTick(): Promise<number> {
|
||||
const now = this.now();
|
||||
const today = localDate(now, this.tz);
|
||||
const { rows } = await this.pool.query(
|
||||
"select id, task_id, linked_task_id, controller_person_id, executor_name, to_char(control_due, 'YYYY-MM-DD') as control_due, status from todo_link where status in ('active', 'overdue') order by created_at",
|
||||
);
|
||||
let changed = 0;
|
||||
for (const l of rows) {
|
||||
const exec = await this.item(String(l.linked_task_id));
|
||||
const ctrl = await this.item(String(l.task_id));
|
||||
let next: "closed" | "done" | "overdue" | null = null;
|
||||
if (ctrl.known && (ctrl.deleted || isClosed(ctrl.progress))) next = "closed"; // закрыл контролёр: слежение снимается без сообщений
|
||||
else if (exec.known && (isClosed(exec.progress) || exec.deleted)) next = "done";
|
||||
else if (l.status === "active" && l.control_due && l.control_due <= today) {
|
||||
const quiet = addDays(today, -this.settings.control.quietDays);
|
||||
const last = exec.lastEventAt ? localDate(exec.lastEventAt, this.tz) : null;
|
||||
if (!last || last <= quiet) next = "overdue";
|
||||
}
|
||||
if (!next) continue;
|
||||
await this.pool.query("update todo_link set status = $2, updated_at = now() where id = $1", [l.id, next]);
|
||||
if (next !== "closed") {
|
||||
await this.pool.query(
|
||||
"update todo_ext set done_flag = $2, overdue_flag = $3, updated_at = now() where task_id = $1",
|
||||
[l.task_id, next === "done", next === "overdue"],
|
||||
);
|
||||
await this.reconcileControlName(String(l.task_id));
|
||||
await this.pool.query("insert into todo_event (event_type, task_id, person_id, payload) values ($1,$2,$3,$4)", [
|
||||
next === "done" ? "control_done" : "control_overdue",
|
||||
l.task_id,
|
||||
l.controller_person_id,
|
||||
{ controlTaskId: l.task_id, executorTaskId: l.linked_task_id, executorName: exec.name || l.executor_name, controlDue: l.control_due },
|
||||
]);
|
||||
}
|
||||
changed++;
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
private async reconcileControlName(controlTaskId: string): Promise<void> {
|
||||
await this.core.reconcile(controlTaskId);
|
||||
}
|
||||
|
||||
/** review_date наступил: одно событие review_due на каждую дату, адресат - person исполнителя(ей), иначе без адресата. */
|
||||
async reviewTick(): Promise<number> {
|
||||
const today = localDate(this.now(), this.tz);
|
||||
const { rows } = await this.pool.query(
|
||||
`select e.task_id, to_char(e.review_date, 'YYYY-MM-DD') as review_date, i.name, i.assignee_ids,
|
||||
(select array_agg(p.id) from person p where p.jt_membership_id = any(i.assignee_ids)) as persons
|
||||
from todo_ext e join todo_item i on i.task_id = e.task_id
|
||||
where e.review_date <= $1::date and (e.review_notified_for is distinct from e.review_date) and not i.is_deleted and (i.progress is null or i.progress < 1)`,
|
||||
[today],
|
||||
);
|
||||
for (const r of rows) {
|
||||
const persons: (string | null)[] = (r.persons as string[] | null) ?? [null];
|
||||
for (const p of persons)
|
||||
await this.pool.query("insert into todo_event (event_type, task_id, person_id, payload) values ('review_due',$1,$2,$3)", [r.task_id, p, { name: r.name, reviewDate: r.review_date }]);
|
||||
await this.pool.query("update todo_ext set review_notified_for = review_date where task_id = $1", [r.task_id]);
|
||||
}
|
||||
return rows.length;
|
||||
}
|
||||
|
||||
/** Доставка событий агентам (если включена): окно часов по локальному времени; режим off у получателя - не доставляется. */
|
||||
async deliverEvents(fetchFn: typeof fetch = fetch): Promise<number> {
|
||||
const n = this.settings.notify;
|
||||
if (!n.enabled || !n.url) return 0;
|
||||
const hour = Number(new Intl.DateTimeFormat("en-US", { timeZone: this.tz, hour: "numeric", hourCycle: "h23" }).format(this.now()));
|
||||
if (hour < n.fromHour || hour >= n.toHour) return 0;
|
||||
const { rows } = await this.pool.query(
|
||||
`select ev.id, ev.event_type, ev.task_id, ev.person_id, ev.payload
|
||||
from todo_event ev left join construction_manager cm on cm.person_id = ev.person_id
|
||||
where ev.delivered_at is null and ev.person_id is not null and not (coalesce(cm.agent_paused, false) and cm.pause_mode = 'off')
|
||||
order by ev.id limit 100`,
|
||||
);
|
||||
const byPerson = new Map<string, typeof rows>();
|
||||
for (const r of rows) byPerson.set(String(r.person_id), [...(byPerson.get(String(r.person_id)) ?? []), r]);
|
||||
let sent = 0;
|
||||
for (const [personId, list] of byPerson) {
|
||||
try {
|
||||
const res = await fetchFn(n.url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...(n.token ? { authorization: `Bearer ${n.token}` } : {}) },
|
||||
body: JSON.stringify({ kind: "todo_events", personId, events: list.map((e) => ({ id: Number(e.id), type: e.event_type, taskId: e.task_id, payload: e.payload })) }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
await this.pool.query("update todo_event set delivered_at = now(), delivery_error = null where id = any($1::bigint[])", [list.map((e) => e.id)]);
|
||||
sent += list.length;
|
||||
} catch (e) {
|
||||
await this.pool.query("update todo_event set delivery_error = $2 where id = any($1::bigint[])", [list.map((x) => x.id), String(e)]);
|
||||
this.log.warn({ personId, err: String(e) }, "доставка событий агенту не удалась");
|
||||
}
|
||||
}
|
||||
return sent;
|
||||
}
|
||||
}
|
||||
6
packages/todo_service/tsconfig.json
Normal file
6
packages/todo_service/tsconfig.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
|
||||
"include": ["src"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
20
pnpm-lock.yaml
generated
20
pnpm-lock.yaml
generated
@@ -129,6 +129,21 @@ importers:
|
||||
specifier: 3.25.76
|
||||
version: 3.25.76
|
||||
|
||||
packages/todo_service:
|
||||
dependencies:
|
||||
fastify:
|
||||
specifier: ^5.2.0
|
||||
version: 5.12.5
|
||||
jose:
|
||||
specifier: ^5.9.6
|
||||
version: 5.10.0
|
||||
khb_common:
|
||||
specifier: workspace:*
|
||||
version: link:../khb_common
|
||||
zod:
|
||||
specifier: 3.25.76
|
||||
version: 3.25.76
|
||||
|
||||
packages:
|
||||
|
||||
'@esbuild/aix-ppc64@0.21.5':
|
||||
@@ -950,6 +965,9 @@ packages:
|
||||
isarray@2.0.5:
|
||||
resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==}
|
||||
|
||||
jose@5.10.0:
|
||||
resolution: {integrity: sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==}
|
||||
|
||||
json-schema-ref-resolver@3.0.1:
|
||||
resolution: {integrity: sha512-w+HwgljXpVwZ3IidoUR1qPZxSOQ+NRQWuVe6a5pe8XbHsNZE4UAwVPUvzZagn7yBKbJtt6UJnRFYbNTRPZI45Q==}
|
||||
|
||||
@@ -2403,6 +2421,8 @@ snapshots:
|
||||
|
||||
isarray@2.0.5: {}
|
||||
|
||||
jose@5.10.0: {}
|
||||
|
||||
json-schema-ref-resolver@3.0.1:
|
||||
dependencies:
|
||||
dequal: 2.0.3
|
||||
|
||||
@@ -80,4 +80,14 @@
|
||||
defaultDays: 30,
|
||||
},
|
||||
|
||||
todo_service: { // todo поверх JobTread и Supabase (todo.khbuild.freeddns.org): REST, MCP, вебхуки
|
||||
http: { host: "127.0.0.1", port: 8094, token: "<token для внутренних вызовов и команды khb-todo>" },
|
||||
allowedJobIds: ["<id проекта JobTread, куда сервису разрешено писать>"],
|
||||
webhook: { publicBaseUrl: "https://todo.khbuild.freeddns.org", secret: "<секрет в адресе вебхука, 8+ знаков>", autoRegister: true },
|
||||
poll: { intervalSeconds: 300, backfillOnStart: true },
|
||||
control: { enabled: true, tickSeconds: 600, quietDays: 2 },
|
||||
notify: { enabled: false, url: "http://khb-assistant-prep:8085/chat/todo-events", token: "<токен сервиса агентов>", fromHour: 7, toHour: 19 },
|
||||
mcp: { enabled: true, publicUrl: "https://todo.khbuild.freeddns.org", issuer: "https://keycloak.khbuild.freeddns.org/realms/khbuild", staticTokens: [] },
|
||||
defaults: { dueWorkdays: 3, controlOffsetDays: 2, staleDays: 21, reviewLine: false },
|
||||
},
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user