BRM-10: сервис Knowledge Base, согласования A/B/C, аудит, деплой-конфиг

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-15 14:02:05 +05:00
parent cd949be88b
commit cb798de74f
31 changed files with 3016 additions and 12 deletions

4
.dockerignore Normal file
View File

@ -0,0 +1,4 @@
node_modules
dist
.git
.env

1
.gitignore vendored
View File

@ -2,3 +2,4 @@ node_modules/
.env
.env.local
.DS_Store
dist/

View File

@ -5,3 +5,9 @@
## Решения
- Открытый веб-поиск не находит профили Татьяны Сафаровой: ссылки в брифе не выдумываем, ставим «уточнить у Татьяны». BRM-3…BRM-10 — дубли, закрывает PM.
- BRM-4: бриф в docs/positioning-brief.md (≤60 строк, гипотезы с пометкой «Допущение»); дубли BRM-1…10 закрывает PM; ветки от main.
## Команды
- Проверки: pnpm lint|typecheck|test|build; миграции — migrations/*.sql, pnpm db:migrate (нужны DATABASE_URL, API_TOKEN); тесты на PGlite (tests/helpers.ts), локального Postgres нет.
## Грабли
- typescript-eslint не работает с TS 7 — держим typescript@6; pnpm 11 требует allowBuilds (pnpm-workspace.yaml) и его копирования в Dockerfile.

View File

@ -1 +1,20 @@
{"slug":"brendmanager","key":"BRM","name":"Бренд менеджер","peppaUrl":"https://peppa.telecom.quest"}
{
"slug": "brendmanager",
"key": "BRM",
"name": "Бренд менеджер",
"peppaUrl": "https://peppa.telecom.quest",
"checks": {
"install": "pnpm install --frozen-lockfile",
"lint": "pnpm lint",
"typecheck": "pnpm typecheck",
"test": "pnpm test",
"build": "pnpm build"
},
"deploy": {
"compose": "deploy/compose.yml",
"service": "web",
"port": 3000,
"health": "/healthz",
"migrate": "pnpm db:migrate"
}
}

16
Dockerfile Normal file
View File

@ -0,0 +1,16 @@
# Заготовка для Node.js (pnpm). Скопируй в ./Dockerfile и поправь под проект.
# Приложение слушает $PORT и отвечает 200 на GET /healthz (deploy.health).
FROM node:22-bookworm-slim AS build
WORKDIR /app
RUN corepack enable
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml ./
RUN pnpm install --frozen-lockfile
COPY . .
RUN pnpm build
FROM node:22-bookworm-slim
WORKDIR /app
ENV NODE_ENV=production PORT=3000
COPY --from=build /app ./
EXPOSE 3000
CMD ["node", "dist/index.js"]

View File

@ -8,14 +8,32 @@ services:
restart: unless-stopped
environment:
PORT: "${APP_PORT:-3000}"
DATABASE_URL: "${DATABASE_URL:-postgres://brand:brand@db:5432/brand}"
API_TOKEN: "${API_TOKEN}"
depends_on:
- db
networks:
- traefik_default
- default
labels:
- traefik.enable=true
- traefik.docker.network=traefik_default
- traefik.http.routers.${ROUTER}.rule=Host(`${HOST}`)
- traefik.http.routers.${ROUTER}.entrypoints=web
- traefik.http.services.${ROUTER}.loadbalancer.server.port=${APP_PORT:-3000}
db:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_USER: brand
POSTGRES_PASSWORD: brand
POSTGRES_DB: brand
volumes:
- dbdata:/var/lib/postgresql/data
networks:
- default
volumes:
dbdata:
networks:
traefik_default:
external: true

3
eslint.config.js Normal file
View File

@ -0,0 +1,3 @@
import tseslint from "typescript-eslint";
export default tseslint.config({ ignores: ["dist", "node_modules"] }, ...tseslint.configs.recommended);

101
migrations/001_init.sql Normal file
View File

@ -0,0 +1,101 @@
create type fact_status as enum ('public_confirmed', 'internal_confirmed', 'hypothesis', 'outdated', 'forbidden');
create table source_evidence (
id serial primary key,
title text not null,
url text,
note text,
status fact_status not null default 'hypothesis',
confidence int check (confidence between 0 and 100),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create table person_profile (
id serial primary key,
full_name text not null,
headline text,
bio text,
status fact_status not null default 'hypothesis',
confidence int check (confidence between 0 and 100),
source_evidence_id int references source_evidence(id),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create table career_history (
id serial primary key,
organization text not null,
position text,
start_year int,
end_year int,
is_current boolean not null default false,
status fact_status not null default 'hypothesis',
confidence int check (confidence between 0 and 100),
source_evidence_id int references source_evidence(id),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create table credentials (
id serial primary key,
title text not null,
issuer text,
year int,
document_url text,
status fact_status not null default 'hypothesis',
confidence int check (confidence between 0 and 100),
source_evidence_id int references source_evidence(id),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create table cases (
id serial primary key,
title text not null,
problem text,
role text,
solution text,
scale text,
result text,
metrics text,
public_use_permitted boolean not null default false,
status fact_status not null default 'hypothesis',
confidence int check (confidence between 0 and 100),
source_evidence_id int references source_evidence(id),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create table action_policy (
action text primary key,
mode char(1) not null check (mode in ('A', 'B', 'C')),
granted boolean not null default false
);
create table approvals (
id serial primary key,
action text not null references action_policy(action),
status text not null default 'pending' check (status in ('pending', 'approved', 'rejected', 'used')),
payload jsonb,
requested_at timestamptz not null default now(),
decided_at timestamptz
);
create table audit_logs (
id serial primary key,
actor text not null,
action text not null,
entity text not null,
before jsonb,
after jsonb,
created_at timestamptz not null default now()
);
insert into action_policy (action, mode) values
('create_hypothesis', 'A'),
('schedule_approved_content', 'B'),
('set_public_positioning', 'C'),
('publish_sensitive_case', 'C'),
('send_commercial_offer', 'C'),
('send_personal_letter', 'C');

View File

@ -1,20 +1,20 @@
## 1. Бриф
- [ ] 1.1 Написать `docs/brief-brm-10.md` из ТЗ BRM-10: цель, аудитория, 2–3 площадки, что уже есть, вопросы к Татьяне; неизвестное — «не определено»
- [x] 1.1 Написать `docs/brief-brm-10.md` из ТЗ BRM-10: цель, аудитория, 2–3 площадки, что уже есть, вопросы к Татьяне; неизвестное — «не определено»
## 2. Каркас сервиса
- [ ] 2.1 Инициализировать TS-проект (Fastify, vitest, eslint), `GET /healthz`, чтение `$PORT`; заполнить `checks` в `.peppa/project.json`
- [ ] 2.2 Подключить Postgres, раннер миграций (`db:migrate`), Bearer-аутентификацию по `API_TOKEN`
- [ ] 2.3 Адаптировать `Dockerfile` и `deploy/compose.yml`, проверить `docker build` и `/healthz`
- [x] 2.1 Инициализировать TS-проект (Fastify, vitest, eslint), `GET /healthz`, чтение `$PORT`; заполнить `checks` в `.peppa/project.json`
- [x] 2.2 Подключить Postgres, раннер миграций (`db:migrate`), Bearer-аутентификацию по `API_TOKEN`
- [x] 2.3 Адаптировать `Dockerfile` и `deploy/compose.yml`, проверить `docker build` и `/healthz`
## 3. Knowledge Base
- [ ] 3.1 Миграции: `source_evidence`, `person_profile`, `career_history`, `credentials`, `cases`, enum `fact_status`
- [ ] 3.2 CRUD API с валидацией статусов (422) и фильтром `audience=public`
- [ ] 3.3 Тесты по сценариям spec `brand-knowledge-base`
- [x] 3.1 Миграции: `source_evidence`, `person_profile`, `career_history`, `credentials`, `cases`, enum `fact_status`
- [x] 3.2 CRUD API с валидацией статусов (422) и фильтром `audience=public`
- [x] 3.3 Тесты по сценариям spec `brand-knowledge-base`
## 4. Согласования и аудит
- [ ] 4.1 Миграции `approvals`, `audit_logs`, таблица политики действий (A/B/C)
- [ ] 4.2 Запись в аудит в транзакции с изменением; проверка режима C
- [ ] 4.3 Тесты по сценариям spec `approvals-audit`
- [x] 4.1 Миграции `approvals`, `audit_logs`, таблица политики действий (A/B/C)
- [x] 4.2 Запись в аудит в транзакции с изменением; проверка режима C
- [x] 4.3 Тесты по сценариям spec `approvals-audit`
## 5. Завершение
- [ ] 5.1 Записать память проекта, прогнать `bash .gitea/peppa-check.sh` по всем проверкам и `openspec validate brm-10-brief-and-foundation`
- [x] 5.1 Записать память проекта, прогнать `bash .gitea/peppa-check.sh` по всем проверкам и `openspec validate brm-10-brief-and-foundation`

View File

@ -0,0 +1,38 @@
# approvals-audit Specification
## Purpose
TBD - created by archiving change brm-10-brief-and-foundation. Update Purpose after archive.
## Requirements
### Requirement: Режимы полномочий
Система SHALL сопоставлять каждому действию режим A (автономно), B (в утверждённых пределах) или C (только с одобрением Татьяны). Действие режима C SHALL выполняться только при одобренном согласовании.
#### Scenario: Режим C без одобрения
- **GIVEN** действие `set_public_positioning` относится к режиму C
- **WHEN** оно запрошено без одобренного согласования
- **THEN** API отвечает 403
- **AND** создано согласование со статусом `pending`
#### Scenario: Режим C с одобрением
- **GIVEN** согласование на `set_public_positioning` со статусом `approved`
- **WHEN** действие запрошено с этим согласованием
- **THEN** действие выполнено, API отвечает 200
#### Scenario: Режим A
- **GIVEN** действие `create_hypothesis` относится к режиму A
- **WHEN** оно запрошено без согласования
- **THEN** действие выполнено
### Requirement: Журнал действий
Каждое изменение данных SHALL записываться в `audit_logs` (кто, что, над какой сущностью, значения до и после) в той же транзакции; значения секретов SHALL NOT попадать в журнал.
#### Scenario: Изменение пишет журнал
- **GIVEN** запись карьеры с id 5 и должностью «Директор»
- **WHEN** владелец меняет должность на «Генеральный директор»
- **THEN** в `audit_logs` есть запись с entity `career_history/5`, before «Директор», after «Генеральный директор»
#### Scenario: Без токена
- **GIVEN** запрос без заголовка Authorization
- **WHEN** вызывается `POST /cases`
- **THEN** API отвечает 401 и журнал не меняется

View File

@ -23,3 +23,18 @@ TBD - created by archiving change brm-1-brand-brief. Update Purpose after archiv
- **GIVEN** ссылку на Instagram не удалось найти в открытых источниках
- **WHEN** читается раздел «Где её видно сейчас»
- **THEN** у Instagram стоит «уточнить у Татьяны», ссылка не придумана
### Requirement: Одностраничный бриф
В репозитории SHALL быть документ `docs/brief-brm-10.md` с разделами «Цель», «Аудитория», «Площадки», «Что уже есть» и «Вопросы к Татьяне». Каждый раздел SHALL быть заполнен или помечен «не определено».
#### Scenario: Все разделы на месте
- **GIVEN** открыт файл `docs/brief-brm-10.md`
- **WHEN** проверяются заголовки разделов
- **THEN** присутствуют «Цель», «Аудитория», «Площадки», «Что уже есть», «Вопросы к Татьяне»
- **AND** пустых разделов нет
#### Scenario: Неизвестное не придумывается
- **GIVEN** срок цели не назван ни в стори, ни в источниках
- **WHEN** читается раздел «Цель»
- **THEN** срок указан как «не определено»
- **BUT** контент-плана и обещаний по цифрам в брифе нет

View File

@ -0,0 +1,40 @@
# brand-knowledge-base Specification
## Purpose
TBD - created by archiving change brm-10-brief-and-foundation. Update Purpose after archive.
## Requirements
### Requirement: Факты со статусом достоверности
Система SHALL хранить факты о Татьяне (профиль, карьера, квалификации, кейсы) со статусом `public_confirmed`, `internal_confirmed`, `hypothesis`, `outdated` или `forbidden`, датами создания и актуализации и ссылкой на источник.
#### Scenario: Создание факта с источником
- **GIVEN** авторизованный владелец и источник «LinkedIn-профиль» с id 1
- **WHEN** он создаёт запись карьеры «Казахтелеком» со статусом `hypothesis` и `source_evidence_id` 1
- **THEN** API отвечает 201 и возвращает запись с `created_at` и `updated_at`
#### Scenario: Недопустимый статус
- **GIVEN** авторизованный владелец
- **WHEN** он создаёт кейс со статусом «точно правда»
- **THEN** API отвечает 422 и запись не создаётся
### Requirement: Публичный вывод только подтверждённого
Публичный вывод (`audience=public`) SHALL содержать только записи `public_confirmed`; кейс SHALL попадать в него только при `public_use_permitted = true`.
#### Scenario: Гипотеза скрыта
- **GIVEN** две записи карьеры: «Казпочта» `public_confirmed` и «Грант» `hypothesis`
- **WHEN** запрашивается `GET /career?audience=public`
- **THEN** в ответе одна запись — «Казпочта»
#### Scenario: Кейс без разрешения
- **GIVEN** кейс `public_confirmed` с `public_use_permitted = false`
- **WHEN** запрашивается `GET /cases?audience=public`
- **THEN** кейса в ответе нет
### Requirement: Историческая роль не текущая
Запись карьеры SHALL иметь признак `is_current`; публичный профиль SHALL выводить как текущие только записи с `is_current = true`.
#### Scenario: Прошлая должность
- **GIVEN** запись «Телеконтакт, генеральный директор» с `is_current = false`
- **WHEN** запрашивается публичный профиль
- **THEN** эта запись в разделе «текущие роли» отсутствует

32
package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "brendmanager",
"version": "0.1.0",
"private": true,
"type": "module",
"engines": {
"node": ">=22"
},
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"lint": "eslint .",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"db:migrate": "node dist/migrate.js"
},
"dependencies": {
"fastify": "^5.12.8",
"pg": "^8.23.1"
},
"devDependencies": {
"@electric-sql/pglite": "^0.5.16",
"@types/node": "^26.6.6",
"@types/pg": "^8.23.1",
"eslint": "^10.15.0",
"tsx": "^4.23.15",
"typescript": "^6.0.3",
"typescript-eslint": "^8.72.2",
"vitest": "^5.1.0"
}
}

2272
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

2
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,2 @@
allowBuilds:
esbuild: true

145
src/app.ts Normal file
View File

@ -0,0 +1,145 @@
import Fastify, { type FastifyInstance } from "fastify";
import type { Db, Queryable } from "./db.js";
import { RESOURCES, validate, type Resource } from "./resources.js";
export interface AppOptions {
db: Db;
apiToken: string;
}
const SECRET_KEY = /token|secret|password|api[_-]?key/i;
export function redact(value: unknown): unknown {
if (Array.isArray(value)) return value.map(redact);
if (value && typeof value === "object") {
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY.test(k) ? "[redacted]" : redact(v)]));
}
return value;
}
async function audit(q: Queryable, action: string, entity: string, before: unknown, after: unknown, actor = "owner") {
await q.query("insert into audit_logs (actor, action, entity, before, after) values ($1,$2,$3,$4,$5)", [
actor, action, entity, before == null ? null : JSON.stringify(redact(before)), after == null ? null : JSON.stringify(redact(after)),
]);
}
export function buildApp({ db, apiToken }: AppOptions): FastifyInstance {
const app = Fastify();
app.get("/healthz", async () => ({ ok: true }));
app.addHook("onRequest", async (req, reply) => {
if (req.url === "/healthz") return;
if (req.headers.authorization !== `Bearer ${apiToken}`) return reply.code(401).send({ error: "unauthorized" });
});
for (const res of RESOURCES) registerResource(app, db, res);
app.get("/public-profile", async () => {
const profile = await db.query("select * from person_profile where status = 'public_confirmed' order by id limit 1");
const roles = await db.query<{ is_current: boolean }>("select * from career_history where status = 'public_confirmed' order by start_year desc nulls last, id");
return { profile: profile[0] ?? null, current_roles: roles.filter((r) => r.is_current), past_roles: roles.filter((r) => !r.is_current) };
});
app.get("/audit", async () => db.query("select * from audit_logs order by id desc limit 200"));
app.get("/approvals", async () => db.query("select * from approvals order by id desc"));
app.post<{ Params: { id: string }; Body: { decision?: string } }>("/approvals/:id/decision", async (req, reply) => {
const decision = req.body?.decision;
if (decision !== "approved" && decision !== "rejected") return reply.code(422).send({ error: "decision must be approved or rejected" });
return db.tx(async (q) => {
const [before] = await q.query("select * from approvals where id = $1 for update", [Number(req.params.id)]);
if (!before) return reply.code(404).send({ error: "not found" });
if ((before as { status: string }).status !== "pending") return reply.code(409).send({ error: "already decided" });
const [after] = await q.query("update approvals set status = $2, decided_at = now() where id = $1 returning *", [Number(req.params.id), decision]);
await audit(q, "decide_approval", `approvals/${req.params.id}`, before, after);
return after;
});
});
app.get("/policy", async () => db.query("select * from action_policy order by action"));
app.post<{ Params: { action: string }; Body: { approval_id?: number; payload?: unknown } }>("/actions/:action", async (req, reply) => {
const action = req.params.action;
const approvalId = req.body?.approval_id;
const payload = req.body?.payload ?? null;
return db.tx(async (q) => {
const [policy] = await q.query<{ mode: string; granted: boolean }>("select * from action_policy where action = $1", [action]);
if (!policy) return reply.code(404).send({ error: "unknown action" });
const needsApproval = policy.mode === "C" || (policy.mode === "B" && !policy.granted);
if (needsApproval) {
const [ap] = approvalId ? await q.query<{ id: number }>("select * from approvals where id = $1 and action = $2 and status = 'approved' for update", [approvalId, action]) : [];
if (!ap) {
const [created] = await q.query<{ id: number }>("insert into approvals (action, payload) values ($1, $2) returning *", [action, payload == null ? null : JSON.stringify(redact(payload))]);
await audit(q, "request_approval", `approvals/${created.id}`, null, created);
// Транзакция коммитится: согласование pending должно сохраниться.
return reply.code(403).send({ error: "approval required", mode: policy.mode, approval_id: created.id });
}
await q.query("update approvals set status = 'used' where id = $1", [ap.id]);
}
await audit(q, `action:${action}`, `actions/${action}`, null, { mode: policy.mode, approval_id: approvalId ?? null, payload });
return { ok: true, action, mode: policy.mode };
});
});
return app;
}
function registerResource(app: FastifyInstance, db: Db, res: Resource) {
const base = `/${res.route}`;
app.get<{ Querystring: { audience?: string } }>(base, async (req) => {
if (req.query.audience === "public") {
const where = ["status = 'public_confirmed'", res.publicWhere].filter(Boolean).join(" and ");
return db.query(`select * from ${res.table} where ${where} order by id`);
}
return db.query(`select * from ${res.table} order by id`);
});
app.get<{ Params: { id: string } }>(`${base}/:id`, async (req, reply) => {
const [row] = await db.query(`select * from ${res.table} where id = $1`, [Number(req.params.id)]);
return row ?? reply.code(404).send({ error: "not found" });
});
app.post(base, async (req, reply) => {
const v = validate(res, req.body, false);
if ("error" in v) return reply.code(422).send({ error: v.error });
const cols = Object.keys(v.values);
try {
const row = await db.tx(async (q) => {
const [created] = await q.query<{ id: number }>(
cols.length ? `insert into ${res.table} (${cols.join(",")}) values (${cols.map((_, i) => `$${i + 1}`).join(",")}) returning *` : `insert into ${res.table} default values returning *`,
Object.values(v.values),
);
await audit(q, "create", `${res.table}/${created.id}`, null, created);
return created;
});
return reply.code(201).send(row);
} catch (e) {
if ((e as { code?: string }).code === "23503") return reply.code(422).send({ error: "referenced record does not exist" });
throw e;
}
});
app.patch<{ Params: { id: string } }>(`${base}/:id`, async (req, reply) => {
const v = validate(res, req.body, true);
if ("error" in v) return reply.code(422).send({ error: v.error });
const cols = Object.keys(v.values);
if (!cols.length) return reply.code(422).send({ error: "nothing to update" });
const id = Number(req.params.id);
try {
return await db.tx(async (q) => {
const [before] = await q.query(`select * from ${res.table} where id = $1 for update`, [id]);
if (!before) return reply.code(404).send({ error: "not found" });
const [after] = await q.query(
`update ${res.table} set ${cols.map((c, i) => `${c} = $${i + 1}`).join(",")}, updated_at = now() where id = $${cols.length + 1} returning *`,
[...Object.values(v.values), id],
);
await audit(q, "update", `${res.table}/${id}`, before, after);
return after;
});
} catch (e) {
if ((e as { code?: string }).code === "23503") return reply.code(422).send({ error: "referenced record does not exist" });
throw e;
}
});
}

56
src/db.ts Normal file
View File

@ -0,0 +1,56 @@
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import pg from "pg";
export interface Queryable {
query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<T[]>;
}
export interface Db extends Queryable {
tx<T>(fn: (q: Queryable) => Promise<T>): Promise<T>;
close(): Promise<void>;
}
export function createPgDb(connectionString: string): Db {
const pool = new pg.Pool({ connectionString });
return {
async query<T>(sql: string, params?: unknown[]) {
return (await pool.query(sql, params)).rows as T[];
},
async tx<T>(fn: (q: Queryable) => Promise<T>) {
const client = await pool.connect();
const q: Queryable = {
async query<R>(sql: string, params?: unknown[]) {
return (await client.query(sql, params)).rows as R[];
},
};
try {
await client.query("begin");
const result = await fn(q);
await client.query("commit");
return result;
} catch (e) {
await client.query("rollback");
throw e;
} finally {
client.release();
}
},
close: () => pool.end(),
};
}
export async function migrate(db: Db, dir = join(process.cwd(), "migrations")): Promise<string[]> {
await db.query("create table if not exists schema_migrations (name text primary key, applied_at timestamptz not null default now())");
const done = new Set((await db.query<{ name: string }>("select name from schema_migrations")).map((r) => r.name));
const applied: string[] = [];
for (const file of readdirSync(dir).filter((f) => f.endsWith(".sql")).sort()) {
if (done.has(file)) continue;
const sql = readFileSync(join(dir, file), "utf8");
await db.tx(async (q) => {
await q.query(sql);
await q.query("insert into schema_migrations (name) values ($1)", [file]);
});
applied.push(file);
}
return applied;
}

13
src/index.ts Normal file
View File

@ -0,0 +1,13 @@
import { buildApp } from "./app.js";
import { createPgDb, migrate } from "./db.js";
const url = process.env.DATABASE_URL;
const token = process.env.API_TOKEN;
if (!url || !token) {
console.error("DATABASE_URL and API_TOKEN are required");
process.exit(1);
}
const db = createPgDb(url);
await migrate(db);
const app = buildApp({ db, apiToken: token });
await app.listen({ port: Number(process.env.PORT ?? 3000), host: "0.0.0.0" });

11
src/migrate.ts Normal file
View File

@ -0,0 +1,11 @@
import { createPgDb, migrate } from "./db.js";
const url = process.env.DATABASE_URL;
if (!url) {
console.error("DATABASE_URL is required");
process.exit(1);
}
const db = createPgDb(url);
const applied = await migrate(db);
console.log(applied.length ? `applied: ${applied.join(", ")}` : "no pending migrations");
await db.close();

51
src/resources.ts Normal file
View File

@ -0,0 +1,51 @@
export const FACT_STATUSES = ["public_confirmed", "internal_confirmed", "hypothesis", "outdated", "forbidden"] as const;
type FieldType = "string" | "int" | "bool";
export interface Resource {
route: string;
table: string;
fields: Record<string, { type: FieldType; required?: boolean }>;
/** Дополнительное условие публичного вывода. */
publicWhere?: string;
}
const common: Resource["fields"] = {
status: { type: "string" },
confidence: { type: "int" },
source_evidence_id: { type: "int" },
};
export const RESOURCES: Resource[] = [
{ route: "sources", table: "source_evidence", fields: { title: { type: "string", required: true }, url: { type: "string" }, note: { type: "string" }, status: { type: "string" }, confidence: { type: "int" } } },
{ route: "profile", table: "person_profile", fields: { full_name: { type: "string", required: true }, headline: { type: "string" }, bio: { type: "string" }, ...common } },
{ route: "career", table: "career_history", fields: { organization: { type: "string", required: true }, position: { type: "string" }, start_year: { type: "int" }, end_year: { type: "int" }, is_current: { type: "bool" }, ...common } },
{ route: "credentials", table: "credentials", fields: { title: { type: "string", required: true }, issuer: { type: "string" }, year: { type: "int" }, document_url: { type: "string" }, ...common } },
{
route: "cases",
table: "cases",
fields: { title: { type: "string", required: true }, problem: { type: "string" }, role: { type: "string" }, solution: { type: "string" }, scale: { type: "string" }, result: { type: "string" }, metrics: { type: "string" }, public_use_permitted: { type: "bool" }, ...common },
publicWhere: "public_use_permitted = true",
},
];
/** Возвращает очищенные значения или текст ошибки. */
export function validate(res: Resource, body: unknown, partial: boolean): { values: Record<string, unknown> } | { error: string } {
if (typeof body !== "object" || body === null || Array.isArray(body)) return { error: "body must be an object" };
const input = body as Record<string, unknown>;
const values: Record<string, unknown> = {};
for (const [name, spec] of Object.entries(res.fields)) {
const v = input[name];
if (v === undefined) {
if (spec.required && !partial) return { error: `${name} is required` };
continue;
}
if (v === null && !spec.required) { values[name] = null; continue; }
if (spec.type === "string" && typeof v !== "string") return { error: `${name} must be a string` };
if (spec.type === "int" && !Number.isInteger(v)) return { error: `${name} must be an integer` };
if (spec.type === "bool" && typeof v !== "boolean") return { error: `${name} must be a boolean` };
if (name === "status" && !(FACT_STATUSES as readonly string[]).includes(v as string)) return { error: `status must be one of ${FACT_STATUSES.join(", ")}` };
if (name === "confidence" && ((v as number) < 0 || (v as number) > 100)) return { error: "confidence must be 0..100" };
values[name] = v;
}
return { values };
}

