dsh-department 0.1.2 → 0.2.0

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,18 @@ 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.cancel': 'Отмена',
128
+ 'dept.offBanner': 'Отдел выключен — новые задачи не запускаются, инструменты заблокированы.',
112
129
  'activity.title': 'Сейчас работают',
113
130
  'activity.none': 'активности нет',
114
131
  'office.lounge': 'КОМНАТА ОТДЫХА',
@@ -271,6 +288,7 @@ window.__ModuleLoader__.load({
271
288
  'nav.office': 'Office',
272
289
  'nav.blueprint': 'Blueprint',
273
290
  'nav.charts': 'Charts',
291
+ 'nav.editor': 'Editor',
274
292
  'nav.refresh': 'Refresh',
275
293
  'office.title': 'Department office',
276
294
  'office.staff': 'staff: {n} of {m}',
@@ -289,12 +307,13 @@ window.__ModuleLoader__.load({
289
307
  'tabs.billing': 'Budget',
290
308
  'tabs.git': 'Git',
291
309
 
292
- 'stage.analysis': 'Analysis',
310
+ 'stage.analysis': 'Discussion',
293
311
  'stage.concept': 'Concept',
294
312
  'stage.concept_review': 'Concept review',
295
313
  'stage.spec': 'Spec',
296
314
  'stage.spec_review': 'Spec review',
297
315
  'stage.executing': 'Execution',
316
+ 'stage.release': 'Production prep',
298
317
  'stage.done': 'Done',
299
318
  'stage.blocked': 'Blocked',
300
319
  'status.pass': 'Pass',
@@ -328,6 +347,9 @@ window.__ModuleLoader__.load({
328
347
  'block.cost': 'Cost',
329
348
  'block.calls': 'Model calls',
330
349
  'block.approval': 'Approval',
350
+ 'approve.spec': 'Approve spec',
351
+ 'approve.concept': 'Approve concept',
352
+ 'doc.main': 'key document',
331
353
  'block.openQuestions': 'Open questions',
332
354
  'block.documents': 'Documents',
333
355
  'block.recentEvents': 'Recent events',
@@ -360,6 +382,18 @@ window.__ModuleLoader__.load({
360
382
  'branch.prefix': 'branch',
361
383
 
362
384
 
385
+ 'dept.enabled': 'Department: on',
386
+ 'dept.disabled': 'Department: off',
387
+ 'dept.newTask': '+ Task',
388
+ 'dept.createTitle': 'New department task',
389
+ 'dept.root': 'Project',
390
+ 'dept.taskId': 'Task ID',
391
+ 'dept.title': 'Title',
392
+ 'dept.brief': 'Brief',
393
+ 'dept.test': 'Test command',
394
+ 'dept.create': 'Create',
395
+ 'dept.cancel': 'Cancel',
396
+ 'dept.offBanner': 'Department is off — new tasks are not started, tools are blocked.',
363
397
  'activity.title': 'Working now',
364
398
  'activity.none': 'no activity',
365
399
  'office.lounge': 'LOUNGE',
@@ -601,6 +635,9 @@ window.__ModuleLoader__.load({
601
635
  document: '/api/department/document',
602
636
  correction: '/api/department/correction',
603
637
  pause: '/api/department/pause',
638
+ settings: '/api/department/settings',
639
+ createTask: '/api/department/task/create',
640
+ editor: '/api/department/editor',
604
641
  projects: '/api/department/projects',
605
642
  review: '/api/department/review',
606
643
  }
@@ -665,7 +702,11 @@ window.__ModuleLoader__.load({
665
702
  .dept-table th { background: #182235; color: #c9d6ea; }
666
703
  .dept-table tr:nth-child(even) td { background: #121a28; }
667
704
  .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); }
705
+ .dept-modal { position: fixed; inset: 0; background: #0008; display: flex; align-items: center; justify-content: center; z-index: 50; }
706
+ .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; }
707
+ .dept-form-row { display: grid; grid-template-columns: 140px 1fr; gap: 8px; align-items: center; }
708
+ .dept-form-row textarea { resize: vertical; }
709
+ .dept-empty { padding: 24px; text-align: center; color: var(--dsw-alias-label-tertiary, #8b98ad); }
669
710
  .dept-office-layout { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 12px; align-items: start; }
670
711
  .dept-office { min-width: 0; }
671
712
  .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 +1263,11 @@ window.__ModuleLoader__.load({
1222
1263
  .catch((problem) => setContent(t('doc.error') + problem.message))
1223
1264
  }, [selected, root, taskId])
1224
1265
 
1266
+ const MAIN_DOCS = ['spec.md', 'concept.md', 'plan.md']
1267
+ const mainRank = (item) => {
1268
+ const index = MAIN_DOCS.indexOf(String(item.path).split('/').pop())
1269
+ return index === -1 ? 9 : index
1270
+ }
1225
1271
  const types = ['all', ...new Set(documents.map((item) => item.type))]
1226
1272
  const memoPaths = memos ?? []
1227
1273
  const isMemo = (item) => item.type === 'служебная записка' && memoPaths.some((path) => String(path).endsWith(item.path))
@@ -1232,7 +1278,7 @@ window.__ModuleLoader__.load({
1232
1278
  const haystack = (item.title + ' ' + item.path + ' ' + item.type).toLowerCase()
1233
1279
  return haystack.includes(query.trim().toLowerCase())
1234
1280
  })
1235
- .sort((a, b) => Number(isMemo(b)) - Number(isMemo(a)) || String(b.ts).localeCompare(String(a.ts)))
1281
+ .sort((a, b) => mainRank(a) - mainRank(b) || Number(isMemo(b)) - Number(isMemo(a)) || String(b.ts).localeCompare(String(a.ts)))
1236
1282
 
1237
1283
  return h('div', { style: { display: 'grid', gridTemplateColumns: '320px minmax(0, 1fr)', gap: '12px', alignItems: 'start' } },
1238
1284
  h('div', { className: 'dept-block', style: { maxHeight: '560px', overflow: 'auto' } },
@@ -1260,7 +1306,7 @@ window.__ModuleLoader__.load({
1260
1306
  : h('div', { className: 'dept-sub' }, t('doc.choose'))))
1261
1307
  }
1262
1308
 
1263
- function TaskDetail({ detail, onBack, onReload }) {
1309
+ function TaskDetail({ detail, onBack, onReload, onEditor }) {
1264
1310
  const docs = ['task.md', 'analysis.md', 'concept.md', 'spec.md', 'plan.md', 'backlog.md']
1265
1311
  const [tab, setTab] = useState('overview')
1266
1312
  const [name, setName] = useState(() => localStorage.getItem('dept-approver') || 'vladimir')
@@ -1636,6 +1682,7 @@ window.__ModuleLoader__.load({
1636
1682
  : null),
1637
1683
  h('div', { className: 'dept-row' },
1638
1684
  h('input', { className: 'dept-input', value: name, onChange: (event) => setName(event.target.value), placeholder: t('form.name'), title: t('form.nameTitle') }),
1685
+ h('button', { className: 'dept-btn', onClick: () => onEditor && onEditor() }, t('nav.editor')),
1639
1686
  h('button', {
1640
1687
  className: 'dept-btn',
1641
1688
  disabled: busy,
@@ -1656,12 +1703,12 @@ window.__ModuleLoader__.load({
1656
1703
  kv(t('block.cost'), `${budget?.costUSD ? '$' + budget.costUSD.toFixed(2) : '—'}${costRub ? ' ≈ ' + costRub.toFixed(0) + ' ₽' : ''}`),
1657
1704
  kv(t('block.calls'), usage?.calls ?? 0),
1658
1705
  h('div', { className: 'dept-bar' }, h('i', { style: { width: `${detail.progress}%` } }))),
1659
- (detail.stage === 'concept' && !approved.has('concept')) || (detail.stage === 'spec' && !approved.has('spec'))
1706
+ (detail.stage === 'spec_review' && !approved.has('spec')) || (detail.stage === 'concept_review' && !approved.has('concept'))
1660
1707
  ? h('div', { className: 'dept-block' },
1661
1708
  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' }) }, 'Утвердить ТЗ'))
1709
+ detail.stage === 'spec_review'
1710
+ ? h('button', { className: 'dept-btn', disabled: busy, onClick: () => post(ROUTES.approve, { root: detail.root, taskId: detail.taskId, doc: 'spec' }) }, t('approve.spec'))
1711
+ : h('button', { className: 'dept-btn', disabled: busy, onClick: () => post(ROUTES.approve, { root: detail.root, taskId: detail.taskId, doc: 'concept' }) }, t('approve.concept')))
1665
1712
  : null),
1666
1713
  content,
1667
1714
  ),
@@ -2090,6 +2137,13 @@ window.__ModuleLoader__.load({
2090
2137
  const [loading, setLoading] = useState(true)
2091
2138
  const [selectedSession, setSelectedSession] = useState(null)
2092
2139
  const [projectFilter, setProjectFilter] = useState(null)
2140
+ const [name, setName] = useState(() => localStorage.getItem('dept-approver') || 'vladimir')
2141
+ const [settings, setSettings] = useState({ enabled: true })
2142
+ const [editorKey, setEditorKey] = useState('')
2143
+ const [showCreate, setShowCreate] = useState(false)
2144
+ const [form, setForm] = useState({ root: '', taskId: '', title: '', brief: '', testCommand: '' })
2145
+ const [creating, setCreating] = useState(false)
2146
+ const [createError, setCreateError] = useState(null)
2093
2147
  const [langTick, setLangTick] = useState(0)
2094
2148
  const [textSize, setTextSize] = useState(() => {
2095
2149
  const saved = Number(localStorage.getItem('dept-text-size'))
@@ -2112,6 +2166,41 @@ window.__ModuleLoader__.load({
2112
2166
  }
2113
2167
  }
2114
2168
 
2169
+ useEffect(() => {
2170
+ api(ROUTES.settings).then(setSettings).catch(() => {})
2171
+ }, [])
2172
+
2173
+ async function postJson(path, body) {
2174
+ const response = await fetch(path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
2175
+ const data = await response.json().catch(() => ({}))
2176
+ if (!response.ok) throw new Error(data.error || response.statusText)
2177
+ return data
2178
+ }
2179
+
2180
+ async function toggleDepartment() {
2181
+ try {
2182
+ const next = await postJson(ROUTES.settings, { enabled: !settings.enabled, by: name })
2183
+ setSettings(next)
2184
+ } catch (problem) {
2185
+ setError(problem.message)
2186
+ }
2187
+ }
2188
+
2189
+ async function createTask() {
2190
+ setCreating(true)
2191
+ setCreateError(null)
2192
+ try {
2193
+ await postJson(ROUTES.createTask, { ...form, by: name })
2194
+ setShowCreate(false)
2195
+ setForm({ root: '', taskId: '', title: '', brief: '', testCommand: '' })
2196
+ await loadTasks()
2197
+ } catch (problem) {
2198
+ setCreateError(problem.message)
2199
+ } finally {
2200
+ setCreating(false)
2201
+ }
2202
+ }
2203
+
2115
2204
  async function openTask(task) {
2116
2205
  setSelected(task)
2117
2206
  setDetail(null)
@@ -2132,7 +2221,7 @@ window.__ModuleLoader__.load({
2132
2221
 
2133
2222
  if (selected) {
2134
2223
  return detail
2135
- ? h(TaskDetail, { detail, onBack: () => { setSelected(null); setDetail(null) }, onReload: () => { if (selected) openTask(selected) } })
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) } })
2136
2225
  : h('div', { className: 'dept-root' }, h('div', { className: 'dept-empty' }, t('loading.task')))
2137
2226
  }
2138
2227
 
@@ -2144,7 +2233,9 @@ window.__ModuleLoader__.load({
2144
2233
  h('button', { className: 'dept-btn active' }, t('nav.projects')),
2145
2234
  h('button', { className: 'dept-btn', onClick: () => setView('office') }, t('nav.office')),
2146
2235
  h('button', { className: 'dept-btn', onClick: () => setView('blueprint') }, t('nav.blueprint')),
2147
- h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')))),
2236
+ h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')), h('button', { className: 'dept-btn', onClick: () => setView('editor') }, t('nav.editor')),
2237
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2238
+ h('button', { className: 'dept-btn' + (settings.enabled ? '' : ' fail'), onClick: toggleDepartment }, settings.enabled ? t('dept.enabled') : t('dept.disabled')))),
2148
2239
  h(ProjectsView, { onOpen: (root) => { setProjectFilter(root); setView('board') } }))
2149
2240
  }
2150
2241
 
@@ -2160,6 +2251,30 @@ window.__ModuleLoader__.load({
2160
2251
  h(ChartsView, { tasks }))
2161
2252
  }
2162
2253
 
2254
+ if (view === 'editor') {
2255
+ const editorTasks = projectFilter ? tasks.filter((task) => task.root === projectFilter) : tasks
2256
+ const current = editorTasks.find((task) => `${task.root}:${task.taskId}` === editorKey) ?? editorTasks[0] ?? null
2257
+ return h('div', { className: 'dept-root' },
2258
+ h('div', { className: 'dept-head' },
2259
+ h('div', null,
2260
+ h('div', { className: 'dept-title' }, t('nav.editor')),
2261
+ h('div', { className: 'dept-sub' }, 'Рисуйте спрайты и отправляйте художнику; трафарет помогает обводить контуры.')),
2262
+ h('div', { className: 'dept-row' },
2263
+ h('select', {
2264
+ className: 'dept-input',
2265
+ value: current ? `${current.root}:${current.taskId}` : '',
2266
+ onChange: (event) => setEditorKey(event.target.value),
2267
+ }, ...editorTasks.map((task) => h('option', { key: `${task.root}:${task.taskId}`, value: `${task.root}:${task.taskId}` }, `${task.root.split('/').pop()} · ${task.taskId}`))),
2268
+ h('button', { className: 'dept-btn', onClick: () => setView('board') }, '← ' + t('nav.board')))),
2269
+ current
2270
+ ? h('iframe', {
2271
+ src: `${ROUTES.editor}?root=${encodeURIComponent(current.root)}&taskId=${encodeURIComponent(current.taskId)}`,
2272
+ style: { width: '100%', height: 'calc(100vh - 150px)', border: '0', borderRadius: '12px', background: '#0b0f18' },
2273
+ title: 'Пиксель-редактор',
2274
+ })
2275
+ : h('div', { className: 'dept-empty' }, t('empty.noTasksHint')))
2276
+ }
2277
+
2163
2278
  if (view === 'blueprint') {
2164
2279
  return h('div', { className: 'dept-root' },
2165
2280
  h('div', { className: 'dept-head' },
@@ -2178,7 +2293,9 @@ window.__ModuleLoader__.load({
2178
2293
  h('button', { className: 'dept-btn', onClick: () => setView('board') }, t('nav.board')),
2179
2294
  h('button', { className: 'dept-btn active', onClick: () => setView('office') }, t('nav.office')),
2180
2295
  h('button', { className: 'dept-btn', onClick: () => setView('blueprint') }, t('nav.blueprint')),
2181
- h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts'))),
2296
+ h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')), h('button', { className: 'dept-btn', onClick: () => setView('editor') }, t('nav.editor')),
2297
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2298
+ h('button', { className: 'dept-btn' + (settings.enabled ? '' : ' fail'), onClick: toggleDepartment }, settings.enabled ? t('dept.enabled') : t('dept.disabled'))),
2182
2299
  h('button', { className: 'dept-btn', onClick: loadTasks }, t('nav.refresh'))),
2183
2300
  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
2301
  )
@@ -2197,7 +2314,9 @@ window.__ModuleLoader__.load({
2197
2314
  h('button', { className: 'dept-btn', onClick: () => setView('projects') }, t('nav.projects')),
2198
2315
  h('button', { className: 'dept-btn', onClick: () => setView('office') }, t('nav.office')),
2199
2316
  h('button', { className: 'dept-btn', onClick: () => setView('blueprint') }, t('nav.blueprint')),
2200
- h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')),
2317
+ h('button', { className: 'dept-btn', onClick: () => setView('charts') }, t('nav.charts')), h('button', { className: 'dept-btn', onClick: () => setView('editor') }, t('nav.editor')),
2318
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2319
+ h('button', { className: 'dept-btn' + (settings.enabled ? '' : ' fail'), onClick: toggleDepartment }, settings.enabled ? t('dept.enabled') : t('dept.disabled')),
2201
2320
  h('button', {
2202
2321
  className: 'dept-btn',
2203
2322
  onClick: () => {
@@ -2207,8 +2326,15 @@ window.__ModuleLoader__.load({
2207
2326
  title: 'Language / Язык',
2208
2327
  }, deptLang === 'en' ? 'RU' : 'EN'),
2209
2328
  h('button', { className: 'dept-btn', onClick: () => setTextSize(textSize >= 19 ? 12 : textSize + 2), title: t('title.textSize') }, 'A+'),
2329
+ h('button', {
2330
+ className: 'dept-btn' + (settings.enabled ? '' : ' fail'),
2331
+ onClick: toggleDepartment,
2332
+ title: settings.enabled ? 'Выключить отдел' : 'Включить отдел',
2333
+ }, settings.enabled ? t('dept.enabled') : t('dept.disabled')),
2334
+ h('button', { className: 'dept-btn', onClick: () => setShowCreate(true) }, t('dept.newTask')),
2210
2335
  h('button', { className: 'dept-btn', onClick: loadTasks }, t('nav.refresh'))),
2211
2336
  ),
2337
+ settings.enabled ? null : h('div', { className: 'dept-badge fail' }, t('dept.offBanner')),
2212
2338
  attention > 0
2213
2339
  ? h('div', { className: 'dept-block' },
2214
2340
  h('div', { className: 'dept-block-title' }, 'Требует внимания'),
@@ -2220,6 +2346,25 @@ window.__ModuleLoader__.load({
2220
2346
  (projectFilter ? tasks.filter((task) => task.root === projectFilter) : tasks).length === 0 && !loading
2221
2347
  ? h('div', { className: 'dept-empty' }, t('empty.noTasksHint'))
2222
2348
  : h('div', { className: 'dept-list' }, ...tasks.map((task) => h(TaskCard, { key: `${task.root}:${task.taskId}`, task, onOpen: openTask }))),
2349
+ showCreate
2350
+ ? h('div', { className: 'dept-modal' },
2351
+ h('div', { className: 'dept-modal-card' },
2352
+ h('div', { className: 'dept-title' }, t('dept.createTitle')),
2353
+ 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 }) })),
2355
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.taskId')),
2356
+ h('input', { className: 'dept-input', value: form.taskId, placeholder: 'feature-01', onChange: (event) => setForm({ ...form, taskId: event.target.value }) })),
2357
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.title')),
2358
+ h('input', { className: 'dept-input', value: form.title, onChange: (event) => setForm({ ...form, title: event.target.value }) })),
2359
+ 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 }) })),
2361
+ h('div', { className: 'dept-form-row' }, h('label', null, t('dept.brief')),
2362
+ h('textarea', { className: 'dept-input', rows: 5, value: form.brief, onChange: (event) => setForm({ ...form, brief: event.target.value }) })),
2363
+ createError ? h('div', { className: 'dept-badge fail' }, createError) : null,
2364
+ h('div', { className: 'dept-row' },
2365
+ h('button', { className: 'dept-btn', disabled: creating || !form.root || !form.taskId, onClick: createTask }, t('dept.create')),
2366
+ h('button', { className: 'dept-btn', onClick: () => { setShowCreate(false); setCreateError(null) } }, t('dept.cancel')))))
2367
+ : null,
2223
2368
  )
2224
2369
  }
2225
2370
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-department",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
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,61 @@
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 } 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))) throw new Error(`not a git repository: ${root}`);
19
+ const existing = await readState(root, taskId);
20
+ if (existing) throw new Error(`task already exists: ${taskId}`);
21
+
22
+ let brief = typeof options.brief === 'string' ? options.brief.trim() : '';
23
+ if (options.release === true) {
24
+ const template = await readFile(new URL('../templates/release.md', import.meta.url), 'utf8');
25
+ brief = (brief ? brief + '\n\n' : '') + 'Подготовка к релизу (шаблон):\n\n' + template;
26
+ }
27
+
28
+ let state = createState({
29
+ root,
30
+ taskId,
31
+ title: options.title,
32
+ branch: options.branch,
33
+ origin: options.origin ?? null,
34
+ testCommand: options.testCommand ?? null,
35
+ maxAttempts: options.maxAttempts,
36
+ budgetTokens: options.budgetTokens,
37
+ });
38
+ const branch = await ensureBranch(root, state.branch);
39
+ if (!branch.ok) throw new Error(`cannot create branch ${state.branch}: ${branch.error ?? ''}`);
40
+ state = appendEvent(state, { actor: 'manager', action: 'branch_ready', detail: branch.branch });
41
+
42
+ const process = [
43
+ '## Порядок работы отдела',
44
+ '',
45
+ '1. **Обсуждение** (`analysis`): вопросы, требования, ограничения. Код не пишется.',
46
+ '2. **ТЗ и концепция** — в любом порядке, итеративно:',
47
+ ' - ТЗ (`spec.md`) — требования; человек утверждает на `spec_review`;',
48
+ ' - концепция (`concept.md`) — варианты архитектора, критика специалистов, вопросы человеку;',
49
+ ' человек утверждает на `concept_review`;',
50
+ ' - после утверждения первого документа отдел переходит к другому и уточняет его.',
51
+ '3. Проект запускается (`executing`) только когда утверждены **оба**: ТЗ и концепция.',
52
+ '4. **План** (`plan.md`): первый документ исполнения; затем этапы, тесты, ревью, коммиты.',
53
+ '',
54
+ 'Три главных документа — `spec.md`, `concept.md`, `plan.md` — всегда актуальны:',
55
+ 'правки через `dept_amend`/`dept_section`, в панели они закреплены сверху.',
56
+ ].join('\n');
57
+ const fullBrief = brief !== '' ? `${brief}\n\n${process}\n` : `${process}\n`;
58
+ await mkdir(taskDir(root, taskId), { recursive: true });
59
+ await writeFile(join(taskDir(root, taskId), 'task.md'), fullBrief, 'utf8');
60
+ return writeState(root, state);
61
+ }
@@ -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
+ }