hermes-pilot 0.0.0-stage → 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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +419 -0
  3. package/README.md +428 -2
  4. package/__init__.py +15 -0
  5. package/apps/bridge/src/api-errors.js +165 -0
  6. package/apps/bridge/src/architect.js +1298 -0
  7. package/apps/bridge/src/auth.js +202 -0
  8. package/apps/bridge/src/capabilities.js +256 -0
  9. package/apps/bridge/src/capture.js +145 -0
  10. package/apps/bridge/src/chat-profile.js +95 -0
  11. package/apps/bridge/src/config.js +73 -0
  12. package/apps/bridge/src/discord.js +89 -0
  13. package/apps/bridge/src/gitinfo.js +211 -0
  14. package/apps/bridge/src/hermes.js +97 -0
  15. package/apps/bridge/src/inbox.js +347 -0
  16. package/apps/bridge/src/kanban.js +361 -0
  17. package/apps/bridge/src/lang.js +60 -0
  18. package/apps/bridge/src/live.js +285 -0
  19. package/apps/bridge/src/memos.js +150 -0
  20. package/apps/bridge/src/ops.js +201 -0
  21. package/apps/bridge/src/pair-codes.js +125 -0
  22. package/apps/bridge/src/pipeline-optimizer.js +513 -0
  23. package/apps/bridge/src/pipeline-watcher.js +1022 -0
  24. package/apps/bridge/src/qr.js +808 -0
  25. package/apps/bridge/src/repos.js +544 -0
  26. package/apps/bridge/src/review-watcher.js +271 -0
  27. package/apps/bridge/src/review.js +1749 -0
  28. package/apps/bridge/src/search.js +162 -0
  29. package/apps/bridge/src/server.js +1745 -0
  30. package/apps/bridge/src/snippets.js +373 -0
  31. package/apps/bridge/src/specs.js +806 -0
  32. package/apps/bridge/src/tail.js +28 -0
  33. package/apps/bridge/src/telemetry.js +667 -0
  34. package/apps/bridge/src/term-snippets.js +228 -0
  35. package/apps/bridge/src/transcript.js +231 -0
  36. package/apps/bridge/src/usage.js +294 -0
  37. package/apps/bridge/src/workerFeed.js +72 -0
  38. package/apps/dashboard/index.js +2014 -0
  39. package/apps/dashboard/manifest.json +14 -0
  40. package/apps/dashboard/pilot_dashboard.py +1466 -0
  41. package/apps/dashboard/plugin_api.py +237 -0
  42. package/apps/dashboard/plugin_init.py +15 -0
  43. package/apps/dashboard/style.css +928 -0
  44. package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
  45. package/apps/web/dist/assets/TermPane-q4f5Zu0I.js +12 -0
  46. package/apps/web/dist/assets/index-BzUof8lw.js +94 -0
  47. package/apps/web/dist/assets/index-DwZdbPU7.css +1 -0
  48. package/apps/web/dist/favicon.ico +0 -0
  49. package/apps/web/dist/icon-180-v6.png +0 -0
  50. package/apps/web/dist/icon-192-v6.png +0 -0
  51. package/apps/web/dist/icon-512-v6.png +0 -0
  52. package/apps/web/dist/icon-maskable-192-v6.png +0 -0
  53. package/apps/web/dist/icon-maskable-512-v6.png +0 -0
  54. package/apps/web/dist/icon-v6.svg +15 -0
  55. package/apps/web/dist/index.html +21 -0
  56. package/apps/web/dist/manifest.webmanifest +49 -0
  57. package/apps/web/dist/sw.js +69 -0
  58. package/bin/hermes-pilot.mjs +964 -0
  59. package/dashboard/dist/index.js +2014 -0
  60. package/dashboard/dist/style.css +928 -0
  61. package/dashboard/manifest.json +14 -0
  62. package/dashboard/pilot_dashboard.py +1466 -0
  63. package/dashboard/plugin_api.py +237 -0
  64. package/package.json +75 -4
  65. package/plugin.json +70 -0
  66. package/plugin.yaml +4 -0
  67. package/scripts/deploy.mjs +58 -0
  68. package/scripts/migrate-to-hermes-pilot.mjs +472 -0
  69. package/scripts/postinstall.mjs +32 -0
  70. package/scripts/sync-dashboard.mjs +98 -0
  71. package/skills/annotation/SKILL.md +138 -0
  72. package/skills/quick-review/SKILL.md +200 -0
  73. package/skills/quick-review/assets/sheet-template.html +175 -0
  74. package/skills/spec-architect/SKILL.md +226 -0