View File

@ -0,0 +1,65 @@
import { beforeEach, describe, expect, it } from "vitest";
import { redact } from "../src/app.js";
import { setup } from "./helpers.js";
let t: Awaited<ReturnType<typeof setup>>;
beforeEach(async () => { t = await setup(); });
describe("Requirement: Режимы полномочий", () => {
it("Scenario: Режим C без одобрения", async () => {
const res = await t.call("POST", "/actions/set_public_positioning", { payload: { text: "x" } });
expect(res.statusCode).toBe(403);
const approvals = (await t.call("GET", "/approvals")).json();
expect(approvals).toHaveLength(1);
expect(approvals[0].status).toBe("pending");
});
it("Scenario: Режим C с одобрением", async () => {
const { approval_id } = (await t.call("POST", "/actions/set_public_positioning", {})).json();
await t.call("POST", `/approvals/${approval_id}/decision`, { decision: "approved" });
const res = await t.call("POST", "/actions/set_public_positioning", { approval_id });
expect(res.statusCode).toBe(200);
// одобрение одноразовое
expect((await t.call("POST", "/actions/set_public_positioning", { approval_id })).statusCode).toBe(403);
});
it("Scenario: Отклонённое согласование не открывает действие", async () => {
const { approval_id } = (await t.call("POST", "/actions/send_commercial_offer", {})).json();
await t.call("POST", `/approvals/${approval_id}/decision`, { decision: "rejected" });
expect((await t.call("POST", "/actions/send_commercial_offer", { approval_id })).statusCode).toBe(403);
});
it("Scenario: Режим A", async () => {
const res = await t.call("POST", "/actions/create_hypothesis", {});
expect(res.statusCode).toBe(200);
});
it("Scenario: неизвестное действие — 404", async () => {
expect((await t.call("POST", "/actions/nope", {})).statusCode).toBe(404);
});
});
describe("Requirement: Журнал действий", () => {
it("Scenario: Изменение пишет журнал", async () => {
const c = (await t.call("POST", "/career", { organization: "X", position: "Директор" })).json();
await t.call("PATCH", `/career/${c.id}`, { position: "Генеральный директор" });
const logs = (await t.call("GET", "/audit")).json();
const upd = logs.find((l: { entity: string; action: string }) => l.entity === `career_history/${c.id}` && l.action === "update");
expect(upd.before.position).toBe("Директор");
expect(upd.after.position).toBe("Генеральный директор");
});
it("Scenario: Без токена", async () => {
const res = await t.call("POST", "/cases", { title: "x" }, null);
expect(res.statusCode).toBe(401);
expect(await t.db.query("select * from audit_logs")).toHaveLength(0);
});
it("Scenario: секреты не попадают в журнал", () => {
expect(redact({ api_token: "abc", nested: { password: "p", ok: 1 } })).toEqual({ api_token: "[redacted]", nested: { password: "[redacted]", ok: 1 } });
});
it("healthz открыт без токена", async () => {
expect((await t.call("GET", "/healthz", undefined, null)).statusCode).toBe(200);
});
});

