hermes-pilot 0.0.0-stage → 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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +390 -0
  3. package/README.md +398 -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 +358 -0
  23. package/apps/bridge/src/pipeline-watcher.js +1018 -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 +1738 -0
  30. package/apps/bridge/src/snippets.js +373 -0
  31. package/apps/bridge/src/specs.js +734 -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-U500JD2P.js +12 -0
  46. package/apps/web/dist/assets/index-6iFDsB0G.css +1 -0
  47. package/apps/web/dist/assets/index-X4Bi2FWB.js +94 -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 +103 -0
  72. package/skills/quick-review/SKILL.md +170 -0
  73. package/skills/quick-review/assets/sheet-template.html +175 -0
  74. package/skills/spec-architect/SKILL.md +175 -0
@@ -0,0 +1,734 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { execFile } from 'node:child_process'
4
+ import { ApiError } from './api-errors.js'
5
+ import { buildAugmentedPath, resolveHermesBin } from './capabilities.js'
6
+
7
+ /**
8
+ * Spec Launchpad — `docs/SPEC-*.md` を検出し、バッチ見出しをカンバンへ一括起票する。
9
+ *
10
+ * 読み取りは**プレーンなファイル走査だけ**(カンバン DB は触らない)。起票は
11
+ * 正規コマンド `hermes kanban create` を実行する(カンバン DB に直接書かない。
12
+ * 盤面のロック・イベント・通知の整合性は本体に任せる)。
13
+ *
14
+ * 冪等性: 同じボードに `[<BatchID>]` で始まる**未完了**タスクがあれば起票しない。
15
+ * 二重タップ・再読み込み・再起動で同じバッチが積み上がらないようにするための規則。
16
+ */
17
+
18
+ /** 走査するディレクトリ(リポジトリ直下と `docs/`)。 */
19
+ export const SPEC_DIRS = ['docs', '']
20
+
21
+ /** ファイル名の規則(`SPEC*.md`。大文字小文字は問わない)。 */
22
+ export const SPEC_FILE_RE = /^SPEC.*\.md$/i
23
+
24
+ /** バッチ ID の規則(英字始まり・16 文字まで)。`### 1.1 見出し` のような番号見出しを拾わない。 */
25
+ export const BATCH_ID_RE = /^[A-Za-z][A-Za-z0-9._-]{0,15}$/
26
+
27
+ /** 完了してよい状態(これ以外を「未完了」とみなして重複起票を止める)。 */
28
+ export const CLOSED_STATUSES = new Set(['done', 'archived'])
29
+
30
+ /** タスク本文の上限(カンバン側の実用上限に合わせる)。 */
31
+ export const BODY_MAX = 6000
32
+
33
+ /**
34
+ * 起票元チャット ID の書式(`Chat:` 行に載せる値)。
35
+ * セッション ID・`local-…`・`__latest__` を通しつつ、改行や空白は弾く(本文を壊さない)。
36
+ */
37
+ export const SPEC_CHAT_RE = /^[A-Za-z0-9_.:-]{1,128}$/
38
+
39
+ /** `pipeline-runs.json` に保持するランの上限(古い完了分から剪定する)。 */
40
+ export const RUNS_MAX = 50
41
+
42
+ /** `### Batch <ID>: <Title>` / `### <ID>: <Title>`。 */
43
+ const BATCH_HEADING_RE = /^###\s+(?:Batch\s+)?([A-Za-z][A-Za-z0-9._-]{0,15})\s*[::]\s*(.+?)\s*$/
44
+
45
+ /** セクションの終わり(レベル 1〜3 の見出し。`####` はバッチ内の小見出しなので含める)。 */
46
+ const SECTION_END_RE = /^#{1,3}\s/
47
+
48
+ /** 目的の行(`- **目的**: …` / `**Objective**: …`)。 */
49
+ const OBJECTIVE_RE = /^[-*]?\s*\*\*\s*(?:目的|Objective)\s*\*\*\s*[::]\s*(.+)$/i
50
+
51
+ /**
52
+ * 実行モード宣言の行(`- **Execution Mode**: `[Mode: Zero-Stop]`` / `- **実行モード**: [Mode: …]`)。
53
+ * バックティック・角括弧・`Mode:` 前置・大小文字をすべて許容する。
54
+ */
55
+ export const EXECUTION_MODE_RE =
56
+ /^[-*]?\s*\*\*\s*(?:Execution\s*Mode|実行モード)\s*\*\*\s*[::]\s*[`\s]*\[?\s*(?:Mode\s*[::]\s*)?(Zero-Stop|Fast-Track\s*Review|Visual\s*Gate)/im
57
+
58
+ /** 正規化した実行モード(`batch.mode` に入る値)。 */
59
+ export const EXECUTION_MODES = ['zero-stop', 'fast-track-review', 'visual-gate']
60
+
61
+ /**
62
+ * 実行モード表記を正規化する(未知の値・未宣言は `null`)。
63
+ *
64
+ * @param {unknown} raw `Zero-Stop` / `[Mode: Visual Gate]` / `visual-gate` など
65
+ * @returns {'zero-stop'|'fast-track-review'|'visual-gate'|null} 正規化したモード
66
+ */
67
+ export function normalizeExecutionMode(raw) {
68
+ const s = String(raw ?? '')
69
+ .toLowerCase()
70
+ // `[Mode: Visual Gate]` のような生の宣言もそのまま受けられるように前置を落とす
71
+ .replace(/mode\s*[::]/g, ' ')
72
+ .replace(/[^a-z-]+/g, '-')
73
+ .replace(/-+/g, '-')
74
+ .replace(/^-|-$/g, '')
75
+ if (!s) return null
76
+ if (s === 'zero-stop' || s === 'zerostop' || s === 'zero') return 'zero-stop'
77
+ if (s === 'fast-track-review' || s === 'fast-track' || s === 'fasttrack-review') return 'fast-track-review'
78
+ if (s === 'visual-gate' || s === 'visualgate' || s === 'visual') return 'visual-gate'
79
+ return null
80
+ }
81
+
82
+ /**
83
+ * バッチ本文から実行モードを読む(未宣言は `null`=後方互換)。
84
+ *
85
+ * @param {string[]|string} section バッチ本文の行(または本文)
86
+ * @returns {'zero-stop'|'fast-track-review'|'visual-gate'|null} モード
87
+ */
88
+ export function extractExecutionMode(section) {
89
+ const text = Array.isArray(section) ? section.join('\n') : String(section ?? '')
90
+ const m = EXECUTION_MODE_RE.exec(text)
91
+ return m ? normalizeExecutionMode(m[1]) : null
92
+ }
93
+
94
+ /** 行動契約ブロックの見出し(本文中で一意)。 */
95
+ export const CONTRACT_HEADER = '[Hermes Pilot Execution Contract]'
96
+
97
+ /** モード別の行動契約(`buildTaskBody` が本文末尾へ注入する)。 */
98
+ export const MODE_CONTRACTS = {
99
+ 'zero-stop': [
100
+ '- Do not ask confirmation questions in chat.',
101
+ '- Repair autonomously until `npm run verify` (tests, build, checks) passes, then mark the task done.',
102
+ '- Only when a design contradiction is unresolvable, file a `quick-review` sheet and block on it.',
103
+ ],
104
+ 'fast-track-review': [
105
+ '- If the change forces a choice between options, file a `quick-review` sheet (each question with `recommended: true`) before implementing, and wait for the 1-tap approval.',
106
+ '- Everything else proceeds without asking: implement, run `npm run verify`, then mark the task done.',
107
+ ],
108
+ 'visual-gate': [
109
+ '- After implementing, run `npm run deploy` and verify the real screen at `390×844` and `820×1180`; capture the screenshots.',
110
+ '- If the rendered result differs from the intent, file an `annotation` review (screenshot + marks) and wait for it.',
111
+ '- `npm run verify` must pass before you mark the task done.',
112
+ ],
113
+ }
114
+
115
+ /**
116
+ * モード別の行動契約ブロック(`[Hermes Pilot Execution Contract]`)を組み立てる。
117
+ *
118
+ * @param {string} mode 正規化済みモード
119
+ * @returns {string} 本文末尾に足すブロック(未知モードは空文字)
120
+ */
121
+ export function buildExecutionContract(mode) {
122
+ const key = normalizeExecutionMode(mode)
123
+ if (!key) return ''
124
+ const rules = MODE_CONTRACTS[key] ?? []
125
+ return [
126
+ '',
127
+ CONTRACT_HEADER,
128
+ '',
129
+ `Mode: ${key}`,
130
+ '',
131
+ 'This task was filed by the Hermes Pilot Spec Launchpad. The contract below overrides any habit of asking first.',
132
+ ...rules,
133
+ '- Finish with a short report: what changed, the verification command and its exit code, and what is still unverified.',
134
+ ].join('\n')
135
+ }
136
+
137
+ /** タイトル行(`# …`)。 */
138
+ const TITLE_RE = /^#\s+(.+?)\s*$/
139
+
140
+ /**
141
+ * 仕様書 1 枚を解析してタイトルとバッチを返す(純粋関数)。
142
+ *
143
+ * @param {string} text Markdown
144
+ * @returns {{title: string, batches: Array<{id: string, title: string, objective: string, section: string}>, valid: boolean}} 解析結果
145
+ */
146
+ export function parseSpec(text) {
147
+ const lines = String(text ?? '').split(/\r?\n/)
148
+ let title = ''
149
+ for (const line of lines) {
150
+ const m = TITLE_RE.exec(line)
151
+ if (m) {
152
+ title = m[1]
153
+ break
154
+ }
155
+ }
156
+
157
+ /** @type {Array<{id: string, title: string, objective: string, section: string}>} */
158
+ const batches = []
159
+ for (let i = 0; i < lines.length; i += 1) {
160
+ const m = BATCH_HEADING_RE.exec(lines[i])
161
+ if (!m || !BATCH_ID_RE.test(m[1])) continue
162
+ // 同じ ID が 2 回出たら最初のものを採る(目次・参照の重複見出し対策)
163
+ if (batches.some((b) => b.id === m[1])) continue
164
+ let end = lines.length
165
+ for (let j = i + 1; j < lines.length; j += 1) {
166
+ if (SECTION_END_RE.test(lines[j])) {
167
+ end = j
168
+ break
169
+ }
170
+ }
171
+ const body = lines.slice(i + 1, end)
172
+ batches.push({
173
+ id: m[1],
174
+ title: m[2].trim(),
175
+ objective: extractObjective(body),
176
+ // 実行モード(未宣言の過去 SPEC は null=後方互換)
177
+ mode: extractExecutionMode(body),
178
+ // 末尾の区切り線(`---`)は本文に含めない
179
+ section: trimTrailingRule(body.join('\n')),
180
+ })
181
+ }
182
+
183
+ return { title, batches, valid: Boolean(title) || batches.length > 0 }
184
+ }
185
+
186
+ /**
187
+ * 抜粋から「目的」だけ取り出す。無ければ最初の意味のある行。
188
+ * @param {string[]} lines セクションの行
189
+ * @returns {string} 目的(無ければ空文字)
190
+ */
191
+ function extractObjective(lines) {
192
+ for (const line of lines) {
193
+ const m = OBJECTIVE_RE.exec(line)
194
+ if (m) return m[1].trim()
195
+ }
196
+ for (const line of lines) {
197
+ const t = line.trim()
198
+ if (!t || t.startsWith('#') || t.startsWith('|') || t === '---') continue
199
+ return t.replace(/^[-*]\s*/, '').slice(0, 200)
200
+ }
201
+ return ''
202
+ }
203
+
204
+ /**
205
+ * 末尾の区切り線と空行を落とす。
206
+ * @param {string} text 本文
207
+ * @returns {string} 整形後
208
+ */
209
+ function trimTrailingRule(text) {
210
+ const lines = String(text ?? '').split('\n')
211
+ while (lines.length && (/^\s*$/.test(lines[lines.length - 1]) || /^\s*-{3,}\s*$/.test(lines[lines.length - 1]))) {
212
+ lines.pop()
213
+ }
214
+ return lines.join('\n').trim()
215
+ }
216
+
217
+ /**
218
+ * リポジトリ内の SPEC を走査する。
219
+ *
220
+ * @param {string} repoPath リポジトリの絶対パス
221
+ * @param {{readdir?: Function, stat?: Function, read?: Function}} [deps] 差し替え(テスト用)
222
+ * @returns {Array<{path: string, title: string, mtime: number, batches: Array<object>, valid: boolean}>} mtime の新しい順
223
+ */
224
+ export function listSpecs(repoPath, deps = {}) {
225
+ const readdir = deps.readdir ?? ((dir) => fs.readdirSync(dir))
226
+ const stat = deps.stat ?? ((file) => fs.statSync(file))
227
+ const read = deps.read ?? ((file) => fs.readFileSync(file, 'utf8'))
228
+ const root = path.resolve(String(repoPath ?? ''))
229
+ if (!root) return []
230
+
231
+ const out = []
232
+ const seen = new Set()
233
+ for (const dir of SPEC_DIRS) {
234
+ const abs = dir ? path.join(root, dir) : root
235
+ let names = []
236
+ try {
237
+ names = readdir(abs)
238
+ } catch {
239
+ continue
240
+ }
241
+ for (const name of names) {
242
+ if (!SPEC_FILE_RE.test(name)) continue
243
+ const file = path.join(abs, name)
244
+ let st
245
+ try {
246
+ st = stat(file)
247
+ } catch {
248
+ continue
249
+ }
250
+ // ディレクトリ(`SPEC-dir.md/` のような変な名前)は無視する
251
+ if (typeof st?.isFile === 'function' && !st.isFile()) continue
252
+ const rel = path.relative(root, file).split(path.sep).join('/')
253
+ if (seen.has(rel)) continue
254
+ let text = ''
255
+ try {
256
+ text = String(read(file))
257
+ } catch {
258
+ continue
259
+ }
260
+ const parsed = parseSpec(text)
261
+ seen.add(rel)
262
+ out.push({
263
+ path: rel,
264
+ title: parsed.title || name.replace(/\.md$/i, ''),
265
+ mtime: Number(st?.mtimeMs ?? st?.mtime ?? 0),
266
+ batches: parsed.batches,
267
+ valid: parsed.valid,
268
+ })
269
+ }
270
+ }
271
+
272
+ return out.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path))
273
+ }
274
+
275
+ /**
276
+ * 起票するタスクのタイトル(`[<BatchID>] <BatchTitle>`)。
277
+ * @param {{id: string, title: string}} batch バッチ
278
+ * @returns {string} タイトル
279
+ */
280
+ export function buildTaskTitle(batch) {
281
+ return `[${batch?.id ?? ''}] ${batch?.title ?? ''}`.trim().slice(0, 200)
282
+ }
283
+
284
+ /**
285
+ * 起票するタスクの本文(spec パス・target・抜粋・受入条件)。
286
+ *
287
+ * @param {{specRelPath: string, repoPath: string, board: string, batch: {id: string, title: string, objective: string, section: string}, chat?: string}} input 入力
288
+ * @returns {string} 本文
289
+ */
290
+ export function buildTaskBody({ specRelPath, repoPath, board, batch, chat }) {
291
+ const chatId = sanitizeSpecChat(chat)
292
+ const mode = normalizeExecutionMode(batch?.mode)
293
+ const head = [
294
+ `Spec: ${specRelPath}`,
295
+ `Target: ${repoPath}`,
296
+ `Board: ${board}`,
297
+ `Batch: ${batch?.id ?? ''} — ${batch?.title ?? ''}`,
298
+ ...(chatId ? [`Chat: ${chatId}`] : []),
299
+ ...(mode ? [`Mode: ${mode}`] : []),
300
+ '',
301
+ '## 目的',
302
+ '',
303
+ batch?.objective || '(バッチ本文の抜粋を参照)',
304
+ '',
305
+ '## 抜粋(受入条件 / Verify を含む)',
306
+ '',
307
+ ].join('\n')
308
+ // 契約ブロックは**末尾に必ず残す**(抜粋だけを切り詰める)。6000 字上限で契約が消えると
309
+ // 自走の保証が壊れるため、順序は「見出し → 抜粋 → 契約」で固定する。
310
+ const contract = buildExecutionContract(mode)
311
+ const room = Math.max(0, BODY_MAX - head.length - contract.length)
312
+ const section = String(batch?.section ?? '').slice(0, room)
313
+ return `${head}${section}${contract}`.slice(0, BODY_MAX)
314
+ }
315
+
316
+ /**
317
+ * 既存タスクの中に同じバッチの未完了タスクがあるか。
318
+ *
319
+ * @param {Array<{title?: string, status?: string, id?: string}>} tasks 同じボードのタスク
320
+ * @param {string} batchId バッチ ID
321
+ * @returns {{id: string, title: string, status: string}|null} 見つかった未完了タスク
322
+ */
323
+ export function findOpenBatchTask(tasks, batchId) {
324
+ const want = `[${String(batchId ?? '').trim()}]`
325
+ if (!want || want === '[]') return null
326
+ for (const t of Array.isArray(tasks) ? tasks : []) {
327
+ if (!t) continue
328
+ if (CLOSED_STATUSES.has(String(t.status ?? ''))) continue
329
+ if (!String(t.title ?? '').trim().startsWith(want)) continue
330
+ return { id: String(t.id ?? ''), title: String(t.title ?? ''), status: String(t.status ?? '') }
331
+ }
332
+ return null
333
+ }
334
+
335
+ /**
336
+ * `repoPath` 配下に収まる形で相対パスを解決する(`../` で外へ出る指定は拒否)。
337
+ *
338
+ * @param {string} repoPath リポジトリの絶対パス
339
+ * @param {string} relPath 相対パス
340
+ * @returns {string} 絶対パス
341
+ * @throws {Error} 不正なパス(statusCode 400)
342
+ */
343
+ export function resolveSpecPath(repoPath, relPath) {
344
+ const root = path.resolve(String(repoPath ?? ''))
345
+ const rel = String(relPath ?? '').trim()
346
+ if (!rel) throw new ApiError('SPEC_PATH_REQUIRED', {}, 400)
347
+ if (path.isAbsolute(rel)) throw new ApiError('SPEC_PATH_NOT_RELATIVE', {}, 400)
348
+ const abs = path.resolve(root, rel)
349
+ if (abs !== root && !abs.startsWith(root + path.sep)) {
350
+ throw new ApiError('SPEC_PATH_OUTSIDE', {}, 400)
351
+ }
352
+ return abs
353
+ }
354
+
355
+ /** 本文取得の上限(256KB)。超えた分は切り詰め、`truncated: true` で知らせる。 */
356
+ export const SPEC_CONTENT_MAX = 256 * 1024
357
+
358
+ /** 本文として読める拡張子(`.md` のみ)。 */
359
+ const MARKDOWN_RE = /\.md$/i
360
+
361
+ /**
362
+ * 1 枚の SPEC の全文を読む(リポジトリ境界内・`.md` のみ・256KB 上限)。
363
+ *
364
+ * パスの検証は `resolveSpecPath` に任せる(`../` や絶対パスは 400)。
365
+ * 上限で切り詰めたときは `truncated: true` を立て、`markdown` は 256KB までに収める
366
+ * (UTF-8 の途中で切れた 1 文字は落とす=壊れた文字を混ぜない)。
367
+ *
368
+ * @param {string} repoPath リポジトリの絶対パス
369
+ * @param {string} specRelPath リポジトリからの相対パス(`docs/SPEC-….md`)
370
+ * @returns {{ok: true, path: string, title: string, mtime: number, batchCount: number, truncated: boolean, markdown: string, bytes: number}} 本文
371
+ * @throws {ApiError} 不正パス(400)/非 `.md`(400)/未検出・読めない(404)
372
+ */
373
+ export function readSpecContent(repoPath, specRelPath) {
374
+ const rel = String(specRelPath ?? '').trim().split(path.sep).join('/')
375
+ const abs = resolveSpecPath(repoPath, rel)
376
+ if (!MARKDOWN_RE.test(abs)) throw new ApiError('SPEC_NOT_MARKDOWN', { path: rel }, 400)
377
+
378
+ let st
379
+ try {
380
+ st = fs.statSync(abs)
381
+ } catch {
382
+ throw new ApiError('SPEC_READ_FAILED', { path: rel }, 404)
383
+ }
384
+ if (typeof st?.isFile === 'function' && !st.isFile()) {
385
+ throw new ApiError('SPEC_READ_FAILED', { path: rel }, 404)
386
+ }
387
+
388
+ let buf
389
+ try {
390
+ buf = fs.readFileSync(abs)
391
+ } catch {
392
+ throw new ApiError('SPEC_READ_FAILED', { path: rel }, 404)
393
+ }
394
+
395
+ const truncated = buf.length > SPEC_CONTENT_MAX
396
+ let markdown = (truncated ? buf.subarray(0, SPEC_CONTENT_MAX) : buf).toString('utf8')
397
+ // 上限で切れた位置が UTF-8 の途中だと U+FFFD が末尾に残る。1 文字だけ落とす。
398
+ if (truncated && markdown.endsWith('\uFFFD')) markdown = markdown.slice(0, -1)
399
+
400
+ const parsed = parseSpec(markdown)
401
+ return {
402
+ ok: true,
403
+ path: rel,
404
+ title: parsed.title || path.basename(abs).replace(/\.md$/i, ''),
405
+ mtime: Number(st?.mtimeMs ?? st?.mtime ?? 0),
406
+ batchCount: parsed.batches.length,
407
+ truncated,
408
+ markdown,
409
+ // 実際に返した本文のバイト数(PWA が「切り詰め」を出せるように)
410
+ bytes: Buffer.byteLength(markdown, 'utf8'),
411
+ }
412
+ }
413
+
414
+ /**
415
+ * 起票元チャット ID をサニタイズする(書式に合わなければ空=`Chat:` 行を書かない)。
416
+ *
417
+ * @param {unknown} raw 入力(セッション ID 等)
418
+ * @returns {string} 安全な ID(無効なら空文字)
419
+ */
420
+ export function sanitizeSpecChat(raw) {
421
+ const s = String(raw ?? '').trim()
422
+ return SPEC_CHAT_RE.test(s) ? s : ''
423
+ }
424
+
425
+ /**
426
+ * `pipeline-runs.json` のパス(レビューディレクトリ配下。`review-watcher` と同じ解決規則)。
427
+ *
428
+ * @param {object} cfg ブリッジ設定(`reviewDir` / `pluginDataDir` / `kanbanRoot`)
429
+ * @returns {string} 絶対パス
430
+ */
431
+ export function runsPathFor(cfg = {}) {
432
+ const root =
433
+ cfg.reviewDir ??
434
+ path.join(
435
+ cfg.pluginDataDir ?? path.join(cfg.kanbanRoot ?? '.', '..', 'plugin-data', 'hermes-pilot'),
436
+ 'review',
437
+ )
438
+ return path.join(root, 'pipeline-runs.json')
439
+ }
440
+
441
+ /**
442
+ * ラン記録を読む(壊れていても空。補助情報なので落とさない)。
443
+ *
444
+ * @param {string} file パス
445
+ * @returns {Array<object>} ラン(新しい順は保証しない)
446
+ */
447
+ export function readRuns(file) {
448
+ let raw = ''
449
+ try {
450
+ raw = fs.readFileSync(file, 'utf8')
451
+ } catch {
452
+ return []
453
+ }
454
+ try {
455
+ const j = JSON.parse(raw)
456
+ const list = Array.isArray(j) ? j : j?.runs
457
+ if (!Array.isArray(list)) return []
458
+ return list.filter((r) => r && typeof r === 'object' && String(r.id ?? '').trim())
459
+ } catch {
460
+ return []
461
+ }
462
+ }
463
+
464
+ /**
465
+ * 上限まで剪定する(**古い完了分から**落とす。未報告ランは最後まで残す)。
466
+ *
467
+ * @param {Array<object>} runs ラン
468
+ * @param {number} [max] 上限(既定 50)
469
+ * @returns {Array<object>} 剪定後(元の順序を保つ)
470
+ */
471
+ export function pruneRuns(runs, max = RUNS_MAX) {
472
+ const list = Array.isArray(runs) ? runs.slice() : []
473
+ let over = list.length - Math.max(0, Number(max) || 0)
474
+ if (over <= 0) return list
475
+ const byAge = list.slice().sort((a, b) => Number(a?.createdAt ?? 0) - Number(b?.createdAt ?? 0))
476
+ const drop = new Set()
477
+ for (const r of byAge) {
478
+ if (over <= 0) break
479
+ if (!r?.reportedAt) continue
480
+ drop.add(r)
481
+ over -= 1
482
+ }
483
+ for (const r of byAge) {
484
+ if (over <= 0) break
485
+ if (drop.has(r)) continue
486
+ drop.add(r)
487
+ over -= 1
488
+ }
489
+ return list.filter((r) => !drop.has(r))
490
+ }
491
+
492
+ /**
493
+ * ラン記録を `.tmp` → `renameSync` でアトミックに書く。
494
+ *
495
+ * @param {string} file パス
496
+ * @param {Array<object>} runs ラン
497
+ * @returns {void}
498
+ */
499
+ export function writeRuns(file, runs) {
500
+ fs.mkdirSync(path.dirname(file), { recursive: true })
501
+ const tmp = `${file}.tmp`
502
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, runs: pruneRuns(runs) }, null, 2), 'utf8')
503
+ fs.renameSync(tmp, file)
504
+ }
505
+
506
+ /**
507
+ * ランを 1 件追記する(同じ ID は置き換え)。
508
+ *
509
+ * @param {object} cfg ブリッジ設定
510
+ * @param {object} run ラン
511
+ * @returns {Array<object>} 書いた内容
512
+ */
513
+ export function appendRun(cfg, run) {
514
+ const file = runsPathFor(cfg)
515
+ const runs = readRuns(file)
516
+ const next = [...runs.filter((r) => r.id !== run.id), run]
517
+ writeRuns(file, next)
518
+ return pruneRuns(next)
519
+ }
520
+
521
+ /**
522
+ * ランの ID(`run_<UTC 秒>_<乱数 4>`)。同じ秒に 2 回落としても衝突しない。
523
+ * @param {number} [ms] epoch ms
524
+ * @returns {string} ID
525
+ */
526
+ export function makeRunId(ms = Date.now()) {
527
+ const stamp = new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\..+$/, '')
528
+ const tail = Math.random().toString(36).slice(2, 6).padEnd(4, '0')
529
+ return `run_${stamp}_${tail}`
530
+ }
531
+
532
+ /**
533
+ * 起票の実行(既定は `hermes kanban create`、テストでは差し替え)。
534
+ *
535
+ * @param {object} cfg 設定(`hermesBin`)
536
+ * @param {Function} [runner] 差し替え
537
+ * @returns {Function} 実行関数
538
+ */
539
+ function defaultRunner(cfg = {}, runner) {
540
+ if (runner) return runner
541
+ return (args) =>
542
+ new Promise((resolve) => {
543
+ execFile(
544
+ cfg.hermesBin ?? resolveHermesBin(),
545
+ args,
546
+ { timeout: 30_000, maxBuffer: 2_000_000, env: { ...process.env, PATH: buildAugmentedPath() } },
547
+ (err, stdout, stderr) => {
548
+ resolve({ code: err ? (err.code ?? 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
549
+ },
550
+ )
551
+ })
552
+ }
553
+
554
+ /**
555
+ * `hermes kanban create` の出力からタスク ID を取り出す。
556
+ * @param {string} stdout 標準出力
557
+ * @returns {{id: string}|null} タスク(取れなければ null)
558
+ */
559
+ export function parseCreatedTask(stdout) {
560
+ const text = String(stdout ?? '')
561
+ const at = text.indexOf('{')
562
+ if (at >= 0) {
563
+ try {
564
+ const obj = JSON.parse(text.slice(at))
565
+ if (obj?.id) return { id: String(obj.id), title: obj.title ?? null, status: obj.status ?? null }
566
+ } catch {
567
+ /* 下の正規表現へ */
568
+ }
569
+ }
570
+ const m = /Created (t_[0-9a-zA-Z]+)/.exec(text)
571
+ return m ? { id: m[1] } : null
572
+ }
573
+
574
+ /**
575
+ * Spec Launchpad(読み取り + 起票)。
576
+ *
577
+ * @param {object} cfg 設定(`hermesBin`)
578
+ * @param {{
579
+ * runner?: Function,
580
+ * tasks?: (board: string) => Array<object>,
581
+ * listSpecs?: Function,
582
+ * recordRun?: (run: object) => void,
583
+ * now?: () => number,
584
+ * }} [deps] 差し替え(テスト用)
585
+ * @returns {{listSpecs: Function, launchSpec: Function, resolveSpecPath: Function, readSpecContent: Function}} 操作
586
+ */
587
+ export function createSpecs(cfg = {}, deps = {}) {
588
+ const run = defaultRunner(cfg, deps.runner)
589
+ // 既存タスクの読み取り(サーバでは kanban.tasks を渡す。テストでは [] か一時 DB)
590
+ const readTasks = deps.tasks ?? (() => [])
591
+ const scan = deps.listSpecs ?? (() => [])
592
+ const now = typeof deps.now === 'function' ? deps.now : () => Date.now()
593
+ // ラン記録(既定は `review/pipeline-runs.json`。テストでは差し替え)。
594
+ // 出力先が分からない cfg(テストの `{}` など)では何もしない(リポジトリを汚さない)。
595
+ const canRecord = Boolean(cfg.reviewDir || cfg.pluginDataDir || cfg.kanbanRoot)
596
+ const recordRun =
597
+ deps.recordRun ?? (canRecord ? (r) => appendRun(cfg, r) : () => {})
598
+
599
+ /**
600
+ * バッチをカンバンへ一括起票する。
601
+ *
602
+ * @param {{
603
+ * repoPath: string,
604
+ * board: string,
605
+ * specRelPath: string,
606
+ * batchIds?: string[],
607
+ * assignee?: string,
608
+ * dryRun?: boolean,
609
+ * limit?: number,
610
+ * }} input 入力
611
+ * @returns {Promise<{ok: boolean, created: Array<object>, skipped: Array<object>, failed: Array<object>, spec?: string, board?: string, error?: string}>} 結果
612
+ */
613
+ async function launchSpec(input = {}) {
614
+ const board = String(input.board ?? '').trim()
615
+ if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(board)) {
616
+ return { ok: false, created: [], skipped: [], failed: [], code: 'BOARD_NAME_INVALID' }
617
+ }
618
+ const repoPath = String(input.repoPath ?? '').trim()
619
+ if (!repoPath || !path.isAbsolute(repoPath)) {
620
+ return { ok: false, created: [], skipped: [], failed: [], code: 'INVALID_REPO' }
621
+ }
622
+ const specRelPath = String(input.specRelPath ?? '').trim()
623
+ let file = ''
624
+ try {
625
+ file = resolveSpecPath(repoPath, specRelPath)
626
+ } catch (e) {
627
+ return { ok: false, created: [], skipped: [], failed: [], code: e.code, params: e.params, error: e.message }
628
+ }
629
+
630
+ let text = ''
631
+ try {
632
+ text = fs.readFileSync(file, 'utf8')
633
+ } catch {
634
+ return { ok: false, created: [], skipped: [], failed: [], code: 'SPEC_READ_FAILED', params: { path: specRelPath } }
635
+ }
636
+ const parsed = parseSpec(text)
637
+ if (!parsed.batches.length) {
638
+ return { ok: false, created: [], skipped: [], failed: [], code: 'SPEC_BATCH_HEADING_MISSING' }
639
+ }
640
+
641
+ const wanted = Array.isArray(input.batchIds) ? new Set(input.batchIds.map((x) => String(x ?? '').trim())) : null
642
+ const batches = parsed.batches.filter((b) => !wanted || wanted.size === 0 || wanted.has(b.id))
643
+ if (!batches.length) {
644
+ return { ok: false, created: [], skipped: [], failed: [], code: 'SPEC_BATCH_NOT_FOUND' }
645
+ }
646
+
647
+ const assignee = String(input.assignee ?? '').trim()
648
+ const dryRun = Boolean(input.dryRun)
649
+ // 起票元チャット(`Chat:` 行+ラン記録の originSessionId)。書式外は黙って捨てる。
650
+ const chat = sanitizeSpecChat(input.chat)
651
+
652
+ let existing = []
653
+ try {
654
+ existing = readTasks(board) ?? []
655
+ } catch {
656
+ existing = []
657
+ }
658
+
659
+ const created = []
660
+ const skipped = []
661
+ const failed = []
662
+ for (const batch of batches) {
663
+ const open = findOpenBatchTask(existing, batch.id)
664
+ if (open) {
665
+ skipped.push({ id: batch.id, title: batch.title, reason: 'exists', taskId: open.id, status: open.status })
666
+ continue
667
+ }
668
+ const title = buildTaskTitle(batch)
669
+ const body = buildTaskBody({ specRelPath, repoPath, board, batch, chat })
670
+ if (dryRun) {
671
+ created.push({ id: batch.id, title, taskId: null, dryRun: true })
672
+ continue
673
+ }
674
+ const args = ['kanban', '--board', board, 'create', title, '--json', '--body', body]
675
+ if (assignee) args.push('--assignee', assignee)
676
+ const res = await run(args)
677
+ if (res.code !== 0) {
678
+ failed.push({
679
+ id: batch.id,
680
+ title,
681
+ code: 'CREATE_FAILED',
682
+ error: (res.stderr || res.stdout || '').trim().slice(0, 400),
683
+ })
684
+ continue
685
+ }
686
+ const task = parseCreatedTask(res.stdout)
687
+ if (!task?.id) {
688
+ failed.push({ id: batch.id, title, code: 'TASK_ID_MISSING' })
689
+ continue
690
+ }
691
+ created.push({ id: batch.id, title, taskId: task.id, status: task.status ?? 'ready' })
692
+ // 同じバッチを 2 回起票しないよう、今回作った分も既存扱いにする
693
+ existing = [...existing, { id: task.id, title, status: task.status ?? 'ready' }]
694
+ }
695
+
696
+ const ok = failed.length === 0
697
+
698
+ // ラン記録(1 件以上起票 or 既存へ紐づけできたときだけ)。記録失敗で起票を失敗させない。
699
+ let runRecord = null
700
+ if (!dryRun && (created.length > 0 || skipped.length > 0)) {
701
+ const taskIds = [...created.map((c) => c.taskId), ...skipped.map((s) => s.taskId)].filter(Boolean)
702
+ runRecord = {
703
+ id: makeRunId(now()),
704
+ board,
705
+ repoPath,
706
+ specRelPath,
707
+ title: parsed.title || specRelPath,
708
+ batchIds: batches.map((b) => b.id),
709
+ taskIds: [...new Set(taskIds)],
710
+ originSessionId: chat || null,
711
+ createdAt: now(),
712
+ reportedAt: null,
713
+ }
714
+ try {
715
+ recordRun(runRecord)
716
+ } catch {
717
+ runRecord = null
718
+ }
719
+ }
720
+
721
+ return {
722
+ ok,
723
+ spec: specRelPath,
724
+ board,
725
+ created,
726
+ skipped,
727
+ failed,
728
+ runId: runRecord?.id ?? null,
729
+ ...(ok ? {} : { error: failed.map((f) => `${f.id}: ${f.error}`).join(' / ') }),
730
+ }
731
+ }
732
+
733
+ return { listSpecs: scan, launchSpec, resolveSpecPath, readSpecContent }
734
+ }