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.
package/client.js CHANGED
@@ -20,6 +20,7 @@ window.__ModuleLoader__.load({
20
20
  'nav.office': 'Офис',
21
21
  'nav.blueprint': 'Схема',
22
22
  'nav.charts': 'Графики',
23
+ 'nav.editor': 'Редактор',
23
24
  'nav.refresh': 'Обновить',
24
25
  'office.title': 'Офис отдела',
25
26
  'office.staff': 'сотрудников: {n} из {m}',
@@ -38,12 +39,13 @@ window.__ModuleLoader__.load({
38
39
  'tabs.billing': 'Бюджет',
39
40
  'tabs.git': 'Git',
40
41
 
41
- 'stage.analysis': 'Анализ',
42
+ 'stage.analysis': 'Обсуждение',
42
43
  'stage.concept': 'Концепция',
43
44
  'stage.concept_review': 'Проверка концепции',
44
45
  'stage.spec': 'ТЗ',
45
46
  'stage.spec_review': 'Проверка ТЗ',
46
47
  'stage.executing': 'Исполнение',
48
+ 'stage.release': 'Подготовка к продакшену',
47
49
  'stage.done': 'Завершено',
48
50
  'stage.blocked': 'Заблокировано',
49
51
  'status.pass': 'Пройдено',
@@ -77,6 +79,9 @@ window.__ModuleLoader__.load({
77
79
  'block.cost': 'Стоимость',
78
80
  'block.calls': 'Вызовов модели',
79
81
  'block.approval': 'Утверждение',
82
+ 'approve.spec': 'Утвердить ТЗ',
83
+ 'approve.concept': 'Утвердить концепцию',
84
+ 'doc.main': 'главный документ',
80
85
  'block.openQuestions': 'Открытые вопросы',
81
86
  'block.documents': 'Документы',
82
87
  'block.recentEvents': 'Последние события',
@@ -109,6 +114,23 @@ window.__ModuleLoader__.load({
109
114
  'branch.prefix': 'ветка',
110
115
 
111
116
 
117
+ 'dept.enabled': 'Отдел: вкл',
118
+ 'dept.disabled': 'Отдел: выкл',
119
+ 'dept.newTask': '+ Задача',
120
+ 'dept.createTitle': 'Новая задача отдела',
121
+ 'dept.root': 'Проект',
122
+ 'dept.taskId': 'ID задачи',
123
+ 'dept.title': 'Название',
124
+ 'dept.brief': 'Бриф',
125
+ 'dept.test': 'Команда тестов',
126
+ 'dept.create': 'Создать',
127
+ 'dept.pick': 'Выбрать…',
128
+ 'dept.up': '↑ Наверх',
129
+ 'dept.chooseThis': 'Выбрать эту папку',
130
+ 'dept.git': 'git-проекты',
131
+ 'dept.dirError': 'Не удалось прочитать каталог',
132
+ 'dept.cancel': 'Отмена',
133
+ 'dept.offBanner': 'Отдел выключен — новые задачи не запускаются, инструменты заблокированы.',
112
134
  'activity.title': 'Сейчас работают',
113
135
  'activity.none': 'активности нет',
114
136
  'office.lounge': 'КОМНАТА ОТДЫХА',
@@ -271,6 +293,7 @@ window.__ModuleLoader__.load({
271
293
  'nav.office': 'Office',
272
294
  'nav.blueprint': 'Blueprint',
273
295
  'nav.charts': 'Charts',
296
+ 'nav.editor': 'Editor',
274
297
  'nav.refresh': 'Refresh',
275
298
  'office.title': 'Department office',
276
299
  'office.staff': 'staff: {n} of {m}',
@@ -289,12 +312,13 @@ window.__ModuleLoader__.load({
289
312
  'tabs.billing': 'Budget',
290
313
  'tabs.git': 'Git',
291
314
 
292
- 'stage.analysis': 'Analysis',
315
+ 'stage.analysis': 'Discussion',
293
316
  'stage.concept': 'Concept',
294
317
  'stage.concept_review': 'Concept review',
295
318
  'stage.spec': 'Spec',
296
319
  'stage.spec_review': 'Spec review',
297
320
  'stage.executing': 'Execution',
321
+ 'stage.release': 'Production prep',
298
322
  'stage.done': 'Done',
299
323
  'stage.blocked': 'Blocked',
300
324
  'status.pass': 'Pass',
@@ -328,6 +352,9 @@ window.__ModuleLoader__.load({
328
352
  'block.cost': 'Cost',
329
353
  'block.calls': 'Model calls',
330
354
  'block.approval': 'Approval',
355
+ 'approve.spec': 'Approve spec',
356
+ 'approve.concept': 'Approve concept',
357
+ 'doc.main': 'key document',
331
358
  'block.openQuestions': 'Open questions',
332
359
  'block.documents': 'Documents',
333
360
  'block.recentEvents': 'Recent events',
@@ -360,6 +387,23 @@ window.__ModuleLoader__.load({
360
387
  'branch.prefix': 'branch',
361
388
 
362
389
 
390
+ 'dept.enabled': 'Department: on',
391
+ 'dept.disabled': 'Department: off',
392
+ 'dept.newTask': '+ Task',
393
+ 'dept.createTitle': 'New department task',
394
+ 'dept.root': 'Project',
395
+ 'dept.taskId': 'Task ID',
396
+ 'dept.title': 'Title',
397
+ 'dept.brief': 'Brief',
398
+ 'dept.test': 'Test command',
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',
405
+ 'dept.cancel': 'Cancel',
406
+ 'dept.offBanner': 'Department is off — new tasks are not started, tools are blocked.',
363
407
  'activity.title': 'Working now',
364
408
  'activity.none': 'no activity',
365
409
  'office.lounge': 'LOUNGE',
@@ -601,6 +645,12 @@ window.__ModuleLoader__.load({
601
645
  document: '/api/department/document',
602
646
  correction: '/api/department/correction',
603
647
  pause: '/api/department/pause',
648
+ settings: '/api/department/settings',
649
+ createTask: '/api/department/task/create',
650
+ editor: '/api/department/editor',
651
+ browseDirs: '/api/department/browse-dirs',
652
+ taskDelete: '/api/department/task/delete',
653
+ taskStart: '/api/department/task/start',
604
654
  projects: '/api/department/projects',
605
655
  review: '/api/department/review',
606
656
  }
@@ -665,7 +715,11 @@ window.__ModuleLoader__.load({
665
715
  .dept-table th { background: #182235; color: #c9d6ea; }
666
716
  .dept-table tr:nth-child(even) td { background: #121a28; }
667
717
  .dept-pre { white-space: pre-wrap; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: calc(var(--dept-text, 13px) - 1px); color: var(--dsw-alias-label-secondary, #b8c4d6); }
668
- .dept-empty { padding: 24px; text-align: center; color: var(--dsw-alias-label-tertiary, #8b98ad); }
718
+ .dept-modal { position: fixed; inset: 0; background: #0008; display: flex; align-items: center; justify-content: center; z-index: 50; }
719
+ .dept-modal-card { background: var(--dsw-alias-bg-secondary, #141a28); border: 1px solid var(--dsw-alias-border-secondary, #2a3446); border-radius: 12px; padding: 16px; width: min(560px, 92vw); display: flex; flex-direction: column; gap: 10px; }
720
+ .dept-form-row { display: grid; grid-template-columns: 140px 1fr; gap: 8px; align-items: center; }
721
+ .dept-form-row textarea { resize: vertical; }
722
+ .dept-empty { padding: 24px; text-align: center; color: var(--dsw-alias-label-tertiary, #8b98ad); }
669
723
  .dept-office-layout { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 12px; align-items: start; }
670
724
  .dept-office { min-width: 0; }
671
725
  .dept-office-side { width: 340px; border: 1px solid var(--dsw-alias-border-secondary, #232c3d); border-radius: 12px; padding: 10px; background: var(--dsw-alias-bg-secondary, #10151f); display: flex; flex-direction: column; gap: 6px; }
@@ -1222,6 +1276,11 @@ window.__ModuleLoader__.load({
1222
1276
  .catch((problem) => setContent(t('doc.error') + problem.message))
1223
1277
  }, [selected, root, taskId])
1224
1278
 
1279
+ const MAIN_DOCS = ['spec.md', 'concept.md', 'plan.md']
1280
+ const mainRank = (item) => {
1281
+ const index = MAIN_DOCS.indexOf(String(item.path).split('/').pop())
1282
+ return index === -1 ? 9 : index
1283
+ }
1225
1284
  const types = ['all', ...new Set(documents.map((item) => item.type))]
1226
1285
  const memoPaths = memos ?? []
1227
1286
  const isMemo = (item) => item.type === 'служебная записка' && memoPaths.some((path) => String(path).endsWith(item.path))
@@ -1232,7 +1291,7 @@ window.__ModuleLoader__.load({
1232
1291
  const haystack = (item.title + ' ' + item.path + ' ' + item.type).toLowerCase()
1233
1292
  return haystack.includes(query.trim().toLowerCase())
1234
1293
  })
1235
- .sort((a, b) => Number(isMemo(b)) - Number(isMemo(a)) || String(b.ts).localeCompare(String(a.ts)))
1294
+ .sort((a, b) => mainRank(a) - mainRank(b) || Number(isMemo(b)) - Number(isMemo(a)) || String(b.ts).localeCompare(String(a.ts)))
1236
1295
 
1237
1296
  return h('div', { style: { display: 'grid', gridTemplateColumns: '320px minmax(0, 1fr)', gap: '12px', alignItems: 'start' } },
1238
1297
  h('div', { className: 'dept-block', style: { maxHeight: '560px', overflow: 'auto' } },
@@ -1260,7 +1319,7 @@ window.__ModuleLoader__.load({
1260
1319
  : h('div', { className: 'dept-sub' }, t('doc.choose'))))
1261
1320
  }
1262
1321
 
1263
- function TaskDetail({ detail, onBack, onReload }) {
1322
+ function TaskDetail({ detail, onBack, onReload, onEditor, onDeleted }) {
1264
1323
  const docs = ['task.md', 'analysis.md', 'concept.md', 'spec.md', 'plan.md', 'backlog.md']
1265
1324
  const [tab, setTab] = useState('overview')
1266
1325
  const [name, setName] = useState(() => localStorage.getItem('dept-approver') || 'vladimir')
@@ -1325,6 +1384,29 @@ window.__ModuleLoader__.load({
1325
1384
  }
1326
1385
  }
1327
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
+
1328
1410
  async function post(path, body) {
1329
1411
  setBusy(true)
1330
1412
  setMessage(null)
@@ -1636,6 +1718,9 @@ window.__ModuleLoader__.load({
1636
1718
  : null),
1637
1719
  h('div', { className: 'dept-row' },
1638
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 }, 'Запустить отдел'),
1722
+ h('button', { className: 'dept-btn', onClick: () => onEditor && onEditor() }, t('nav.editor')),
1723
+ h('button', { className: 'dept-btn fail', disabled: busy, onClick: deleteTask }, 'Удалить'),
1639
1724
  h('button', {
1640
1725
  className: 'dept-btn',
1641
1726
  disabled: busy,
@@ -1656,12 +1741,12 @@ window.__ModuleLoader__.load({
1656
1741
  kv(t('block.cost'), `${budget?.costUSD ? '$' + budget.costUSD.toFixed(2) : '—'}${costRub ? ' ≈ ' + costRub.toFixed(0) + ' ₽' : ''}`),
1657
1742
  kv(t('block.calls'), usage?.calls ?? 0),
1658
1743
  h('div', { className: 'dept-bar' }, h('i', { style: { width: `${detail.progress}%` } }))),
1659
- (detail.stage === 'concept' && !approved.has('concept')) || (detail.stage === 'spec' && !approved.has('spec'))
1744
+ (detail.stage === 'spec_review' && !approved.has('spec')) || (detail.stage === 'concept_review' && !approved.has('concept'))
1660
1745
  ? h('div', { className: 'dept-block' },
1661
1746
  h('div', { className: 'dept-block-title' }, t('block.approval')),
1662
- detail.stage === 'concept'
1663
- ? h('button', { className: 'dept-btn', disabled: busy, onClick: () => post(ROUTES.approve, { root: detail.root, taskId: detail.taskId, doc: 'concept' }) }, 'Утвердить концепцию')
1664
- : h('button', { className: 'dept-btn', disabled: busy, onClick: () => post(ROUTES.approve, { root: detail.root, taskId: detail.taskId, doc: 'spec' }) }, 'Утвердить ТЗ'))
1747
+ detail.stage === 'spec_review'
1748
+ ? h('button', { className: 'dept-btn', disabled: busy, onClick: () => post(ROUTES.approve, { root: detail.root, taskId: detail.taskId, doc: 'spec' }) }, t('approve.spec'))
1749
+ : h('button', { className: 'dept-btn', disabled: busy, onClick: () => post(ROUTES.approve, { root: detail.root, taskId: detail.taskId, doc: 'concept' }) }, t('approve.concept')))
1665
1750
  : null),
1666
1751
  content,
1667
1752
  ),
@@ -2090,6 +2175,14 @@ window.__ModuleLoader__.load({
2090
2175
  const [loading, setLoading] = useState(true)
2091
2176
  const [selectedSession, setSelectedSession] = useState(null)
2092
2177
  const [projectFilter, setProjectFilter] = useState(null)
2178
+ const [name, setName] = useState(() => localStorage.getItem('dept-approver') || 'vladimir')
2179
+ const [settings, setSettings] = useState({ enabled: true })
2180
+ const [editorKey, setEditorKey] = useState('')
2181
+ const [showCreate, setShowCreate] = useState(false)
2182
+ const [form, setForm] = useState({ root: '', taskId: '', title: '', brief: '', testCommand: '' })
2183
+ const [creating, setCreating] = useState(false)
2184
+ const [createError, setCreateError] = useState(null)
2185
+ const [browse, setBrowse] = useState(null)
2093
2186
  const [langTick, setLangTick] = useState(0)
2094
2187
  const [textSize, setTextSize] = useState(() => {
2095
2188
  const saved = Number(localStorage.getItem('dept-text-size'))
@@ -2112,6 +2205,64 @@ window.__ModuleLoader__.load({
2112
2205
  }
2113
2206
  }
2114
2207
 
2208
+ useEffect(() => {
2209
+ api(ROUTES.settings).then(setSettings).catch(() => {})
2210
+ }, [])
2211
+
2212
+ async function postJson(path, body) {
2213
+ const response = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
2214
+ const data = await response.json().catch(() => ({}))
2215
+ if (!response.ok) throw new Error(data.error || response.statusText)
2216
+ return data
2217
+ }
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
+
2228
+ async function toggleDepartment() {
2229
+ try {
2230
+ const next = await postJson(ROUTES.settings, { enabled: !settings.enabled, by: name })
2231
+ setSettings(next)
2232
+ } catch (problem) {
2233
+ setError(problem.message)
2234
+ }
2235
+ }
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
+
2248
+ async function createTask() {
2249
+ setCreating(true)
2250
+ setCreateError(null)
2251
+ try {
2252
+ await postJson(ROUTES.createTask, { ...form, by: name })
2253
+ const created = { root: form.root, taskId: form.taskId, title: form.title }
2254
+ setShowCreate(false)
2255
+ setForm({ root: '', taskId: '', title: '', brief: '', testCommand: '' })
2256
+ setBrowse(null)
2257
+ await loadTasks()
2258
+ await openTask(created)
2259
+ } catch (problem) {
2260
+ setCreateError(problem.message)
2261
+ } finally {
2262
+ setCreating(false)
2263
+ }
2264
+ }
2265
+
2115
2266
  async function openTask(task) {
2116
2267
  setSelected(task)
2117
2268
  setDetail(null)
@@ -2132,7 +2283,7 @@ window.__ModuleLoader__.load({
2132
2283
 
2133
2284
  if (selected) {
2134
2285
  return detail
2135
- ? h(TaskDetail, { detail, 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) } })
2136
2287
  : h('div', { className: 'dept-root' }, h('div', { className: 'dept-empty' }, t('loading.task')))
2137
2288
  }
2138
2289
 
@@ -2144,7 +2295,9 @@ window.__ModuleLoader__.load({
2144
2295
  h('button', { className: 'dept-btn active' }, t('nav.projects')),
2145
2296
  h('button', { className: 'dept-btn', onClick: () => setView('office') }, t('nav.office')),
2146
2297
  h('button', { className: 'dept-btn', onClick: () => setView('blueprint') }, t('nav.blueprint')),
2147
- h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')))),
2298
+ h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')), h('button', { className: 'dept-btn', onClick: () => setView('editor') }, t('nav.editor')),
2299
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2300
+ h('button', { className: 'dept-btn' + (settings.enabled ? '' : ' fail'), onClick: toggleDepartment }, settings.enabled ? t('dept.enabled') : t('dept.disabled')))),
2148
2301
  h(ProjectsView, { onOpen: (root) => { setProjectFilter(root); setView('board') } }))
2149
2302
  }
2150
2303
 
@@ -2160,6 +2313,30 @@ window.__ModuleLoader__.load({
2160
2313
  h(ChartsView, { tasks }))
2161
2314
  }
2162
2315
 
2316
+ if (view === 'editor') {
2317
+ const editorTasks = projectFilter ? tasks.filter((task) => task.root === projectFilter) : tasks
2318
+ const current = editorTasks.find((task) => `${task.root}:${task.taskId}` === editorKey) ?? editorTasks[0] ?? null
2319
+ return h('div', { className: 'dept-root' },
2320
+ h('div', { className: 'dept-head' },
2321
+ h('div', null,
2322
+ h('div', { className: 'dept-title' }, t('nav.editor')),
2323
+ h('div', { className: 'dept-sub' }, 'Рисуйте спрайты и отправляйте художнику; трафарет помогает обводить контуры.')),
2324
+ h('div', { className: 'dept-row' },
2325
+ h('select', {
2326
+ className: 'dept-input',
2327
+ value: current ? `${current.root}:${current.taskId}` : '',
2328
+ onChange: (event) => setEditorKey(event.target.value),
2329
+ }, ...editorTasks.map((task) => h('option', { key: `${task.root}:${task.taskId}`, value: `${task.root}:${task.taskId}` }, `${task.root.split('/').pop()} · ${task.taskId}`))),
2330
+ h('button', { className: 'dept-btn', onClick: () => setView('board') }, '← ' + t('nav.board')))),
2331
+ current
2332
+ ? h('iframe', {
2333
+ src: `${ROUTES.editor}?root=${encodeURIComponent(current.root)}&taskId=${encodeURIComponent(current.taskId)}`,
2334
+ style: { width: '100%', height: 'calc(100vh - 150px)', border: '0', borderRadius: '12px', background: '#0b0f18' },
2335
+ title: 'Пиксель-редактор',
2336
+ })
2337
+ : h('div', { className: 'dept-empty' }, t('empty.noTasksHint')))
2338
+ }
2339
+
2163
2340
  if (view === 'blueprint') {
2164
2341
  return h('div', { className: 'dept-root' },
2165
2342
  h('div', { className: 'dept-head' },
@@ -2178,7 +2355,9 @@ window.__ModuleLoader__.load({
2178
2355
  h('button', { className: 'dept-btn', onClick: () => setView('board') }, t('nav.board')),
2179
2356
  h('button', { className: 'dept-btn active', onClick: () => setView('office') }, t('nav.office')),
2180
2357
  h('button', { className: 'dept-btn', onClick: () => setView('blueprint') }, t('nav.blueprint')),
2181
- h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts'))),
2358
+ h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')), h('button', { className: 'dept-btn', onClick: () => setView('editor') }, t('nav.editor')),
2359
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2360
+ h('button', { className: 'dept-btn' + (settings.enabled ? '' : ' fail'), onClick: toggleDepartment }, settings.enabled ? t('dept.enabled') : t('dept.disabled'))),
2182
2361
  h('button', { className: 'dept-btn', onClick: loadTasks }, t('nav.refresh'))),
2183
2362
  h(OfficeView, { items: activity.items, selected: selectedSession, onSelect: setSelectedSession, tasks, attention, onOpenTask: (root) => { const task = tasks.find((candidate) => candidate.root === root); if (task) openTask(task) }, party, paused: tasks.some((task) => task.paused), pauseReason: (tasks.find((task) => task.paused) ?? {}).pauseReason }),
2184
2363
  )
@@ -2197,7 +2376,9 @@ window.__ModuleLoader__.load({
2197
2376
  h('button', { className: 'dept-btn', onClick: () => setView('projects') }, t('nav.projects')),
2198
2377
  h('button', { className: 'dept-btn', onClick: () => setView('office') }, t('nav.office')),
2199
2378
  h('button', { className: 'dept-btn', onClick: () => setView('blueprint') }, t('nav.blueprint')),
2200
- h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')),
2379
+ h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')), h('button', { className: 'dept-btn', onClick: () => setView('editor') }, t('nav.editor')),
2380
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2381
+ h('button', { className: 'dept-btn' + (settings.enabled ? '' : ' fail'), onClick: toggleDepartment }, settings.enabled ? t('dept.enabled') : t('dept.disabled')),
2201
2382
  h('button', {
2202
2383
  className: 'dept-btn',
2203
2384
  onClick: () => {
@@ -2207,8 +2388,15 @@ window.__ModuleLoader__.load({
2207
2388
  title: 'Language / Язык',
2208
2389
  }, deptLang === 'en' ? 'RU' : 'EN'),
2209
2390
  h('button', { className: 'dept-btn', onClick: () => setTextSize(textSize >= 19 ? 12 : textSize + 2), title: t('title.textSize') }, 'A+'),
2391
+ h('button', {
2392
+ className: 'dept-btn' + (settings.enabled ? '' : ' fail'),
2393
+ onClick: toggleDepartment,
2394
+ title: settings.enabled ? 'Выключить отдел' : 'Включить отдел',
2395
+ }, settings.enabled ? t('dept.enabled') : t('dept.disabled')),
2396
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2210
2397
  h('button', { className: 'dept-btn', onClick: loadTasks }, t('nav.refresh'))),
2211
2398
  ),
2399
+ settings.enabled ? null : h('div', { className: 'dept-badge fail' }, t('dept.offBanner')),
2212
2400
  attention > 0
2213
2401
  ? h('div', { className: 'dept-block' },
2214
2402
  h('div', { className: 'dept-block-title' }, 'Требует внимания'),
@@ -2220,6 +2408,45 @@ window.__ModuleLoader__.load({
2220
2408
  (projectFilter ? tasks.filter((task) => task.root === projectFilter) : tasks).length === 0 && !loading
2221
2409
  ? h('div', { className: 'dept-empty' }, t('empty.noTasksHint'))
2222
2410
  : h('div', { className: 'dept-list' }, ...tasks.map((task) => h(TaskCard, { key: `${task.root}:${task.taskId}`, task, onOpen: openTask }))),
2411
+ showCreate
2412
+ ? h('div', { className: 'dept-modal' },
2413
+ h('div', { className: 'dept-modal-card' },
2414
+ h('div', { className: 'dept-title' }, t('dept.createTitle')),
2415
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.root')),
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,
2437
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.taskId')),
2438
+ h('input', { className: 'dept-input', value: form.taskId, placeholder: 'feature-01', onChange: (event) => setForm({ ...form, taskId: event.target.value }) })),
2439
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.title')),
2440
+ h('input', { className: 'dept-input', value: form.title, onChange: (event) => setForm({ ...form, title: event.target.value }) })),
2441
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.test')),
2442
+ h('input', { className: 'dept-input', value: form.testCommand, placeholder: 'авто: npm test, если есть package.json', onChange: (event) => setForm({ ...form, testCommand: event.target.value }) })),
2443
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.brief')),
2444
+ h('textarea', { className: 'dept-input', rows: 5, value: form.brief, onChange: (event) => setForm({ ...form, brief: event.target.value }) })),
2445
+ createError ? h('div', { className: 'dept-badge fail' }, createError) : null,
2446
+ h('div', { className: 'dept-row' },
2447
+ h('button', { className: 'dept-btn', disabled: creating || !form.root || !form.taskId, onClick: createTask }, t('dept.create')),
2448
+ h('button', { className: 'dept-btn', onClick: () => { setShowCreate(false); setCreateError(null) } }, t('dept.cancel')))))
2449
+ : null,
2223
2450
  )
2224
2451
  }
2225
2452
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-department",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
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 { access, readFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { listQuestions, taskDir } from './store.js';
7
+
8
+ async function exists(path) {
9
+ try { await access(path); return true; } catch { return false; }
10
+ }
11
+
12
+ /**
13
+ * Проверяет готовность документа к утверждению человеком.
14
+ *
15
+ * @param {string} root Корень проекта.
16
+ * @param {string} taskId Задача.
17
+ * @param {'spec'|'concept'} doc Документ.
18
+ * @param {object} state Состояние.
19
+ */
20
+ export async function assertApprovalReady(root, taskId, doc, state) {
21
+ const dir = taskDir(root, taskId);
22
+ if (doc === 'spec') {
23
+ if (!(await exists(join(dir, 'discussion.md')))) {
24
+ throw new Error('нельзя утвердить ТЗ: нет discussion.md — сначала обсудите задачу (dept_discussion)');
25
+ }
26
+ const open = listQuestions(state, { status: 'open' });
27
+ if (open.length > 0) {
28
+ throw new Error(`нельзя утвердить ТЗ: открытых вопросов ${open.length}; получите ответы или закройте их`);
29
+ }
30
+ }
31
+ if (doc === 'concept') {
32
+ const path = join(dir, 'concept.md');
33
+ if (!(await exists(path))) throw new Error('нельзя утвердить концепцию: нет concept.md');
34
+ const text = await readFile(path, 'utf8');
35
+ const variants = (text.match(/^#{2,3}\s*(?:\d+[.)]\s*)?Вариант/gim) ?? []).length;
36
+ if (variants < 2) {
37
+ throw new Error('нельзя утвердить концепцию: нужно минимум 2 варианта (## Вариант) с плюсами/минусами и выбором');
38
+ }
39
+ }
40
+ }
@@ -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
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Создание задачи отдела — общая логика для инструмента и HTTP-маршрута.
3
+ */
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { appendEvent, createState, readState, taskDir, writeState } from './store.js';
7
+ import { ensureBranch, isRepo, runGit } from './git.js';
8
+
9
+ /**
10
+ * Создаёт задачу: состояние, ветка, task.md.
11
+ *
12
+ * @param {string} root Корень проекта.
13
+ * @param {string} taskId Идентификатор.
14
+ * @param {object} [options] Параметры.
15
+ * @returns {Promise<object>} Состояние.
16
+ */
17
+ export async function createDepartmentTask(root, taskId, options = {}) {
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
+ }
28
+ const existing = await readState(root, taskId);
29
+ if (existing) throw new Error(`task already exists: ${taskId}`);
30
+
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
+ }
41
+ if (options.release === true) {
42
+ const template = await readFile(new URL('../templates/release.md', import.meta.url), 'utf8');
43
+ brief = (brief ? brief + '\n\n' : '') + 'Подготовка к релизу (шаблон):\n\n' + template;
44
+ }
45
+
46
+ let state = createState({
47
+ root,
48
+ taskId,
49
+ title: options.title,
50
+ branch: options.branch,
51
+ origin: options.origin ?? null,
52
+ testCommand,
53
+ maxAttempts: options.maxAttempts,
54
+ budgetTokens: options.budgetTokens,
55
+ });
56
+ const branch = await ensureBranch(root, state.branch);
57
+ if (!branch.ok) throw new Error(`cannot create branch ${state.branch}: ${branch.error ?? ''}`);
58
+ state = appendEvent(state, { actor: 'manager', action: 'branch_ready', detail: branch.branch });
59
+
60
+ const process = [
61
+ '## Порядок работы отдела',
62
+ '',
63
+ '1. **Обсуждение** (`analysis`): вопросы, требования, ограничения. Код не пишется.',
64
+ '2. **ТЗ и концепция** — в любом порядке, итеративно:',
65
+ ' - ТЗ (`spec.md`) — требования; человек утверждает на `spec_review`;',
66
+ ' - концепция (`concept.md`) — варианты архитектора, критика специалистов, вопросы человеку;',
67
+ ' человек утверждает на `concept_review`;',
68
+ ' - после утверждения первого документа отдел переходит к другому и уточняет его.',
69
+ '3. Проект запускается (`executing`) только когда утверждены **оба**: ТЗ и концепция.',
70
+ '4. **План** (`plan.md`): первый документ исполнения; затем этапы, тесты, ревью, коммиты.',
71
+ '',
72
+ 'Три главных документа — `spec.md`, `concept.md`, `plan.md` — всегда актуальны:',
73
+ 'правки через `dept_amend`/`dept_section`, в панели они закреплены сверху.',
74
+ ].join('\n');
75
+ const fullBrief = brief !== '' ? `${brief}\n\n${process}\n` : `${process}\n`;
76
+ await mkdir(taskDir(root, taskId), { recursive: true });
77
+ await writeFile(join(taskDir(root, taskId), 'task.md'), fullBrief, 'utf8');
78
+ return writeState(root, state);
79
+ }