34
tests/helpers.ts Normal file
View File

@ -0,0 +1,34 @@
import { PGlite } from "@electric-sql/pglite";
import { buildApp } from "../src/app.js";
import { migrate, type Db, type Queryable } from "../src/db.js";
export const TOKEN = "mock-owner-token";
/** Postgres в WASM (PGlite) с тем же интерфейсом Db, что и боевой pg. */
export function createMockDb(): Db {
const pg = new PGlite();
const wrap = (c: { query: PGlite["query"]; exec: PGlite["exec"] }): Queryable => ({
async query<T>(sql: string, params?: unknown[]) {
if (params === undefined) {
const r = await c.exec(sql);
return (r[r.length - 1]?.rows ?? []) as T[];
}
return (await c.query(sql, params)).rows as T[];
},
});
const base = wrap(pg as never);
return {
...base,
tx: (fn) => pg.transaction((t) => fn(wrap(t as never))),
close: () => pg.close(),
};
}
export async function setup() {
const db = createMockDb();
await migrate(db);
const app = buildApp({ db, apiToken: TOKEN });
const call = (method: "GET" | "POST" | "PATCH", url: string, payload?: unknown, token: string | null = TOKEN) =>
app.inject({ method, url, payload: payload as object, headers: token ? { authorization: `Bearer ${token}` } : {} });
return { db, app, call };
}

