dsh-department 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Обсуждение задачи: структурированный документ до ТЗ.
3
+ */
4
+ import { mkdir, writeFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { appendEvent, taskDir, writeState } from './store.js';
7
+
8
+ const list = (value) => (Array.isArray(value) ? value : []).filter((item) => String(item ?? '').trim() !== '');
9
+
10
+ /**
11
+ * Пишет discussion.md и фиксирует событие.
12
+ *
13
+ * @param {string} root Корень.
14
+ * @param {string} taskId Задача.
15
+ * @param {object} state Состояние.
16
+ * @param {object} input goals, nonGoals, users, constraints, risks, questions, decisions.
17
+ * @returns {Promise<{ path: string }>}
18
+ */
19
+ export async function writeDiscussion(root, taskId, state, input = {}) {
20
+ const groups = [
21
+ ['Цели', list(input.goals)],
22
+ ['Не цели', list(input.nonGoals)],
23
+ ['Пользователи', list(input.users)],
24
+ ['Ограничения', list(input.constraints)],
25
+ ['Риски', list(input.risks)],
26
+ ['Открытые вопросы', list(input.questions)],
27
+ ['Решения', list(input.decisions)],
28
+ ];
29
+ const lines = ['# Обсуждение задачи', ''];
30
+ for (const [title, items] of groups) {
31
+ lines.push(`## ${title}`, '');
32
+ if (items.length === 0) lines.push('- _нет_');
33
+ for (const item of items) lines.push(`- ${item}`);
34
+ lines.push('');
35
+ }
36
+ lines.push('> Пока есть открытые вопросы, ТЗ нельзя утверждать.', '');
37
+ const dir = taskDir(root, taskId);
38
+ await mkdir(dir, { recursive: true });
39
+ const path = join(dir, 'discussion.md');
40
+ await writeFile(path, lines.join('\n'), 'utf8');
41
+ const next = appendEvent(state, {
42
+ actor: 'analyst',
43
+ action: 'discussion_updated',
44
+ detail: `цели=${list(input.goals).length} вопросы=${list(input.questions).length}`,
45
+ });
46
+ await writeState(root, next);
47
+ return { path };
48
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Подготовка к продакшену: пакет документации для передачи.
3
+ */
4
+ import { access, copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { appendEvent, readState, taskDir, writeState } from './store.js';
7
+ import { runGit } from './git.js';
8
+
9
+ async function exists(path) {
10
+ try { await access(path); return true; } catch { return false; }
11
+ }
12
+
13
+ /**
14
+ * Собирает delivery/: RUN.md, MANUAL-QA.md, CHANGELOG.md, RELEASE.md и копии главных документов.
15
+ *
16
+ * @param {string} root Корень проекта.
17
+ * @param {string} taskId Задача.
18
+ * @param {object} [options] version, run, port, notes.
19
+ * @returns {Promise<{ dir: string, files: string[], version: string }>}
20
+ */
21
+ export async function buildHandover(root, taskId, options = {}) {
22
+ const state = await readState(root, taskId);
23
+ if (!state) throw new Error(`task not found: ${taskId}`);
24
+ const dir = join(taskDir(root, taskId), 'delivery');
25
+ await mkdir(dir, { recursive: true });
26
+ await mkdir(join(dir, 'docs'), { recursive: true });
27
+
28
+ const branch = await runGit(root, ['rev-parse', '--abbrev-ref', 'HEAD']);
29
+ const commit = await runGit(root, ['rev-parse', '--short', 'HEAD']);
30
+ const version = String(options.version ?? '1.0.0');
31
+ const run = String(options.run ?? 'укажите команду запуска');
32
+ const port = String(options.port ?? '');
33
+ const notes = String(options.notes ?? '');
34
+ const branchName = branch.code === 0 ? branch.stdout.trim() : state.branch;
35
+ const commitHash = commit.code === 0 ? commit.stdout.trim() : '—';
36
+
37
+ const runDoc = [
38
+ `# Запуск: ${state.title ?? taskId}`,
39
+ '',
40
+ `- Версия: **${version}**`,
41
+ `- Ветка: \`${branchName}\``,
42
+ `- Коммит: \`${commitHash}\``,
43
+ '',
44
+ '## Требования',
45
+ '',
46
+ '- окружение и зависимости продукта (см. README продукта);',
47
+ '- свободные порты и доступ к локальной сети, если нужно.',
48
+ '',
49
+ '## Запуск',
50
+ '',
51
+ '```bash',
52
+ run,
53
+ '```',
54
+ '',
55
+ port ? `Открыть: \`${port}\`` : '',
56
+ notes ? `\n## Заметки\n\n${notes}` : '',
57
+ '',
58
+ '## Проверка после запуска',
59
+ '',
60
+ '1. Продукт открывается/стартует без ошибок.',
61
+ '2. Основной сценарий работает.',
62
+ '3. Данные сохраняются и восстанавливаются.',
63
+ '4. Ошибки не ломают интерфейс.',
64
+ '',
65
+ '## Известные ограничения',
66
+ '',
67
+ 'См. README продукта и `docs/releases/`.',
68
+ ].filter((line) => line !== '').join('\n') + '\n';
69
+ await writeFile(join(dir, 'RUN.md'), runDoc, 'utf8');
70
+
71
+ const qa = [
72
+ `# Ручное тестирование: ${state.title ?? taskId} ${version}`,
73
+ '',
74
+ 'Отмечай: ✅ работает / ⚠️ странно / ❌ сломано. Для багов — шаги, ожидаемое, фактическое.',
75
+ '',
76
+ '## 1. Запуск',
77
+ '- [ ] Продукт запускается по инструкции RUN.md.',
78
+ '- [ ] Нет ошибок в консоли при старте.',
79
+ '',
80
+ '## 2. Основные сценарии',
81
+ '- [ ] Главный сценарий проходит от начала до конца.',
82
+ '- [ ] Второстепенные сценарии не ломаются.',
83
+ '',
84
+ '## 3. Данные',
85
+ '- [ ] Сохранение и загрузка работают.',
86
+ '- [ ] Некорректные данные обрабатываются без падения.',
87
+ '',
88
+ '## 4. Интерфейс',
89
+ '- [ ] Все элементы управления доступны.',
90
+ '- [ ] Тексты понятны, без обрезаний.',
91
+ '',
92
+ '## 5. Ограничения',
93
+ '- [ ] Известные ограничения подтверждены и не мешают работе.',
94
+ ].join('\n') + '\n';
95
+ await writeFile(join(dir, 'MANUAL-QA.md'), qa, 'utf8');
96
+
97
+ // CHANGELOG: копия корневого, иначе из событий задачи.
98
+ const rootChangelog = join(root, 'CHANGELOG.md');
99
+ if (await exists(rootChangelog)) {
100
+ await copyFile(rootChangelog, join(dir, 'CHANGELOG.md'));
101
+ } else {
102
+ const lines = ['# Changelog', '', `## ${version}`, ''];
103
+ for (const event of (state.events ?? []).slice(-20)) {
104
+ lines.push(`- ${event.action}${event.detail ? ': ' + String(event.detail).slice(0, 120) : ''}`);
105
+ }
106
+ await writeFile(join(dir, 'CHANGELOG.md'), lines.join('\n') + '\n', 'utf8');
107
+ }
108
+
109
+ const docs = ['spec.md', 'concept.md', 'plan.md'];
110
+ for (const name of docs) {
111
+ const source = join(taskDir(root, taskId), name);
112
+ if (await exists(source)) await copyFile(source, join(dir, 'docs', name));
113
+ }
114
+
115
+ const release = [
116
+ `# Передача в продакшен: ${state.title ?? taskId}`,
117
+ '',
118
+ `- Версия: **${version}**`,
119
+ `- Ветка: \`${branchName}\``,
120
+ `- Коммит: \`${commitHash}\``,
121
+ '',
122
+ '## Состав пакета',
123
+ '',
124
+ '- `RUN.md` — как запустить и проверить;',
125
+ '- `MANUAL-QA.md` — чек-лист ручного тестирования;',
126
+ '- `CHANGELOG.md` — что вошло в версию;',
127
+ '- `docs/spec.md`, `docs/concept.md`, `docs/plan.md` — главные документы проекта.',
128
+ '',
129
+ '## Статус',
130
+ '',
131
+ `Стадия: \`${state.stage}\`. Тесты: \`${state.gates?.tests?.status ?? 'pending'}\`.`,
132
+ ].join('\n') + '\n';
133
+ await writeFile(join(dir, 'RELEASE.md'), release, 'utf8');
134
+
135
+ const next = appendEvent(state, { actor: 'manager', action: 'handover_ready', detail: `version=${version} branch=${branchName} commit=${commitHash}` });
136
+ await writeState(root, next);
137
+ return { dir, files: ['RUN.md', 'MANUAL-QA.md', 'CHANGELOG.md', 'RELEASE.md'], version };
138
+ }
package/src/panel-api.js CHANGED
@@ -11,11 +11,12 @@ import { currentBranch, runGit } from './git.js';
11
11
  /** Стадии в порядке конвейера — для прогресса. */
12
12
  export const STAGE_ORDER = [
13
13
  'analysis',
14
- 'concept',
15
- 'concept_review',
16
14
  'spec',
17
15
  'spec_review',
16
+ 'concept',
17
+ 'concept_review',
18
18
  'executing',
19
+ 'release',
19
20
  'done',
20
21
  ];
21
22
 
@@ -134,6 +135,9 @@ export async function taskPayload(root, taskId) {
134
135
  files[name] = await fileExists(join(root, DEPARTMENT_DIR, taskId, name));
135
136
  }
136
137
  files['README.md'] = await fileExists(join(root, 'README.md'));
138
+ for (const name of ['RUN.md', 'MANUAL-QA.md', 'CHANGELOG.md']) {
139
+ files['delivery/' + name] = await fileExists(join(root, DEPARTMENT_DIR, taskId, 'delivery', name));
140
+ }
137
141
  const stageNo = String((state.stageIndex ?? 0) + 1).padStart(2, '0');
138
142
  for (const name of ['review.md', 'report.md']) {
139
143
  files['stage:' + name.replace('.md', '')] = await fileExists(join(root, DEPARTMENT_DIR, taskId, 'stages', stageNo, name));
package/src/routes.js CHANGED
@@ -2,10 +2,17 @@
2
2
  * HTTP-маршруты Web-панели отдела на общем канале `/api`.
3
3
  * Только чтение: доска и карточка задачи.
4
4
  */
5
- import { readFile } from 'node:fs/promises';
5
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { dirname, join } from 'node:path';
8
8
  import { listProjects, listTasks, resolveRoots, rootsWithTasks, taskPayload } from './panel-api.js';
9
+ import { createDepartmentTask } from './create-task.js';
10
+ import { encodePng } from './png.js';
11
+ import { assertApprovalReady } from './approval.js';
12
+ import { isGitProject, listDirectories } from './browse-dirs.js';
13
+ import { readSettings, writeSettings } from './settings.js';
14
+ import { randomUUID } from 'node:crypto';
15
+ import { rename } from 'node:fs/promises';
9
16
  import { addCorrection, amendDocument, answerQuestion, approveDocument, listRoles, readState, reviewMemo, setBudget, setPaused, setRole, writeState } from './store.js';
10
17
  import { isHumanApprover } from './roles.js';
11
18
  import { buildBlueprint } from './blueprint.js';
@@ -13,6 +20,37 @@ import { listDocuments, readDocument } from './documents.js';
13
20
 
14
21
  const assetsDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'assets');
15
22
 
23
+
24
+ /**
25
+ * Будит руководителя в проекте или создаёт для него чат.
26
+ *
27
+ * @param {object} ctx Контекст плагина.
28
+ * @param {string} root Корень.
29
+ * @param {string} taskId Задача.
30
+ * @param {string} title Название.
31
+ * @returns {Promise<string|null>} id сессии.
32
+ */
33
+ async function startManager(ctx, root, taskId, title) {
34
+ const kickoff = `Ты — руководитель ИИ-отдела. Задача ${taskId} («${title}») в ${root}.
35
+ Прочитай docs/department/${taskId}/task.md и начни с ОБСУЖДЕНИЯ:
36
+ задай 4–6 вопросов через dept_ask, запиши dept_discussion, затем подготовь ТЗ и концепцию
37
+ (2–3 варианта). Не утверждай документы и не пиши код — утверждает человек в панели.`;
38
+ try {
39
+ const registry = ctx.get('agents');
40
+ const existing = registry.list().find((agent) => agent?.session?.header?.cwd === root && typeof agent.followup === 'function');
41
+ if (existing) {
42
+ existing.followup({ role: 'user', content: [{ type: 'text', text: kickoff }], source: { kind: 'dsh-department' } });
43
+ return existing.id ?? null;
44
+ }
45
+ const sessionId = `session-${randomUUID()}`;
46
+ const handle = await registry.create({ sessionId, meta: { cwd: root, agentPreset: 'standard' } });
47
+ handle.agent.followup({ role: 'user', content: [{ type: 'text', text: kickoff }], source: { kind: 'dsh-department' } });
48
+ return sessionId;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
16
54
  /** Точные маршруты панели. */
17
55
  export const DEPARTMENT_ROUTES = {
18
56
  tasks: '/api/department/tasks',
@@ -26,6 +64,14 @@ export const DEPARTMENT_ROUTES = {
26
64
  review: '/api/department/review',
27
65
  correction: '/api/department/correction',
28
66
  pause: '/api/department/pause',
67
+ settings: '/api/department/settings',
68
+ createTask: '/api/department/task/create',
69
+ editor: '/api/department/editor',
70
+ editorSave: '/api/department/editor/save',
71
+ editorHandoff: '/api/department/editor/handoff',
72
+ browseDirs: '/api/department/browse-dirs',
73
+ taskDelete: '/api/department/task/delete',
74
+ taskStart: '/api/department/task/start',
29
75
  documents: '/api/department/documents',
30
76
  document: '/api/department/document',
31
77
  answer: '/api/department/answer',
@@ -116,6 +162,169 @@ export function registerDepartmentRoutes(ctx, activity) {
116
162
  },
117
163
  });
118
164
 
165
+ add({
166
+ path: DEPARTMENT_ROUTES.settings,
167
+ methods: ['GET', 'POST'],
168
+ requestBody: 'buffered',
169
+ fetch: async (request) => {
170
+ if (request.method === 'GET') return Response.json(await readSettings());
171
+ const body = await request.json().catch(() => ({}));
172
+ const { enabled, by } = body ?? {};
173
+ if (typeof enabled !== 'boolean' || !isHumanApprover(by)) {
174
+ return Response.json({ error: 'enabled boolean and human signature required' }, { status: 400 });
175
+ }
176
+ const next = await writeSettings({ enabled });
177
+ return Response.json(next);
178
+ },
179
+ });
180
+
181
+ add({
182
+ path: DEPARTMENT_ROUTES.createTask,
183
+ methods: ['POST'],
184
+ requestBody: 'buffered',
185
+ fetch: async (request) => {
186
+ const body = await request.json().catch(() => ({}));
187
+ const { root, taskId, title, brief, testCommand, branch, by } = body ?? {};
188
+ if (!root || !taskId) return Response.json({ error: 'root, taskId required' }, { status: 400 });
189
+ if (!isHumanApprover(by)) return Response.json({ error: 'task must be created by the human' }, { status: 403 });
190
+ try {
191
+ const state = await createDepartmentTask(root, taskId, { title, brief, testCommand, branch });
192
+ const sessionId = await startManager(ctx, root, taskId, title || taskId);
193
+ return Response.json({ ok: true, taskId: state.taskId, stage: state.stage, sessionId });
194
+ } catch (error) {
195
+ return Response.json({ error: error.message }, { status: 400 });
196
+ }
197
+ },
198
+ });
199
+
200
+
201
+ add({
202
+ path: DEPARTMENT_ROUTES.editor,
203
+ methods: ['GET'],
204
+ requestBody: 'buffered',
205
+ fetch: async () => {
206
+ const html = await readFile(join(dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'editor.html'), 'utf8');
207
+ return new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' } });
208
+ },
209
+ });
210
+
211
+ add({
212
+ path: DEPARTMENT_ROUTES.editorSave,
213
+ methods: ['POST'],
214
+ requestBody: 'buffered',
215
+ fetch: async (request) => {
216
+ const body = await request.json().catch(() => ({}));
217
+ const { root, taskId, name, rows, palette } = body ?? {};
218
+ if (!root || !taskId || !Array.isArray(rows) || !palette) return Response.json({ error: 'root, taskId, rows, palette required' }, { status: 400 });
219
+ const safe = String(name ?? 'sprite').replace(/[^a-z0-9._-]/gi, '_').slice(0, 60) || 'sprite';
220
+ const state = await readState(root, taskId);
221
+ if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
222
+ const height = rows.length;
223
+ const width = rows[0]?.length ?? 0;
224
+ const rgba = new Uint8Array(width * height * 4);
225
+ for (let y = 0; y < height; y += 1) {
226
+ for (let x = 0; x < width; x += 1) {
227
+ const symbol = rows[y][x];
228
+ if (!symbol || symbol === '.') continue;
229
+ const hex = palette[symbol];
230
+ if (!hex) continue;
231
+ const value = parseInt(String(hex).replace('#', ''), 16);
232
+ const i = (y * width + x) * 4;
233
+ rgba[i] = (value >> 16) & 255;
234
+ rgba[i + 1] = (value >> 8) & 255;
235
+ rgba[i + 2] = value & 255;
236
+ rgba[i + 3] = 255;
237
+ }
238
+ }
239
+ const dir = join(root, 'assets', 'office', 'editor');
240
+ await mkdir(dir, { recursive: true });
241
+ const png = join(dir, `${safe}.png`);
242
+ await writeFile(png, encodePng(width, height, rgba));
243
+ await writeFile(join(dir, `${safe}.json`), JSON.stringify({ rows, palette }, null, 2) + '\n', 'utf8');
244
+ return Response.json({ ok: true, path: `assets/office/editor/${safe}.png`, width, height });
245
+ },
246
+ });
247
+
248
+ add({
249
+ path: DEPARTMENT_ROUTES.editorHandoff,
250
+ methods: ['POST'],
251
+ requestBody: 'buffered',
252
+ fetch: async (request) => {
253
+ const body = await request.json().catch(() => ({}));
254
+ const { root, taskId, name, note, by } = body ?? {};
255
+ if (!root || !taskId || !isHumanApprover(by)) return Response.json({ error: 'root, taskId, human signature required' }, { status: 400 });
256
+ const state = await readState(root, taskId);
257
+ if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
258
+ const result = addCorrection(state, {
259
+ doc: 'interface',
260
+ subject: `Спрайт: ${name || 'sprite'}`,
261
+ text: note || 'Дорисовать спрайт в assets/office/editor/' + (name || 'sprite') + '.png',
262
+ by: String(by),
263
+ });
264
+ await writeState(root, result.state);
265
+ return Response.json({ ok: true, correctionId: result.correction.id });
266
+ },
267
+ });
268
+
269
+
270
+
271
+
272
+ add({
273
+ path: DEPARTMENT_ROUTES.taskStart,
274
+ methods: ['POST'],
275
+ requestBody: 'buffered',
276
+ fetch: async (request) => {
277
+ const body = await request.json().catch(() => ({}));
278
+ const { root, taskId, by } = body ?? {};
279
+ if (!root || !taskId || !isHumanApprover(by)) return Response.json({ error: 'root, taskId, human signature required' }, { status: 400 });
280
+ const state = await readState(root, taskId);
281
+ if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
282
+ const sessionId = await startManager(ctx, root, taskId, state.title ?? taskId);
283
+ return Response.json({ ok: true, sessionId });
284
+ },
285
+ });
286
+
287
+ add({
288
+ path: DEPARTMENT_ROUTES.taskDelete,
289
+ methods: ['DELETE'],
290
+ requestBody: 'buffered',
291
+ fetch: async (request) => {
292
+ const url = new URL(request.url);
293
+ const root = url.searchParams.get('root');
294
+ const taskId = url.searchParams.get('taskId');
295
+ const by = url.searchParams.get('by');
296
+ if (!root || !taskId || !isHumanApprover(by)) return Response.json({ error: 'root, taskId, human signature required' }, { status: 400 });
297
+ const state = await readState(root, taskId);
298
+ if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
299
+ const dir = join(root, 'docs', 'department', taskId);
300
+ const trash = join(root, 'docs', 'department', '.trash');
301
+ await mkdir(trash, { recursive: true });
302
+ const target = join(trash, `${taskId}-${Date.now()}`);
303
+ await rename(dir, target);
304
+ return Response.json({ ok: true, movedTo: target });
305
+ },
306
+ });
307
+
308
+ add({
309
+ path: DEPARTMENT_ROUTES.browseDirs,
310
+ methods: ['GET'],
311
+ requestBody: 'buffered',
312
+ fetch: async (request) => {
313
+ const url = new URL(request.url);
314
+ try {
315
+ const listing = await listDirectories(url.searchParams.get('path'));
316
+ const projects = [];
317
+ for (const name of listing.dirs) {
318
+ const full = join(listing.path, name);
319
+ if (await isGitProject(full)) projects.push(name);
320
+ }
321
+ return Response.json({ ...listing, projects });
322
+ } catch (error) {
323
+ return Response.json({ error: error.message }, { status: 400 });
324
+ }
325
+ },
326
+ });
327
+
119
328
  add({
120
329
  path: DEPARTMENT_ROUTES.pause,
121
330
  methods: ['POST'],
@@ -256,6 +465,7 @@ export function registerDepartmentRoutes(ctx, activity) {
256
465
  const state = await readState(root, taskId);
257
466
  if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
258
467
  try {
468
+ await assertApprovalReady(root, taskId, doc, state);
259
469
  const next = await writeState(root, approveDocument(state, { doc, by }));
260
470
  return Response.json({ stage: next.stage, summary: next.approvals });
261
471
  } catch (error) {
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Глобальные настройки отдела: включён ли отдел как процесс.
3
+ *
4
+ * Файл лежит вне проектов, чтобы одна кнопка управляла всеми задачами.
5
+ */
6
+ import { readFile, writeFile, mkdir } from 'node:fs/promises';
7
+ import { homedir } from 'node:os';
8
+ import { join } from 'node:path';
9
+
10
+ const SETTINGS_FILE = join(homedir(), '.dsh', 'department-settings.json');
11
+
12
+ /**
13
+ * Читает настройки (по умолчанию отдел включён).
14
+ *
15
+ * @returns {Promise<{ enabled: boolean }>}
16
+ */
17
+ export async function readSettings() {
18
+ try {
19
+ const data = JSON.parse(await readFile(SETTINGS_FILE, 'utf8'));
20
+ return { enabled: data.enabled !== false };
21
+ } catch {
22
+ return { enabled: true };
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Сохраняет настройки.
28
+ *
29
+ * @param {{ enabled?: boolean }} patch Изменения.
30
+ * @returns {Promise<{ enabled: boolean }>}
31
+ */
32
+ export async function writeSettings(patch) {
33
+ const current = await readSettings();
34
+ const next = { ...current, ...(patch ?? {}) };
35
+ next.enabled = next.enabled !== false;
36
+ await mkdir(join(homedir(), '.dsh'), { recursive: true });
37
+ await writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2) + '\n', 'utf8');
38
+ return next;
39
+ }
40
+
41
+ /**
42
+ * Бросает ошибку, если отдел выключен.
43
+ *
44
+ * @param {string} action Что пытались сделать.
45
+ */
46
+ export async function assertDepartmentEnabled(action = 'работа отдела') {
47
+ const settings = await readSettings();
48
+ if (!settings.enabled) throw new Error(`отдел выключен человеком: ${action} недоступно (включи в панели «Отдел») `);
49
+ }
package/src/store.js CHANGED
@@ -13,19 +13,20 @@ export const DEPARTMENT_DIR = 'docs/department';
13
13
  /** Допустимые стадии задачи. */
14
14
  export const STAGES = Object.freeze([
15
15
  'analysis',
16
- 'concept',
17
- 'concept_review',
18
16
  'spec',
19
17
  'spec_review',
18
+ 'concept',
19
+ 'concept_review',
20
20
  'executing',
21
+ 'release',
21
22
  'done',
22
23
  'blocked',
23
24
  ]);
24
25
 
25
- /** Документы, которые человек утверждает. */
26
- const APPROVAL_TRANSITIONS = Object.freeze({
27
- concept: { from: ['concept_review'], to: 'spec' },
28
- spec: { from: ['spec_review'], to: 'executing' },
26
+ /** Документы, которые человек утверждает, и стадии, где это разрешено. */
27
+ const APPROVAL_STAGE = Object.freeze({
28
+ spec: 'spec_review',
29
+ concept: 'concept_review',
29
30
  });
30
31
 
31
32
  /**
@@ -196,25 +197,26 @@ export function appendEvent(state, event) {
196
197
  * @returns {object} Новое состояние.
197
198
  */
198
199
  export function approveDocument(state, input) {
199
- const transition = APPROVAL_TRANSITIONS[input.doc];
200
- if (!transition) throw new Error(`unknown document: ${input.doc}`);
201
- if (!transition.from.includes(state.stage)) {
202
- throw new Error(`cannot approve ${input.doc} in stage ${state.stage}`);
200
+ const stage = APPROVAL_STAGE[input.doc];
201
+ if (!stage) throw new Error(`unknown document: ${input.doc}`);
202
+ if (state.stage !== stage) {
203
+ throw new Error(`cannot approve ${input.doc} in stage ${state.stage}; move to ${stage} first`);
203
204
  }
204
205
  const now = new Date().toISOString();
205
- const approved = {
206
- ...state,
207
- stage: transition.to,
208
- updatedAt: now,
209
- approvals: [
210
- ...state.approvals,
211
- { doc: input.doc, by: input.by, via: input.via ?? 'chat', ts: now },
212
- ],
213
- };
206
+ const approvals = [
207
+ ...(state.approvals ?? []),
208
+ { doc: input.doc, by: input.by, via: input.via ?? 'chat', ts: now },
209
+ ];
210
+ const approvedDocs = new Set(approvals.map((item) => item.doc));
211
+ // Оба документа утверждены → проект запускается. Иначе — переходим к другому документу.
212
+ const nextStage = approvedDocs.has('spec') && approvedDocs.has('concept')
213
+ ? 'executing'
214
+ : input.doc === 'spec' ? 'concept' : 'spec';
215
+ const approved = { ...state, stage: nextStage, updatedAt: now, approvals };
214
216
  return appendEvent(approved, {
215
217
  actor: input.by,
216
218
  action: `approved_${input.doc}`,
217
- detail: `stage=${transition.to}`,
219
+ detail: `stage=${nextStage}`,
218
220
  });
219
221
  }
220
222
 
@@ -340,19 +342,20 @@ export function summarize(state) {
340
342
 
341
343
  /** Разрешённые переходы стадий без утверждения человеком. */
342
344
  const STAGE_FLOW = Object.freeze({
343
- analysis: ['concept'],
344
- concept: ['concept_review', 'analysis'],
345
- concept_review: ['concept', 'spec'],
345
+ analysis: ['concept', 'spec'],
346
+ concept: ['concept_review', 'spec'],
347
+ concept_review: ['concept'],
346
348
  spec: ['spec_review', 'concept'],
347
- spec_review: ['spec', 'executing'],
348
- executing: ['done', 'blocked', 'spec'],
349
+ spec_review: ['spec'],
350
+ executing: ['release', 'blocked', 'spec', 'concept'],
351
+ release: ['done', 'executing'],
349
352
  done: [],
350
353
  blocked: ['analysis', 'executing'],
351
354
  });
352
355
 
353
356
  /**
354
357
  * Переводит задачу на следующую стадию с проверкой допустимости перехода.
355
- * Утверждения (concept→spec, spec→executing) выполняются только через
358
+ * Запуск проекта (executing) — только после утверждения и ТЗ, и концепции, через
356
359
  * `approveDocument`, чтобы нельзя было проскочить человеческий гейт.
357
360
  *
358
361
  * @param {object} state Состояние.
@@ -365,7 +368,7 @@ export function advanceStage(state, target, reason = '') {
365
368
  if (!allowed.includes(target)) {
366
369
  throw new Error(`cannot move ${state.stage} -> ${target}; allowed: ${allowed.join(', ') || 'none'}`);
367
370
  }
368
- if (target === 'spec' || target === 'executing') {
371
+ if (target === 'executing') {
369
372
  throw new Error(`${target} requires a human approval, use dept_approve`);
370
373
  }
371
374
  return appendEvent({ ...state, stage: target }, { actor: 'manager', action: `stage_${target}`, detail: reason });