@@ -0,0 +1,347 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { DatabaseSync } from 'node:sqlite'
4
+ import { execFile } from 'node:child_process'
5
+ import { ApiError } from './api-errors.js'
6
+
7
+ /**
8
+ * 承認待ちインボックス。
9
+ *
10
+ * ボード横断で `status='blocked'` のタスクを集め、**エージェントからの質問を読んで
11
+ * コメントで答える**だけの画面を作る。ステータスは変えない(再開は Discord / ダッシュボード)。
12
+ *
13
+ * 読み取りは SQLite を readOnly、書き込み(コメント)は `hermes kanban comment` を CLI で実行する。
14
+ */
15
+
16
+ const TEXT_MAX = 2000
17
+
18
+ /** 閉じる操作。done=完了 / cancel=アーカイブ(一覧から外す)。 */
19
+ const CLOSE_ACTIONS = new Set(['done', 'cancel'])
20
+
21
+ /**
22
+ * ボードスラッグを検証する(DB パスに混ぜるので厳しめ)。
23
+ * @param {unknown} board 入力
24
+ * @returns {string} 検証済みスラッグ
25
+ */
26
+ function assertBoard(board) {
27
+ const slug = String(board ?? '')
28
+ if (!/^[a-z0-9][a-z0-9_-]{0,40}$/i.test(slug)) {
29
+ throw new ApiError('BOARD_NAME_INVALID', {}, 400)
30
+ }
31
+ return slug
32
+ }
33
+
34
+ /**
35
+ * タスクIDを検証する。
36
+ * @param {unknown} id 入力
37
+ * @returns {string} 検証済みID
38
+ */
39
+ function assertTaskId(id) {
40
+ const tid = String(id ?? '')
41
+ if (!/^t_[0-9a-z]+$/i.test(tid)) {
42
+ throw new ApiError('TASK_ID_INVALID', {}, 400)
43
+ }
44
+ return tid
45
+ }
46
+
47
+ /**
48
+ * コメント本文を検証する。
49
+ * @param {unknown} raw 入力
50
+ * @returns {string} 正規化済み本文
51
+ */
52
+ export function normalizeComment(raw) {
53
+ const body = String(raw ?? '').trim()
54
+ if (!body) throw new ApiError('COMMENT_REQUIRED', {}, 400)
55
+ if (body.length > TEXT_MAX) return body.slice(0, TEXT_MAX)
56
+ return body
57
+ }
58
+
59
+ export function createInbox(cfg, kanban) {
60
+ const boardsRoot = path.join(cfg.kanbanRoot, 'boards')
61
+
62
+ /**
63
+ * 1ボードの blocked タスク(理由・直近コメント付き)。
64
+ *
65
+ * **レビュー待ちは除く**(本文に `[review]` を持つ blocked)。レビューはレビュータブが受け持つ別の
66
+ * 待ち行列で、承認待ちの数字に混ぜると「同じ 1 件を 2 か所で数える」ことになる(実測: レビューの
67
+ * シート待ちが立っている間、承認待ちが 1 件から 3 件に増えていた)。レビュー待ちはコメントでは
68
+ * 答えられず、注釈シート / 回答フォームで答えるものなので、この一覧に出す意味も無い。
69
+ */
70
+ function boardItems(slug, name) {
71
+ const dbPath = path.join(boardsRoot, slug, 'kanban.db')
72
+ if (!fs.existsSync(dbPath)) return []
73
+ let db
74
+ try {
75
+ db = new DatabaseSync(dbPath, { readOnly: true })
76
+ const rows = db
77
+ .prepare(
78
+ `SELECT id, title, status, block_kind, block_recurrences, last_failure_error,
79
+ worker_pid, created_at, started_at, completed_at, session_id
80
+ FROM tasks
81
+ WHERE status = 'blocked'
82
+ AND COALESCE(body, '') NOT LIKE '%[review]%'
83
+ AND COALESCE(body, '') NOT LIKE '%[akapen]%'
84
+ ORDER BY COALESCE(completed_at, started_at, created_at) DESC
85
+ LIMIT 30`,
86
+ )
87
+ .all()
88
+ const commentStmt = db.prepare(
89
+ 'SELECT author, body, created_at FROM task_comments WHERE task_id = ? ORDER BY id DESC LIMIT 1',
90
+ )
91
+ const eventStmt = db.prepare(
92
+ `SELECT payload, created_at FROM task_events
93
+ WHERE task_id = ? AND kind IN ('blocked', 'failed', 'needs_input')
94
+ ORDER BY id DESC LIMIT 1`,
95
+ )
96
+ return rows.map((r) => {
97
+ let lastComment = null
98
+ let reason = r.last_failure_error ?? null
99
+ let blockedAt = null
100
+ try {
101
+ const c = commentStmt.get(r.id)
102
+ if (c) {
103
+ lastComment = {
104
+ author: c.author ?? '',
105
+ body: String(c.body ?? '').slice(0, 600),
106
+ at: Math.round(Number(c.created_at ?? 0) * 1000),
107
+ }
108
+ }
109
+ } catch {
110
+ /* noop */
111
+ }
112
+ try {
113
+ const e = eventStmt.get(r.id)
114
+ if (e) {
115
+ blockedAt = Math.round(Number(e.created_at ?? 0) * 1000)
116
+ try {
117
+ const p = JSON.parse(e.payload)
118
+ const msg = p?.message ?? p?.reason ?? p?.summary
119
+ if (typeof msg === 'string' && msg.trim()) reason = msg.trim()
120
+ } catch {
121
+ /* payload が JSON でない場合は無視 */
122
+ }
123
+ }
124
+ } catch {
125
+ /* noop */
126
+ }
127
+ return {
128
+ id: r.id,
129
+ title: r.title,
130
+ board: slug,
131
+ boardName: name,
132
+ status: r.status,
133
+ blockKind: r.block_kind ?? null,
134
+ recurrences: Number(r.block_recurrences ?? 0),
135
+ reason: reason ? String(reason).slice(0, 400) : null,
136
+ blockedAt: blockedAt ?? (r.completed_at ? Number(r.completed_at) * 1000 : null),
137
+ createdAt: r.created_at ? Number(r.created_at) * 1000 : null,
138
+ sessionId: r.session_id ?? null,
139
+ lastComment,
140
+ }
141
+ })
142
+ } catch {
143
+ return []
144
+ } finally {
145
+ try {
146
+ db?.close()
147
+ } catch {
148
+ /* noop */
149
+ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * 承認待ちの一覧(ボード横断)。
155
+ * @returns {{ok: boolean, at: number, items: Array<object>, counts: Record<string, number>}} 一覧
156
+ */
157
+ function list() {
158
+ const items = []
159
+ let boards = []
160
+ try {
161
+ boards = kanban.boards().filter((b) => !b.archived)
162
+ } catch {
163
+ boards = []
164
+ }
165
+ for (const b of boards) items.push(...boardItems(b.slug, b.name))
166
+ items.sort((a, b) => (b.blockedAt ?? 0) - (a.blockedAt ?? 0))
167
+ /** @type {Record<string, number>} */
168
+ const counts = {}
169
+ for (const it of items) counts[it.blockKind ?? 'untyped'] = (counts[it.blockKind ?? 'untyped'] ?? 0) + 1
170
+ return { ok: true, at: Date.now(), items, counts }
171
+ }
172
+
173
+ /**
174
+ * コメントを付ける(ステータスは変えない)。
175
+ * @param {string} board ボード
176
+ * @param {string} id タスクID
177
+ * @param {string} text 本文
178
+ * @param {string} by 実行者
179
+ * @returns {Promise<object>} 結果
180
+ */
181
+ async function comment(board, id, text, by = 'mobile') {
182
+ const body = normalizeComment(text)
183
+ if (!/^t_[0-9a-z]+$/i.test(String(id))) {
184
+ throw new ApiError('TASK_ID_INVALID', {}, 400)
185
+ }
186
+ const res = await run(cfg, ['kanban', '--board', board, 'comment', id, body, '--author', String(by).slice(0, 40)])
187
+ if (res.code !== 0) {
188
+ throw new ApiError('COMMENT_FAILED', {}, 502)
189
+ }
190
+ return { ok: true, id, output: res.out.slice(0, 400), at: Date.now() }
191
+ }
192
+
193
+ /** CLI 実行(runner で差し替え可)。 */
194
+ function run(c, args) {
195
+ if (c.runner) return c.runner(args)
196
+ return new Promise((resolve) => {
197
+ execFile(
198
+ c.hermesBin ?? 'hermes',
199
+ args,
200
+ { timeout: 20_000, maxBuffer: 500_000, env: { ...process.env } },
201
+ (err, stdout, stderr) => {
202
+ resolve({ code: err ? (err.code ?? 1) : 0, out: `${stdout ?? ''}${stderr ?? ''}`.trim() })
203
+ },
204
+ )
205
+ })
206
+ }
207
+
208
+ /** 1タスクの現在の status(読めなければ null)。 */
209
+ function statusOf(board, id) {
210
+ let db
211
+ try {
212
+ db = new DatabaseSync(path.join(boardsRoot, board, 'kanban.db'), { readOnly: true })
213
+ } catch {
214
+ return null
215
+ }
216
+ try {
217
+ const r = db.prepare('SELECT status FROM tasks WHERE id = ?').get(id)
218
+ return r?.status ?? null
219
+ } catch {
220
+ return null
221
+ } finally {
222
+ try {
223
+ db.close()
224
+ } catch {
225
+ /* noop */
226
+ }
227
+ }
228
+ }
229
+
230
+ /**
231
+ * 判断待ちを閉じる。
232
+ *
233
+ * `done` = 完了(result に理由を残す)/ `cancel` = アーカイブ(一覧から消える)。
234
+ * 既に閉じている場合は CLI を呼ばず `noop` を返す(連打しても二重に閉じない)。
235
+ *
236
+ * @param {string} board ボード
237
+ * @param {string} id タスクID
238
+ * @param {'done'|'cancel'} action 閉じ方
239
+ * @param {string} [note] 理由・結果(400字まで)
240
+ * @param {string} [by] 実行者
241
+ * @returns {Promise<object>} 結果
242
+ */
243
+ async function close(board, id, action, note = '', by = 'mobile') {
244
+ const b = assertBoard(board)
245
+ const tid = assertTaskId(id)
246
+ const act = String(action ?? '')
247
+ if (!CLOSE_ACTIONS.has(act)) {
248
+ throw new ApiError('ACTION_INVALID', { action: act }, 400)
249
+ }
250
+ const before = statusOf(b, tid)
251
+ if (before == null) {
252
+ throw new ApiError('TASK_NOT_FOUND', {}, 404)
253
+ }
254
+ const actor = String(by ?? 'mobile').slice(0, 40)
255
+ const text = String(note ?? '').trim().slice(0, 400)
256
+ if (act === 'done' && before === 'done') {
257
+ return { ok: true, board: b, id: tid, action: act, status: before, noop: true, at: Date.now() }
258
+ }
259
+ if (act === 'cancel' && before === 'archived') {
260
+ return { ok: true, board: b, id: tid, action: act, status: before, noop: true, at: Date.now() }
261
+ }
262
+
263
+ // 取消は理由の欄が無いので、先にコメントで残す(失敗しても取消は続ける)
264
+ if (act === 'cancel') {
265
+ await run(cfg, [
266
+ 'kanban', '--board', b, 'comment', tid,
267
+ `PWAから取消(アーカイブ)${text ? `: ${text}` : ''}`,
268
+ '--author', actor,
269
+ ])
270
+ }
271
+
272
+ const args =
273
+ act === 'done'
274
+ ? [
275
+ 'kanban', '--board', b, 'complete', tid,
276
+ '--result', text || 'PWAから完了(追加作業なし)',
277
+ '--metadata', JSON.stringify({ closed_from: 'mobile', closed_by: actor, closed_at: new Date().toISOString() }),
278
+ ]
279
+ : ['kanban', '--board', b, 'archive', tid]
280
+ const res = await run(cfg, args)
281
+ if (res.code !== 0) {
282
+ throw new ApiError('CLI_FAILED', {}, 502)
283
+ }
284
+ const after = statusOf(b, tid)
285
+ return {
286
+ ok: true,
287
+ board: b,
288
+ id: tid,
289
+ action: act,
290
+ status: after ?? null,
291
+ changed: after !== before,
292
+ output: res.out.slice(0, 400),
293
+ at: Date.now(),
294
+ }
295
+ }
296
+
297
+ /**
298
+ * blocked のタスクを再開(ready へ戻す)。
299
+ * 下書きコメントがあれば先に記録してから unblock する。
300
+ * @param {string} board ボード
301
+ * @param {string} id タスクID
302
+ * @param {string} [note] コメント/理由(400字まで)
303
+ * @param {string} [by] 実行者
304
+ * @returns {Promise<object>} 結果
305
+ */
306
+ async function unblock(board, id, note = '', by = 'mobile') {
307
+ const b = assertBoard(board)
308
+ const tid = assertTaskId(id)
309
+ const before = statusOf(b, tid)
310
+ if (before == null) {
311
+ throw new ApiError('TASK_NOT_FOUND', {}, 404)
312
+ }
313
+ if (before === 'ready' || before === 'running') {
314
+ return { ok: true, board: b, id: tid, status: before, noop: true, at: Date.now() }
315
+ }
316
+ if (before !== 'blocked') {
317
+ throw new ApiError('TASK_STATE_LOCKED', { status: before }, 409)
318
+ }
319
+ const actor = String(by ?? 'mobile').slice(0, 40)
320
+ const text = String(note ?? '').trim().slice(0, 400)
321
+ if (text) {
322
+ const cRes = await run(cfg, ['kanban', '--board', b, 'comment', tid, text, '--author', actor])
323
+ if (cRes.code !== 0) {
324
+ throw new ApiError('COMMENT_FAILED', {}, 502)
325
+ }
326
+ }
327
+ const res = await run(cfg, [
328
+ 'kanban', '--board', b, 'unblock', tid,
329
+ '--reason', text || 'PWAから再開',
330
+ ])
331
+ if (res.code !== 0) {
332
+ throw new ApiError('CLI_FAILED', {}, 502)
333
+ }
334
+ const after = statusOf(b, tid)
335
+ return {
336
+ ok: true,
337
+ board: b,
338
+ id: tid,
339
+ status: after ?? null,
340
+ changed: after !== before,
341
+ output: res.out.slice(0, 400),
342
+ at: Date.now(),
343
+ }
344
+ }
345
+
346
+ return { list, comment, close, unblock }
347
+ }
@@ -0,0 +1,361 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { execFile } from 'node:child_process'
4
+ import { DatabaseSync } from 'node:sqlite'
5
+ import { ApiError } from './api-errors.js'
6
+
7
+ /**
8
+ * カンバン(SQLite)の読み取りと、実行中タスクの中断。
9
+ *
10
+ * 読み取りは**読み取り専用**で開く(WAL なので運用中の読み取りは安全)。
11
+ * 中断は正規コマンド `hermes kanban reclaim` → `block` を使う(生の kill はしない)。
12
+ *
13
+ * @param {object} cfg 設定
14
+ * @returns {object} カンバン操作
15
+ */
16
+ export function createKanban(cfg) {
17
+ const boardsRoot = path.join(cfg.kanbanRoot, 'boards')
18
+ const defaultDb = cfg.kanbanDb
19
+
20
+ /**
21
+ * ボード一覧(board.json + 件数)。
22
+ * @returns {Array<{slug: string, name: string, icon?: string, archived: boolean, workdir?: string, counts: Record<string, number>}>} 一覧
23
+ */
24
+ function boards() {
25
+ let dirs = []
26
+ try {
27
+ dirs = fs.readdirSync(boardsRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name)
28
+ } catch {
29
+ return []
30
+ }
31
+ let current = ''
32
+ try {
33
+ current = fs.readFileSync(path.join(cfg.kanbanRoot, 'current'), 'utf8').trim()
34
+ } catch {
35
+ current = ''
36
+ }
37
+ const out = []
38
+ for (const slug of dirs) {
39
+ const dir = path.join(boardsRoot, slug)
40
+ let meta = {}
41
+ try {
42
+ meta = JSON.parse(fs.readFileSync(path.join(dir, 'board.json'), 'utf8'))
43
+ } catch {
44
+ meta = { slug, name: slug }
45
+ }
46
+ const db = path.join(dir, 'kanban.db')
47
+ let counts = {}
48
+ let lastActivityAt = null
49
+ if (fs.existsSync(db)) {
50
+ const info = countsFor(db)
51
+ counts = info.counts
52
+ lastActivityAt = info.lastActivityAt
53
+ }
54
+ out.push({
55
+ slug,
56
+ name: meta.name ?? slug,
57
+ icon: meta.icon ?? '📋',
58
+ archived: Boolean(meta.archived),
59
+ workdir: meta.default_workdir ?? null,
60
+ current: slug === current,
61
+ counts,
62
+ lastActivityAt,
63
+ })
64
+ }
65
+ // 並び順: アーカイブでない → **最終活動が新しい順** → 実行中 → 現在のボード → 名前
66
+ // 「current」を先頭に固定すると並び順の規則が見えなくなるので、同着時の優先に留める
67
+ return out.sort(
68
+ (a, b) =>
69
+ Number(a.archived) - Number(b.archived) ||
70
+ Number(b.lastActivityAt ?? 0) - Number(a.lastActivityAt ?? 0) ||
71
+ Number(b.counts?.running ?? 0) - Number(a.counts?.running ?? 0) ||
72
+ Number(b.current) - Number(a.current) ||
73
+ a.name.localeCompare(b.name),
74
+ )
75
+ }
76
+
77
+ /**
78
+ * ステータス別件数と最終活動時刻。
79
+ * 最終活動は tasks の completed_at / started_at / created_at の最大(epoch 秒)。
80
+ */
81
+ function countsFor(dbPath) {
82
+ let db
83
+ try {
84
+ db = new DatabaseSync(dbPath, { readOnly: true })
85
+ const rows = db.prepare('SELECT status, COUNT(*) AS n FROM tasks GROUP BY status').all()
86
+ /** @type {Record<string, number>} */
87
+ const counts = {}
88
+ for (const r of rows) counts[String(r.status)] = Number(r.n)
89
+ let lastActivityAt = null
90
+ try {
91
+ const t = db
92
+ .prepare('SELECT MAX(COALESCE(completed_at, started_at, created_at)) AS t FROM tasks')
93
+ .get()
94
+ if (t && t.t != null) lastActivityAt = Number(t.t)
95
+ } catch {
96
+ /* tasks が無い板 */
97
+ }
98
+ return { counts, lastActivityAt }
99
+ } catch {
100
+ return { counts: {}, lastActivityAt: null }
101
+ } finally {
102
+ try {
103
+ db?.close()
104
+ } catch {
105
+ /* noop */
106
+ }
107
+ }
108
+ }
109
+
110
+ /** ボードの DB パス(旧: 単一 kanban.db のボードも拾う)。 */
111
+ function dbFor(slug) {
112
+ const p = path.join(boardsRoot, slug, 'kanban.db')
113
+ if (fs.existsSync(p)) return p
114
+ if (fs.existsSync(defaultDb)) return defaultDb
115
+ throw new ApiError('BOARD_NOT_FOUND', { board: slug }, 404)
116
+ }
117
+
118
+ /**
119
+ * タスク一覧(更新の新しい順)。
120
+ *
121
+ * `body` は Architect の `findJobReviewTask` が `[review]` の本文を読むために要る
122
+ * (SPEC V7 §3.1①)。重い一覧(PWA のタスク一覧)だけは `withBody: false` で落とせる。
123
+ *
124
+ * @param {string} slug ボード
125
+ * @param {{limit?: number, statuses?: string[], withBody?: boolean}} [opts] オプション
126
+ * @returns {Array<object>} タスク
127
+ */
128
+ function tasks(slug, opts = {}) {
129
+ const limit = Math.min(Number(opts.limit ?? 60), 200)
130
+ const withBody = opts.withBody !== false
131
+ const db = new DatabaseSync(dbFor(slug), { readOnly: true })
132
+ try {
133
+ // 古い板の `tasks` に `body` 列が無くても落とさない(無ければ空文字)
134
+ const bodyCol = hasColumn(db, 'tasks', 'body') ? 'body' : "'' AS body"
135
+ const rows = db
136
+ .prepare(
137
+ `SELECT id, title, ${bodyCol}, status, priority, assignee, created_at, started_at, completed_at,
138
+ workspace_path, branch_name, worker_pid, last_heartbeat_at, result,
139
+ consecutive_failures, session_id, current_step_key
140
+ FROM tasks
141
+ ORDER BY COALESCE(completed_at, started_at, created_at) DESC
142
+ LIMIT ?`,
143
+ )
144
+ .all(limit)
145
+ return rows.map((r) => {
146
+ const row = {
147
+ id: r.id,
148
+ title: r.title,
149
+ status: r.status,
150
+ priority: Number(r.priority ?? 0),
151
+ assignee: r.assignee,
152
+ createdAt: Number(r.created_at ?? 0) * 1000,
153
+ startedAt: r.started_at ? Number(r.started_at) * 1000 : null,
154
+ completedAt: r.completed_at ? Number(r.completed_at) * 1000 : null,
155
+ workspace: r.workspace_path,
156
+ branch: r.branch_name,
157
+ running: r.status === 'running',
158
+ workerPid: r.worker_pid ?? null,
159
+ elapsedSec: r.started_at ? Math.max(0, Math.round(Date.now() / 1000 - Number(r.started_at))) : null,
160
+ result: r.result ? String(r.result).slice(0, 400) : null,
161
+ failures: Number(r.consecutive_failures ?? 0),
162
+ sessionId: r.session_id ?? null,
163
+ }
164
+ if (withBody) row.body = r.body == null ? '' : String(r.body)
165
+ return row
166
+ })
167
+ } finally {
168
+ db.close()
169
+ }
170
+ }
171
+
172
+ /**
173
+ * 実行ワーカーのセッションと、その会話が入っている state.db を引く。
174
+ *
175
+ * `tasks.session_id` は `complete --force` などで空になるので、`task_events` の
176
+ * `owner_admitted` / `worker_bound` / `spawned` の payload も見る。`db` はイベントにしか
177
+ * 残らない(どのプロファイルの state.db か)ため、session_id がタスク行にあっても
178
+ * イベントを読む。
179
+ *
180
+ * @param {import('node:sqlite').DatabaseSync} db ボードの DB(開いているもの)
181
+ * @param {string} id タスク ID
182
+ * @returns {{sessionId: string, db: string|null}|null} 見つからなければ null
183
+ */
184
+ function resolveSessionInfoIn(db, id) {
185
+ let sessionId = null
186
+ try {
187
+ const r = db.prepare('SELECT session_id FROM tasks WHERE id = ?').get(id)
188
+ if (r?.session_id) sessionId = String(r.session_id)
189
+ } catch {
190
+ /* 古い板に session_id 列が無い */
191
+ }
192
+ let dbPath = null
193
+ for (const ev of safeAll(
194
+ db,
195
+ `SELECT payload FROM task_events WHERE task_id = ?
196
+ AND kind IN ('owner_admitted','worker_bound','spawned') ORDER BY id DESC LIMIT 8`,
197
+ id,
198
+ )) {
199
+ const p = safeJson(ev?.payload)
200
+ if (!p || typeof p !== 'object') continue
201
+ if (!sessionId && p.session_id) sessionId = String(p.session_id)
202
+ if (!dbPath && p.db) dbPath = String(p.db)
203
+ if (sessionId && dbPath) break
204
+ }
205
+ return sessionId ? { sessionId, db: dbPath } : null
206
+ }
207
+
208
+ /**
209
+ * 実行ワーカーのセッション情報(ボードを指定して引く)。
210
+ * @param {string} slug ボード
211
+ * @param {string} id タスク ID
212
+ * @returns {{sessionId: string, db: string|null}|null} 見つからなければ null
213
+ */
214
+ function taskSession(slug, id) {
215
+ let db
216
+ try {
217
+ db = new DatabaseSync(dbFor(slug), { readOnly: true })
218
+ } catch {
219
+ return null
220
+ }
221
+ try {
222
+ return resolveSessionInfoIn(db, id)
223
+ } finally {
224
+ db.close()
225
+ }
226
+ }
227
+
228
+ /**
229
+ * タスク詳細(イベント・実行履歴・コメント付き)。
230
+ * @param {string} slug ボード
231
+ * @param {string} id タスク ID
232
+ * @returns {object} 詳細
233
+ */
234
+ function task(slug, id) {
235
+ const db = new DatabaseSync(dbFor(slug), { readOnly: true })
236
+ try {
237
+ const row = db.prepare('SELECT * FROM tasks WHERE id = ?').get(id)
238
+ if (!row) throw new ApiError('TASK_NOT_FOUND', { id }, 404)
239
+ const events = safeAll(
240
+ db,
241
+ `SELECT kind, payload, created_at FROM task_events WHERE task_id = ? ORDER BY id DESC LIMIT 40`,
242
+ id,
243
+ ).map((e) => ({
244
+ kind: e.kind,
245
+ at: Number(e.created_at) * 1000,
246
+ payload: safeJson(e.payload),
247
+ }))
248
+ const runs = safeAll(
249
+ db,
250
+ `SELECT id, status, started_at, ended_at, exit_code FROM task_runs WHERE task_id = ? ORDER BY id DESC LIMIT 10`,
251
+ id,
252
+ ).map((r) => ({
253
+ id: r.id,
254
+ status: r.status,
255
+ startedAt: r.started_at ? Number(r.started_at) * 1000 : null,
256
+ endedAt: r.ended_at ? Number(r.ended_at) * 1000 : null,
257
+ }))
258
+ const comments = safeAll(
259
+ db,
260
+ `SELECT author, body, created_at FROM task_comments WHERE task_id = ? ORDER BY id DESC LIMIT 10`,
261
+ id,
262
+ ).map((c) => ({ author: c.author, body: c.body, at: Number(c.created_at) * 1000 }))
263
+ // 実行ワーカーのライブ進捗(`<WorkerFeed>`)は sessionId がある時だけ出す
264
+ const session = resolveSessionInfoIn(db, id)
265
+ return {
266
+ id: row.id,
267
+ title: row.title,
268
+ body: row.body,
269
+ status: row.status,
270
+ assignee: row.assignee,
271
+ priority: Number(row.priority ?? 0),
272
+ workspace: row.workspace_path,
273
+ branch: row.branch_name,
274
+ workerPid: row.worker_pid ?? null,
275
+ sessionId: session?.sessionId ?? null,
276
+ startedAt: row.started_at ? Number(row.started_at) * 1000 : null,
277
+ completedAt: row.completed_at ? Number(row.completed_at) * 1000 : null,
278
+ result: row.result,
279
+ failures: Number(row.consecutive_failures ?? 0),
280
+ events,
281
+ runs,
282
+ comments,
283
+ }
284
+ } finally {
285
+ db.close()
286
+ }
287
+ }
288
+
289
+ /**
290
+ * 実行中タスクを中断する(reclaim で worker を終了 → block で再実行を止める)。
291
+ * @param {string} slug ボード
292
+ * @param {string} id タスク ID
293
+ * @param {string} reason 理由(監査・イベントに残る)
294
+ * @returns {Promise<{ok: boolean, reclaimed: boolean, blocked: boolean, output: string}>} 結果
295
+ */
296
+ async function abort(slug, id, reason = 'mobile kill switch') {
297
+ const detail = task(slug, id)
298
+ if (detail.status !== 'running' && !detail.workerPid) {
299
+ throw new ApiError('TASK_STATE_LOCKED', { status: detail.status }, 409)
300
+ }
301
+ const reclaim = await runKanban(slug, ['reclaim', id, '--reason', reason])
302
+ const block = await runKanban(slug, ['block', id, `モバイルから中断: ${reason}`, '--kind', 'needs_input'])
303
+ return {
304
+ ok: reclaim.code === 0,
305
+ reclaimed: reclaim.code === 0,
306
+ blocked: block.code === 0,
307
+ workerPid: detail.workerPid,
308
+ output: `${reclaim.out}\n${block.out}`.trim().slice(0, 800),
309
+ }
310
+ }
311
+
312
+ /** `hermes kanban` を実行する(シェルを介さない)。 */
313
+ function runKanban(slug, args) {
314
+ return new Promise((resolve) => {
315
+ execFile(
316
+ 'hermes',
317
+ ['--board', slug, 'kanban', ...args],
318
+ { timeout: 30000, maxBuffer: 1_000_000, env: { ...process.env } },
319
+ (err, stdout, stderr) => {
320
+ resolve({ code: err ? (err.code ?? 1) : 0, out: `${stdout ?? ''}${stderr ?? ''}`.trim() })
321
+ },
322
+ )
323
+ })
324
+ }
325
+
326
+ function safeAll(db, sql, arg) {
327
+ try {
328
+ return db.prepare(sql).all(arg)
329
+ } catch {
330
+ return []
331
+ }
332
+ }
333
+
334
+ /**
335
+ * テーブルに列があるか(板のスキーマ版差を吸収する)。
336
+ * @param {import('node:sqlite').DatabaseSync} db DB
337
+ * @param {string} table テーブル名
338
+ * @param {string} column 列名
339
+ * @returns {boolean} あれば true
340
+ */
341
+ function hasColumn(db, table, column) {
342
+ try {
343
+ return db
344
+ .prepare(`PRAGMA table_info(${table})`)
345
+ .all()
346
+ .some((c) => String(c?.name ?? '') === column)
347
+ } catch {
348
+ return false
349
+ }
350
+ }
351
+
352
+ function safeJson(v) {
353
+ try {
354
+ return JSON.parse(v)
355
+ } catch {
356
+ return v
357
+ }
358
+ }
359
+
360
+ return { boards, tasks, task, taskSession, abort }
361
+ }