dsh-department 0.2.0 → 0.2.2

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2
4
+ - Утверждение ТЗ/концепции автоматически будит руководителя промтом по стадии.
5
+ - «Запустить отдел» отправляет промт под текущую стадию (обсуждение, ТЗ, концепция, план, релиз).
6
+
7
+
8
+ ## 0.2.1
9
+ - Создание задачи: авто-инициализация git, автоподстановка ID/названия, авто-определение `npm test`.
10
+ - Выбор папки проекта: обзор каталогов, список известных корней.
11
+ - Создание задачи автоматически запускает чат руководителя с готовым промтом.
12
+ - Кнопка «Запустить отдел» для уже созданной задачи.
13
+ - Удаление задачи (перемещение в `docs/department/.trash`).
14
+
15
+
3
16
  ## 0.2.0
4
17
  - **Обсуждение задачи**: `discussion.md` (цели, не-цели, пользователи, ограничения, риски, вопросы, решения).
5
18
  - **Гейт утверждения**: ТЗ нельзя утвердить при открытых вопросах; концепция — без двух вариантов.
package/client.js CHANGED
@@ -124,6 +124,11 @@ window.__ModuleLoader__.load({
124
124
  'dept.brief': 'Бриф',
125
125
  'dept.test': 'Команда тестов',
126
126
  'dept.create': 'Создать',
127
+ 'dept.pick': 'Выбрать…',
128
+ 'dept.up': '↑ Наверх',
129
+ 'dept.chooseThis': 'Выбрать эту папку',
130
+ 'dept.git': 'git-проекты',
131
+ 'dept.dirError': 'Не удалось прочитать каталог',
127
132
  'dept.cancel': 'Отмена',
128
133
  'dept.offBanner': 'Отдел выключен — новые задачи не запускаются, инструменты заблокированы.',
129
134
  'activity.title': 'Сейчас работают',
@@ -392,6 +397,11 @@ window.__ModuleLoader__.load({
392
397
  'dept.brief': 'Brief',
393
398
  'dept.test': 'Test command',
394
399
  'dept.create': 'Create',
400
+ 'dept.pick': 'Choose…',
401
+ 'dept.up': '↑ Up',
402
+ 'dept.chooseThis': 'Choose this folder',
403
+ 'dept.git': 'git projects',
404
+ 'dept.dirError': 'Cannot read directory',
395
405
  'dept.cancel': 'Cancel',
396
406
  'dept.offBanner': 'Department is off — new tasks are not started, tools are blocked.',
397
407
  'activity.title': 'Working now',
@@ -638,6 +648,9 @@ window.__ModuleLoader__.load({
638
648
  settings: '/api/department/settings',
639
649
  createTask: '/api/department/task/create',
640
650
  editor: '/api/department/editor',
651
+ browseDirs: '/api/department/browse-dirs',
652
+ taskDelete: '/api/department/task/delete',
653
+ taskStart: '/api/department/task/start',
641
654
  projects: '/api/department/projects',
642
655
  review: '/api/department/review',
643
656
  }
@@ -1306,7 +1319,7 @@ window.__ModuleLoader__.load({
1306
1319
  : h('div', { className: 'dept-sub' }, t('doc.choose'))))
1307
1320
  }
1308
1321
 
1309
- function TaskDetail({ detail, onBack, onReload, onEditor }) {
1322
+ function TaskDetail({ detail, onBack, onReload, onEditor, onDeleted }) {
1310
1323
  const docs = ['task.md', 'analysis.md', 'concept.md', 'spec.md', 'plan.md', 'backlog.md']
1311
1324
  const [tab, setTab] = useState('overview')
1312
1325
  const [name, setName] = useState(() => localStorage.getItem('dept-approver') || 'vladimir')
@@ -1371,6 +1384,29 @@ window.__ModuleLoader__.load({
1371
1384
  }
1372
1385
  }
1373
1386
 
1387
+ async function startDepartment() {
1388
+ try {
1389
+ const response = await fetch(ROUTES.taskStart, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ root: detail.root, taskId: detail.taskId, by: name }) })
1390
+ const data = await response.json().catch(() => ({}))
1391
+ if (!response.ok) throw new Error(data.error || response.statusText)
1392
+ setMessage(data.sessionId ? 'Руководитель запущен в чате ' + data.sessionId : 'Промт отправлен в чат проекта')
1393
+ } catch (problem) {
1394
+ setMessage(problem.message)
1395
+ }
1396
+ }
1397
+
1398
+ async function deleteTask() {
1399
+ if (!window.confirm('Удалить задачу ' + detail.taskId + '? Папка будет перемещена в docs/department/.trash.')) return
1400
+ try {
1401
+ const response = await fetch(`${ROUTES.taskDelete}?root=${encodeURIComponent(detail.root)}&taskId=${encodeURIComponent(detail.taskId)}&by=${encodeURIComponent(name)}`, { method: 'DELETE' })
1402
+ const data = await response.json().catch(() => ({}))
1403
+ if (!response.ok) throw new Error(data.error || response.statusText)
1404
+ if (onDeleted) onDeleted()
1405
+ } catch (problem) {
1406
+ setMessage(problem.message)
1407
+ }
1408
+ }
1409
+
1374
1410
  async function post(path, body) {
1375
1411
  setBusy(true)
1376
1412
  setMessage(null)
@@ -1682,7 +1718,9 @@ window.__ModuleLoader__.load({
1682
1718
  : null),
1683
1719
  h('div', { className: 'dept-row' },
1684
1720
  h('input', { className: 'dept-input', value: name, onChange: (event) => setName(event.target.value), placeholder: t('form.name'), title: t('form.nameTitle') }),
1721
+ h('button', { className: 'dept-btn', onClick: startDepartment }, 'Запустить отдел'),
1685
1722
  h('button', { className: 'dept-btn', onClick: () => onEditor && onEditor() }, t('nav.editor')),
1723
+ h('button', { className: 'dept-btn fail', disabled: busy, onClick: deleteTask }, 'Удалить'),
1686
1724
  h('button', {
1687
1725
  className: 'dept-btn',
1688
1726
  disabled: busy,
@@ -2144,6 +2182,7 @@ window.__ModuleLoader__.load({
2144
2182
  const [form, setForm] = useState({ root: '', taskId: '', title: '', brief: '', testCommand: '' })
2145
2183
  const [creating, setCreating] = useState(false)
2146
2184
  const [createError, setCreateError] = useState(null)
2185
+ const [browse, setBrowse] = useState(null)
2147
2186
  const [langTick, setLangTick] = useState(0)
2148
2187
  const [textSize, setTextSize] = useState(() => {
2149
2188
  const saved = Number(localStorage.getItem('dept-text-size'))
@@ -2177,6 +2216,15 @@ window.__ModuleLoader__.load({
2177
2216
  return data
2178
2217
  }
2179
2218
 
2219
+ async function openBrowse(target) {
2220
+ try {
2221
+ const payload = await api(`${ROUTES.browseDirs}?path=${encodeURIComponent(target || form.root || '')}`)
2222
+ setBrowse(payload)
2223
+ } catch (problem) {
2224
+ setBrowse({ error: problem.message })
2225
+ }
2226
+ }
2227
+
2180
2228
  async function toggleDepartment() {
2181
2229
  try {
2182
2230
  const next = await postJson(ROUTES.settings, { enabled: !settings.enabled, by: name })
@@ -2186,14 +2234,28 @@ window.__ModuleLoader__.load({
2186
2234
  }
2187
2235
  }
2188
2236
 
2237
+ function applyRoot(path) {
2238
+ const base = String(path).split('/').filter(Boolean).pop() ?? 'project'
2239
+ const id = base.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 30) + '-01'
2240
+ setForm((current) => ({
2241
+ ...current,
2242
+ root: path,
2243
+ taskId: current.taskId || id,
2244
+ title: current.title || base,
2245
+ }))
2246
+ }
2247
+
2189
2248
  async function createTask() {
2190
2249
  setCreating(true)
2191
2250
  setCreateError(null)
2192
2251
  try {
2193
2252
  await postJson(ROUTES.createTask, { ...form, by: name })
2253
+ const created = { root: form.root, taskId: form.taskId, title: form.title }
2194
2254
  setShowCreate(false)
2195
2255
  setForm({ root: '', taskId: '', title: '', brief: '', testCommand: '' })
2256
+ setBrowse(null)
2196
2257
  await loadTasks()
2258
+ await openTask(created)
2197
2259
  } catch (problem) {
2198
2260
  setCreateError(problem.message)
2199
2261
  } finally {
@@ -2221,7 +2283,7 @@ window.__ModuleLoader__.load({
2221
2283
 
2222
2284
  if (selected) {
2223
2285
  return detail
2224
- ? h(TaskDetail, { detail, onEditor: () => { setEditorKey(detail.root + ':' + detail.taskId); setView('editor'); setSelected(null); setDetail(null) }, onBack: () => { setSelected(null); setDetail(null) }, onReload: () => { if (selected) openTask(selected) } })
2286
+ ? h(TaskDetail, { detail, onDeleted: () => { setSelected(null); setDetail(null); loadTasks() }, onEditor: () => { setEditorKey(detail.root + ':' + detail.taskId); setView('editor'); setSelected(null); setDetail(null) }, onBack: () => { setSelected(null); setDetail(null) }, onReload: () => { if (selected) openTask(selected) } })
2225
2287
  : h('div', { className: 'dept-root' }, h('div', { className: 'dept-empty' }, t('loading.task')))
2226
2288
  }
2227
2289
 
@@ -2351,13 +2413,33 @@ window.__ModuleLoader__.load({
2351
2413
  h('div', { className: 'dept-modal-card' },
2352
2414
  h('div', { className: 'dept-title' }, t('dept.createTitle')),
2353
2415
  h('div', { className: 'dept-form-row' }, h('label', null, t('dept.root')),
2354
- h('input', { className: 'dept-input', value: form.root, placeholder: '/home/agent/work/projects/my-app', onChange: (event) => setForm({ ...form, root: event.target.value }) })),
2416
+ h('div', { className: 'dept-row', style: { flexWrap: 'nowrap' } },
2417
+ h('input', { className: 'dept-input', list: 'dept-roots', value: form.root, placeholder: '/home/agent/work/projects/my-app', onChange: (event) => setForm({ ...form, root: event.target.value }), style: { flex: 1 } }),
2418
+ h('button', { className: 'dept-btn', type: 'button', onClick: () => openBrowse(form.root) }, t('dept.pick'))),
2419
+ h('datalist', { id: 'dept-roots' }, ...[...new Set(tasks.map((task) => task.root))].map((root) => h('option', { key: root, value: root })))),
2420
+ browse
2421
+ ? h('div', { className: 'dept-block', style: { maxHeight: '220px', overflow: 'auto', gap: '6px' } },
2422
+ browse.error
2423
+ ? h('div', { className: 'dept-badge fail' }, t('dept.dirError') + ': ' + browse.error)
2424
+ : h('div', null,
2425
+ h('div', { className: 'dept-sub' }, browse.path),
2426
+ h('div', { className: 'dept-row' },
2427
+ browse.parent ? h('button', { className: 'dept-btn', type: 'button', onClick: () => openBrowse(browse.parent) }, t('dept.up')) : null,
2428
+ h('button', { className: 'dept-btn', type: 'button', onClick: () => { applyRoot(browse.path); setBrowse(null) } }, t('dept.chooseThis'))),
2429
+ ...browse.dirs.map((dir) => h('button', {
2430
+ key: dir,
2431
+ className: 'dept-btn',
2432
+ type: 'button',
2433
+ style: { textAlign: 'left' },
2434
+ onClick: () => openBrowse(browse.path + '/' + dir),
2435
+ }, dir + (browse.projects?.includes(dir) ? ' · ' + t('dept.git') : '')))))
2436
+ : null,
2355
2437
  h('div', { className: 'dept-form-row' }, h('label', null, t('dept.taskId')),
2356
2438
  h('input', { className: 'dept-input', value: form.taskId, placeholder: 'feature-01', onChange: (event) => setForm({ ...form, taskId: event.target.value }) })),
2357
2439
  h('div', { className: 'dept-form-row' }, h('label', null, t('dept.title')),
2358
2440
  h('input', { className: 'dept-input', value: form.title, onChange: (event) => setForm({ ...form, title: event.target.value }) })),
2359
2441
  h('div', { className: 'dept-form-row' }, h('label', null, t('dept.test')),
2360
- h('input', { className: 'dept-input', value: form.testCommand, placeholder: 'npm test', onChange: (event) => setForm({ ...form, testCommand: event.target.value }) })),
2442
+ h('input', { className: 'dept-input', value: form.testCommand, placeholder: 'авто: npm test, если есть package.json', onChange: (event) => setForm({ ...form, testCommand: event.target.value }) })),
2361
2443
  h('div', { className: 'dept-form-row' }, h('label', null, t('dept.brief')),
2362
2444
  h('textarea', { className: 'dept-input', rows: 5, value: form.brief, onChange: (event) => setForm({ ...form, brief: event.target.value }) })),
2363
2445
  createError ? h('div', { className: 'dept-badge fail' }, createError) : null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-department",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "AI development department for DeepSeek Harness: tasks, stages, gates, git workflow, budgets, roles and a pixel office.",
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Просмотр каталогов для выбора корня проекта.
3
+ */
4
+ import { readdir, stat } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, join, resolve } from 'node:path';
7
+
8
+ /**
9
+ * Список подкаталогов.
10
+ *
11
+ * @param {string} [target] Каталог (по умолчанию домашний).
12
+ * @returns {Promise<{ path: string, parent: string|null, dirs: string[] }>}
13
+ */
14
+ export async function listDirectories(target) {
15
+ const path = resolve(String(target ?? '').trim() || homedir());
16
+ const info = await stat(path);
17
+ if (!info.isDirectory()) throw new Error('not a directory');
18
+ const entries = await readdir(path, { withFileTypes: true });
19
+ const dirs = entries
20
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
21
+ .map((entry) => entry.name)
22
+ .sort((a, b) => a.localeCompare(b));
23
+ const parent = dirname(path);
24
+ return { path, parent: parent === path ? null : parent, dirs };
25
+ }
26
+
27
+ /**
28
+ * Есть ли git-репозиторий в каталоге.
29
+ *
30
+ * @param {string} path Каталог.
31
+ * @returns {Promise<boolean>}
32
+ */
33
+ export async function isGitProject(path) {
34
+ try {
35
+ const info = await stat(join(path, '.git'));
36
+ return info.isDirectory() || info.isFile();
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
@@ -4,7 +4,7 @@
4
4
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
5
  import { join } from 'node:path';
6
6
  import { appendEvent, createState, readState, taskDir, writeState } from './store.js';
7
- import { ensureBranch, isRepo } from './git.js';
7
+ import { ensureBranch, isRepo, runGit } from './git.js';
8
8
 
9
9
  /**
10
10
  * Создаёт задачу: состояние, ветка, task.md.
@@ -15,11 +15,29 @@ import { ensureBranch, isRepo } from './git.js';
15
15
  * @returns {Promise<object>} Состояние.
16
16
  */
17
17
  export async function createDepartmentTask(root, taskId, options = {}) {
18
- if (!(await isRepo(root))) throw new Error(`not a git repository: ${root}`);
18
+ if (!(await isRepo(root))) {
19
+ // Удобство: пустая папка автоматически становится git-репозиторием.
20
+ const init = await runGit(root, ['init', '-q']);
21
+ if (init.code !== 0) throw new Error(`cannot init git repository: ${init.stderr ?? ''}`);
22
+ await runGit(root, ['config', 'user.name', 'Department Bot']);
23
+ await runGit(root, ['config', 'user.email', 'dept@pilot.local']);
24
+ await runGit(root, ['add', '-A']);
25
+ const commit = await runGit(root, ['commit', '--allow-empty', '-qm', 'init: project created by department']);
26
+ if (commit.code !== 0) throw new Error(`cannot create initial commit: ${commit.stderr ?? ''}`);
27
+ }
19
28
  const existing = await readState(root, taskId);
20
29
  if (existing) throw new Error(`task already exists: ${taskId}`);
21
30
 
22
31
  let brief = typeof options.brief === 'string' ? options.brief.trim() : '';
32
+ let testCommand = options.testCommand ?? null;
33
+ if (!testCommand) {
34
+ try {
35
+ const pkg = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'));
36
+ if (pkg?.scripts?.test) testCommand = 'npm test';
37
+ } catch {
38
+ // package.json может отсутствовать
39
+ }
40
+ }
23
41
  if (options.release === true) {
24
42
  const template = await readFile(new URL('../templates/release.md', import.meta.url), 'utf8');
25
43
  brief = (brief ? brief + '\n\n' : '') + 'Подготовка к релизу (шаблон):\n\n' + template;
@@ -31,7 +49,7 @@ export async function createDepartmentTask(root, taskId, options = {}) {
31
49
  title: options.title,
32
50
  branch: options.branch,
33
51
  origin: options.origin ?? null,
34
- testCommand: options.testCommand ?? null,
52
+ testCommand,
35
53
  maxAttempts: options.maxAttempts,
36
54
  budgetTokens: options.budgetTokens,
37
55
  });
package/src/routes.js CHANGED
@@ -9,7 +9,10 @@ import { listProjects, listTasks, resolveRoots, rootsWithTasks, taskPayload } fr
9
9
  import { createDepartmentTask } from './create-task.js';
10
10
  import { encodePng } from './png.js';
11
11
  import { assertApprovalReady } from './approval.js';
12
+ import { isGitProject, listDirectories } from './browse-dirs.js';
12
13
  import { readSettings, writeSettings } from './settings.js';
14
+ import { randomUUID } from 'node:crypto';
15
+ import { rename } from 'node:fs/promises';
13
16
  import { addCorrection, amendDocument, answerQuestion, approveDocument, listRoles, readState, reviewMemo, setBudget, setPaused, setRole, writeState } from './store.js';
14
17
  import { isHumanApprover } from './roles.js';
15
18
  import { buildBlueprint } from './blueprint.js';
@@ -17,6 +20,68 @@ import { listDocuments, readDocument } from './documents.js';
17
20
 
18
21
  const assetsDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'assets');
19
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, text) {
34
+ const kickoff = text || `Ты — руководитель ИИ-отдела. Задача ${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
+
54
+
55
+ /**
56
+ * Промт руководителю по текущей стадии.
57
+ *
58
+ * @param {object} state Состояние.
59
+ * @param {string} root Корень.
60
+ * @param {string} taskId Задача.
61
+ * @returns {string}
62
+ */
63
+ function promptFor(state, root, taskId) {
64
+ const base = `Задача ${taskId} в ${root}. Стадия: ${state.stage}.`;
65
+ switch (state.stage) {
66
+ case 'analysis':
67
+ return `${base}\nПрочитай docs/department/${taskId}/task.md и начни с ОБСУЖДЕНИЯ: 4–6 вопросов через dept_ask, discussion.md, затем ТЗ и концепция. Не утверждай и не пиши код.`;
68
+ case 'spec':
69
+ return `${base}\nПодготовь ТЗ (spec.md): требования, НФТ, критерии приёмки, границы. Затем dept_stage spec_review и жди утверждения человеком.`;
70
+ case 'spec_review':
71
+ return `${base}\nТЗ готово к утверждению человеком. Дождись решения; после утверждения — концепция (2–3 варианта).`;
72
+ case 'concept':
73
+ return `${base}\nСделай концепцию (concept.md): 2–3 варианта, плюсы/минусы, выбор, архитектура. Затем dept_stage concept_review и жди утверждения.`;
74
+ case 'concept_review':
75
+ return `${base}\nКонцепция готова к утверждению человеком. Дождись решения.`;
76
+ case 'executing':
77
+ return `${base}\nСоставь план (plan.md), если его нет, затем веди этапы: реализация → тесты → ревью → dept_commit. Проверяй dept_health.`;
78
+ case 'release':
79
+ return `${base}\nСобери пакет передачи: dept_handover (RUN.md, MANUAL-QA.md, CHANGELOG.md), dept_verify, затем dept_stage done.`;
80
+ default:
81
+ return `${base}\nПродолжай по процессу отдела.`;
82
+ }
83
+ }
84
+
20
85
  /** Точные маршруты панели. */
21
86
  export const DEPARTMENT_ROUTES = {
22
87
  tasks: '/api/department/tasks',
@@ -35,6 +100,9 @@ export const DEPARTMENT_ROUTES = {
35
100
  editor: '/api/department/editor',
36
101
  editorSave: '/api/department/editor/save',
37
102
  editorHandoff: '/api/department/editor/handoff',
103
+ browseDirs: '/api/department/browse-dirs',
104
+ taskDelete: '/api/department/task/delete',
105
+ taskStart: '/api/department/task/start',
38
106
  documents: '/api/department/documents',
39
107
  document: '/api/department/document',
40
108
  answer: '/api/department/answer',
@@ -152,7 +220,8 @@ export function registerDepartmentRoutes(ctx, activity) {
152
220
  if (!isHumanApprover(by)) return Response.json({ error: 'task must be created by the human' }, { status: 403 });
153
221
  try {
154
222
  const state = await createDepartmentTask(root, taskId, { title, brief, testCommand, branch });
155
- return Response.json({ ok: true, taskId: state.taskId, stage: state.stage });
223
+ const sessionId = await startManager(ctx, root, taskId, title || taskId, promptFor(state, root, taskId));
224
+ return Response.json({ ok: true, taskId: state.taskId, stage: state.stage, sessionId });
156
225
  } catch (error) {
157
226
  return Response.json({ error: error.message }, { status: 400 });
158
227
  }
@@ -228,6 +297,65 @@ export function registerDepartmentRoutes(ctx, activity) {
228
297
  },
229
298
  });
230
299
 
300
+
301
+
302
+
303
+ add({
304
+ path: DEPARTMENT_ROUTES.taskStart,
305
+ methods: ['POST'],
306
+ requestBody: 'buffered',
307
+ fetch: async (request) => {
308
+ const body = await request.json().catch(() => ({}));
309
+ const { root, taskId, by } = body ?? {};
310
+ if (!root || !taskId || !isHumanApprover(by)) return Response.json({ error: 'root, taskId, human signature required' }, { status: 400 });
311
+ const state = await readState(root, taskId);
312
+ if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
313
+ const sessionId = await startManager(ctx, root, taskId, state.title ?? taskId, promptFor(state, root, taskId));
314
+ return Response.json({ ok: true, sessionId });
315
+ },
316
+ });
317
+
318
+ add({
319
+ path: DEPARTMENT_ROUTES.taskDelete,
320
+ methods: ['DELETE'],
321
+ requestBody: 'buffered',
322
+ fetch: async (request) => {
323
+ const url = new URL(request.url);
324
+ const root = url.searchParams.get('root');
325
+ const taskId = url.searchParams.get('taskId');
326
+ const by = url.searchParams.get('by');
327
+ if (!root || !taskId || !isHumanApprover(by)) return Response.json({ error: 'root, taskId, human signature required' }, { status: 400 });
328
+ const state = await readState(root, taskId);
329
+ if (!state) return Response.json({ error: 'task not found' }, { status: 404 });
330
+ const dir = join(root, 'docs', 'department', taskId);
331
+ const trash = join(root, 'docs', 'department', '.trash');
332
+ await mkdir(trash, { recursive: true });
333
+ const target = join(trash, `${taskId}-${Date.now()}`);
334
+ await rename(dir, target);
335
+ return Response.json({ ok: true, movedTo: target });
336
+ },
337
+ });
338
+
339
+ add({
340
+ path: DEPARTMENT_ROUTES.browseDirs,
341
+ methods: ['GET'],
342
+ requestBody: 'buffered',
343
+ fetch: async (request) => {
344
+ const url = new URL(request.url);
345
+ try {
346
+ const listing = await listDirectories(url.searchParams.get('path'));
347
+ const projects = [];
348
+ for (const name of listing.dirs) {
349
+ const full = join(listing.path, name);
350
+ if (await isGitProject(full)) projects.push(name);
351
+ }
352
+ return Response.json({ ...listing, projects });
353
+ } catch (error) {
354
+ return Response.json({ error: error.message }, { status: 400 });
355
+ }
356
+ },
357
+ });
358
+
231
359
  add({
232
360
  path: DEPARTMENT_ROUTES.pause,
233
361
  methods: ['POST'],
@@ -370,6 +498,7 @@ export function registerDepartmentRoutes(ctx, activity) {
370
498
  try {
371
499
  await assertApprovalReady(root, taskId, doc, state);
372
500
  const next = await writeState(root, approveDocument(state, { doc, by }));
501
+ await startManager(ctx, root, taskId, state.title ?? taskId, promptFor(next, root, taskId));
373
502
  return Response.json({ stage: next.stage, summary: next.approvals });
374
503
  } catch (error) {
375
504
  return Response.json({ error: error.message }, { status: 400 });