View File

@ -0,0 +1,54 @@
import { beforeEach, describe, expect, it } from "vitest";
import { setup } from "./helpers.js";
let t: Awaited<ReturnType<typeof setup>>;
beforeEach(async () => { t = await setup(); });
describe("Requirement: Факты со статусом достоверности", () => {
it("Scenario: Создание факта с источником", async () => {
const src = (await t.call("POST", "/sources", { title: "LinkedIn-профиль" })).json();
const res = await t.call("POST", "/career", { organization: "Казахтелеком", status: "hypothesis", source_evidence_id: src.id });
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.created_at).toBeTruthy();
expect(body.updated_at).toBeTruthy();
expect(body.source_evidence_id).toBe(src.id);
});
it("Scenario: Недопустимый статус", async () => {
const res = await t.call("POST", "/cases", { title: "Кейс", status: "точно правда" });
expect(res.statusCode).toBe(422);
expect((await t.call("GET", "/cases")).json()).toHaveLength(0);
});
it("Scenario: несуществующий источник — 422", async () => {
const res = await t.call("POST", "/career", { organization: "X", source_evidence_id: 999 });
expect(res.statusCode).toBe(422);
});
});
describe("Requirement: Публичный вывод только подтверждённого", () => {
it("Scenario: Гипотеза скрыта", async () => {
await t.call("POST", "/career", { organization: "Казпочта", status: "public_confirmed" });
await t.call("POST", "/career", { organization: "Грант", status: "hypothesis" });
const rows = (await t.call("GET", "/career?audience=public")).json();
expect(rows.map((r: { organization: string }) => r.organization)).toEqual(["Казпочта"]);
});
it("Scenario: Кейс без разрешения", async () => {
await t.call("POST", "/cases", { title: "Закрытый", status: "public_confirmed", public_use_permitted: false });
await t.call("POST", "/cases", { title: "Открытый", status: "public_confirmed", public_use_permitted: true });
const rows = (await t.call("GET", "/cases?audience=public")).json();
expect(rows.map((r: { title: string }) => r.title)).toEqual(["Открытый"]);
});
});
describe("Requirement: Историческая роль не текущая", () => {
it("Scenario: Прошлая должность", async () => {
await t.call("POST", "/career", { organization: "Телеконтакт", position: "генеральный директор", is_current: false, status: "public_confirmed" });
await t.call("POST", "/career", { organization: "Grow Consulting", is_current: true, status: "public_confirmed" });
const body = (await t.call("GET", "/public-profile")).json();
expect(body.current_roles.map((r: { organization: string }) => r.organization)).toEqual(["Grow Consulting"]);
expect(body.past_roles.map((r: { organization: string }) => r.organization)).toEqual(["Телеконтакт"]);
});
});

1
tsconfig.build.json Normal file
View File

@ -0,0 +1 @@
{ "extends": "./tsconfig.json", "compilerOptions": { "rootDir": "src" }, "include": ["src"] }

7
tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"compilerOptions": {
"target": "ES2023", "module": "NodeNext", "moduleResolution": "NodeNext",
"strict": true, "esModuleInterop": true, "skipLibCheck": true, "outDir": "dist", "rootDir": "."
},
"include": ["src", "tests"]
}