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,1298 @@
1
+ /**
2
+ * Architect ランナー(SPEC V5 §3.2 / D23・D25・D26①)— 「仕様の種」から仕様書まで。
3
+ *
4
+ * 役割は 4 つだけ。どれも**観測できる状態**を返し、PWA が固まらないように即答する。
5
+ * 1. `seed()` … 1 行メモ(または音声の書き起こし)を受けて Architect を**背後で**起動し、
6
+ * `202` で `jobId` を返す(タイムアウト待ちで画面を固めない)
7
+ * 2. `jobs()` … ジョブの進み具合と、**完成した新しい SPEC** を返す(A2B の「仕様書の準備が完了」)
8
+ * 3. `jobs()` … 未起票の SPEC を数えて返す(1 タップ一括起票カードの材料)
9
+ * 4. `autoStart` … ON のジョブだけ、完成 SPEC の未起票バッチを**1 回だけ**起票する(冪等)
10
+ *
11
+ * ## スタックしないための終端判定(SPEC V7 §3.1)
12
+ *
13
+ * - 親 `[ARCH]` タスクが `done` / `archived` になったら、SPEC 未検知でもジョブは終端にして
14
+ * 進行バー(`jobs`)から落とす。落とさないと「仕様書を書いています…」が残り続ける。
15
+ * - `dismiss(jobId)` は破棄を**データストアに永続化**する(リロード・再起動で復活しない)。
16
+ * `jobs()` は破棄済みを既定で除外する(`includeDismissed: true` は監査・テスト用)。
17
+ * - `queueState`(`queued` / `running`)で「キュー待ち」と「実行中」を区別できる形で返す。
18
+ *
19
+ * ## 実行ランナー
20
+ *
21
+ * ランナーは **`Hermes Native` の 1 本だけ**(`RUNNERS = ['hermes']`)。`hermes kanban create` で
22
+ * `[ARCH]` タスクを起票する**公式ルート**を子プロセスで 1 回だけ呼び、あとはカンバンの
23
+ * 自走ワーカーが仕様書を書く。外部 AI CLI の検出・パス解決・子プロセス起動は
24
+ * SPEC V11 D50 で**完全に削除**した(サードパーティの CLI をラップ起動してサブスク枠を
25
+ * 消費させる行為は規約違反=BAN 対象)。`scripts/check-oauth-boundary.mjs` が再混入を機械検査する。
26
+ * 旧 Opt-in ランナー名を指定された場合は `INVALID_RUNNER`(HTTP 400)で弾く。
27
+ *
28
+ * ## ステータス遷移
29
+ *
30
+ * `running`(CLI 実行中)→ `awaiting_spec`(CLI 正常終了・SPEC 待ち)→ `spec_ready`(完成検知)
31
+ * → `launched`(autoStart で起票済み)/ `failed`(CLI 異常終了)
32
+ *
33
+ * ## 終了時の扱い(SPEC V9 D41 の決定を維持)
34
+ *
35
+ * ランナー(`hermes kanban create`)が非 0 終了したら `failed` に理由を残すだけで、
36
+ * 裏で勝手に別経路の起票へ切り替えたりはしない(二重稼働・重複起票の根絶)。
37
+ * 再試行は UI の明示操作(1 タップ再試行)だけ。
38
+ *
39
+ * ## ボード横断の Review 検知とフェーズ(SPEC V9 D42)
40
+ *
41
+ * `[review]` は `job.board` に加えて `mobile` ボードも走査する(`reviewBoardsFor`)。
42
+ * `review/sheets/spec-*.json` の中間シートを `sheetPath` として観測し、
43
+ * `phase`(`spawning`〜`failed`)と `stalled`(3 分無進展)を `publicJob()` で返す。
44
+ */
45
+
46
+ import fs from 'node:fs'
47
+ import path from 'node:path'
48
+ import { execFile } from 'node:child_process'
49
+ import { listSpecs as scanSpecs, parseCreatedTask } from './specs.js'
50
+ import { appendChatReport } from './pipeline-watcher.js'
51
+ import { buildAugmentedPath, resolveHermesBin } from './capabilities.js'
52
+
53
+ /** `chat-reports.jsonl` の行種別(仕様書が完成した)。 */
54
+ export const SPEC_READY_KIND = 'spec_ready'
55
+ /** `chat-reports.jsonl` の行種別(autoStart がバッチを起票した)。 */
56
+ export const SPEC_LAUNCH_KIND = 'spec_launch'
57
+
58
+ /**
59
+ * 選べるランナー。**`Hermes Native` の 1 本だけ**(SPEC V11 D50)。
60
+ *
61
+ * 外部 AI CLI をラップ起動するランナーは規約違反(サブスク枠の消費)なので、
62
+ * 検出もパス解決も子プロセス起動もこのファイルには置かない。
63
+ */
64
+ export const RUNNERS = ['hermes']
65
+
66
+ /**
67
+ * 実行方針(生成する SPEC 各バッチの既定 Execution Mode)。SPEC V7 §3.1 / D35。
68
+ *
69
+ * どちらの方針でも Round 1 の Quick Review インタビューは必ず行い、
70
+ * 変わるのは「各バッチを止まらずに完走させるか・要所で視覚確認を挟むか」だけ。
71
+ */
72
+ export const EXECUTION_POLICIES = ['zero-stop', 'visual-gate']
73
+ /** 実行方針の既定値(未指定・不正値はこれへ正規化する)。 */
74
+ export const DEFAULT_EXECUTION_POLICY = 'zero-stop'
75
+
76
+ /** 親 `[ARCH]` タスクがこの状態になったらジョブは終端(進行バーに残さない)。 */
77
+ export const TERMINAL_TASK_STATUSES = ['done', 'archived']
78
+
79
+ /**
80
+ * Quick Review(`[review]`)が撒かれる既定ボード(SPEC V9 D42)。
81
+ *
82
+ * 種は `hermes-pilot` などリポジトリ固有ボードで撒かれても、Round 1 のシートは `mobile` に届く。
83
+ * 走査対象を `[job.board, DEFAULT_REVIEW_BOARD]` に広げないと `awaiting_review` を取りこぼす。
84
+ */
85
+ export const DEFAULT_REVIEW_BOARD = 'mobile'
86
+
87
+ /** 進行バーに残す「アクティブ」状態(ボード横断で返す対象。`failed` も人が気づくまで残す)。 */
88
+ export const ACTIVE_JOB_STATUSES = ['running', 'awaiting_spec', 'awaiting_review', 'failed']
89
+
90
+ /** `publicJob().phase` が返すフェーズ(SPEC V9 D42)。 */
91
+ export const ARCHITECT_PHASES = [
92
+ 'spawning',
93
+ 'round1_sheet',
94
+ 'awaiting_review',
95
+ 'round2_spec',
96
+ 'spec_ready',
97
+ 'launched',
98
+ 'failed',
99
+ ]
100
+
101
+ /** 進展が無いままこの時間を超えたら `stalled`(3 分。SPEC V9 D42/D43)。 */
102
+ export const STALLED_AFTER_MS = 180_000
103
+ /** 破棄したジョブ ID を保持する上限(古いものから落とす)。 */
104
+ export const DISMISSED_MAX = 500
105
+
106
+ /** 0 行の種はインタビューにならない。長すぎる種はプロンプトを壊す。 */
107
+ export const SEED_MIN = 1
108
+ /** 種の最大文字数。 */
109
+ export const SEED_MAX = 4000
110
+ /** 保持するジョブ数(古いものから落とす)。 */
111
+ export const JOBS_MAX = 40
112
+ /** 「このジョブが作った SPEC」と見なす mtime の猶予(秒ズレ対策)。 */
113
+ export const SPEC_MTIME_SLACK_MS = 5000
114
+ /** ランナーの既定タイムアウト(ミリ秒)。 */
115
+ export const RUNNER_TIMEOUT_MS = 15 * 60 * 1000
116
+ /** ボード名の書式(`specs.launchSpec` と同じ)。 */
117
+ export const BOARD_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/i
118
+
119
+ /** ランナーの表示名(ランナーは 1 本だけ)。 */
120
+ export const RUNNER_LABELS = {
121
+ hermes: 'Hermes Native',
122
+ }
123
+
124
+ /** ランナー名として受け付ける値(空・未指定は Hermes Native へ倒す)。 */
125
+ export const DEFAULT_RUNNER = 'hermes'
126
+
127
+ /**
128
+ * ランナー ID を正規化する(**常に `hermes`**。SPEC V11 D50)。
129
+ *
130
+ * 受け付ける値は `hermes` だけだが、`sanitizeRunner()` は表示用の緩い正規化なので
131
+ * 未知の値も既定へ倒す。API 入力の可否判定は `isSupportedRunner()` で行う。
132
+ * @param {unknown} value 入力
133
+ * @returns {'hermes'} ランナー
134
+ */
135
+ export function sanitizeRunner(value) {
136
+ return DEFAULT_RUNNER
137
+ }
138
+
139
+ /**
140
+ * 明示されたランナーが受け付けられるか(`''` / 未指定は既定として許す)。
141
+ * @param {unknown} value 入力
142
+ * @returns {boolean} `hermes` か未指定なら true
143
+ */
144
+ export function isSupportedRunner(value) {
145
+ const text = String(value ?? '')
146
+ .trim()
147
+ .toLowerCase()
148
+ return text === '' || text === DEFAULT_RUNNER
149
+ }
150
+
151
+ /**
152
+ * ランナーの表示名。
153
+ * @param {unknown} value 入力
154
+ * @returns {string} 表示名
155
+ */
156
+ export function runnerLabel(value) {
157
+ return RUNNER_LABELS[sanitizeRunner(value)]
158
+ }
159
+
160
+ /**
161
+ * 実行方針を正規化する(未指定・不正値は `zero-stop`)。
162
+ * @param {unknown} value 入力
163
+ * @returns {'zero-stop'|'visual-gate'} 実行方針
164
+ */
165
+ export function normalizeExecutionPolicy(value) {
166
+ const text = String(value ?? '')
167
+ .trim()
168
+ .toLowerCase()
169
+ .replace(/_/g, '-')
170
+ return EXECUTION_POLICIES.includes(text) ? text : DEFAULT_EXECUTION_POLICY
171
+ }
172
+
173
+ /**
174
+ * 実行方針に対応する SPEC バッチの `Execution Mode` 表記。
175
+ * @param {unknown} value 実行方針
176
+ * @returns {string} `[Mode: Zero-Stop]` / `[Mode: Visual Gate]`
177
+ */
178
+ export function executionModeLabel(value) {
179
+ return normalizeExecutionPolicy(value) === 'visual-gate' ? '[Mode: Visual Gate]' : '[Mode: Zero-Stop]'
180
+ }
181
+
182
+ /**
183
+ * プロンプトへ差し込む実行方針の指示(両方針共通で Quick Review は必須)。
184
+ * @param {unknown} value 実行方針
185
+ * @returns {string[]} 行
186
+ */
187
+ function executionPolicyLines(value) {
188
+ const policy = normalizeExecutionPolicy(value)
189
+ const mode = executionModeLabel(policy)
190
+ const intent =
191
+ policy === 'visual-gate'
192
+ ? 'pause at the visual checkpoints and wait for approval before going further'
193
+ : 'do not stop for approval: run every batch autonomously to done'
194
+ return [
195
+ `- Round 1 Quick Review interview is mandatory under both policies: still write the sheet and stop.`,
196
+ `- Execution policy chosen by the user: \`${policy}\`. Every batch in the generated SPEC must default to`,
197
+ ` **Execution Mode**: \`${mode}\` : ${intent}.`,
198
+ ]
199
+ }
200
+
201
+ /**
202
+ * [`[ARCH]` タスクのタイトル](カンバン起票に載る 1 行)。
203
+ * @param {{seedText?: string, prompt?: string}} input 入力
204
+ * @returns {string} タイトル
205
+ */
206
+ export function buildArchitectTaskTitle({ seedText, prompt } = {}) {
207
+ const line = String(seedText ?? prompt ?? '')
208
+ .split('\n')
209
+ .map((s) => s.trim())
210
+ .find(Boolean)
211
+ return `[ARCH] ${String(line ?? 'Spec seed').slice(0, 80)}`
212
+ }
213
+
214
+ /** 推奨スラッグの最大長(`docs/SPEC-<SLUG>.md` のファイル名が長くなりすぎないように)。 */
215
+ export const SPEC_SLUG_MAX = 28
216
+ /** プロンプトへ注入する既存 SPEC の最大件数(探索ターンとトークンの節約)。 */
217
+ export const EXISTING_SPECS_MAX = 6
218
+
219
+ /**
220
+ * 種から「推奨スラッグ」を作る(純関数。SPEC V11 D54)。
221
+ *
222
+ * Round 1 のシート名(`review/sheets/spec-<slug>-1.json`)と Round 2 の SPEC 名
223
+ * (`docs/SPEC-<SLUG>.md`)が、種を撒くたびに違う名前になるのを防ぐための**目安**。
224
+ * 先頭付近の ASCII 英数字(`[A-Za-z0-9]`)を小文字ハイフン区切りにし、最大 28 文字。
225
+ * ASCII が 1 つも無ければ `jobId` の末尾セグメントを使う。
226
+ *
227
+ * @param {unknown} seedText 種の本文
228
+ * @param {unknown} jobId ジョブ ID(`arch-<base36>-<tail>`)
229
+ * @returns {string} スラッグ(空にはならない)
230
+ */
231
+ export function suggestSpecSlug(seedText, jobId) {
232
+ /** @type {string[]} */
233
+ const words = []
234
+ for (const line of String(seedText ?? '')
235
+ .split('\n')
236
+ .map((s) => s.trim())
237
+ .filter(Boolean)
238
+ .slice(0, 3)) {
239
+ for (const token of line.match(/[A-Za-z0-9]+/g) ?? []) words.push(token)
240
+ if (words.length >= 4) break
241
+ }
242
+ const shape = (text) =>
243
+ String(text ?? '')
244
+ .toLowerCase()
245
+ .replace(/[^a-z0-9]+/g, '-')
246
+ .replace(/^-+|-+$/g, '')
247
+ let slug = shape(words.join('-'))
248
+ if (!slug) {
249
+ const tail = String(jobId ?? '')
250
+ .trim()
251
+ .split('-')
252
+ .filter(Boolean)
253
+ .pop()
254
+ slug = shape(tail)
255
+ }
256
+ if (!slug) return 'spec'
257
+ const clipped = slug.slice(0, SPEC_SLUG_MAX).replace(/-+$/g, '')
258
+ return clipped || slug.slice(0, SPEC_SLUG_MAX)
259
+ }
260
+
261
+ /**
262
+ * 既存 `docs/SPEC-*.md` の相対パスを「直近 N 件」で返す(SPEC V11 D54)。
263
+ *
264
+ * 名前の衝突と全量探索を減らすためにプロンプトへ注入する。走査に失敗しても
265
+ * 起票は止めない(空配列を返す)。
266
+ * @param {Function} listSpecsFn SPEC 走査(`specs.listSpecs`)
267
+ * @param {string} repoPath リポジトリ
268
+ * @param {number} [limit] 最大件数
269
+ * @returns {string[]} 相対パス(mtime の新しい順)
270
+ */
271
+ export function recentSpecPaths(listSpecsFn, repoPath, limit = EXISTING_SPECS_MAX) {
272
+ try {
273
+ const list = listSpecsFn(repoPath) ?? []
274
+ return (Array.isArray(list) ? list : [])
275
+ .filter((s) => s && s.path)
276
+ .sort((a, b) => Number(b.mtime ?? 0) - Number(a.mtime ?? 0) || String(a.path).localeCompare(String(b.path)))
277
+ .slice(0, Math.max(1, Number(limit) || EXISTING_SPECS_MAX))
278
+ .map((s) => String(s.path))
279
+ } catch {
280
+ return []
281
+ }
282
+ }
283
+
284
+ /**
285
+ * [`[ARCH]` タスクの本文](spec-architect プロトコル+実行契約)。
286
+ *
287
+ * カンバン起票に載せるので、ワーカーが**チャットを見なくても**完走できる内容にする。
288
+ * `executionPolicy` は**生成する SPEC の各バッチ**に付す既定 Execution Mode を決める
289
+ * (Architect 自身は止まらずに書き切るので、この本文の契約は常に zero-stop)。
290
+ *
291
+ * SPEC V11 D54: `suggestedSlug` / `existingSpecs` を渡すと、ファイル名の衝突回避と
292
+ * Round 1 の探索コスト削減の指示が本文に入る。
293
+ *
294
+ * @param {{prompt: string, board: string, repoPath: string, jobId: string, executionPolicy?: string, suggestedSlug?: string, existingSpecs?: string[]}} input 入力
295
+ * @returns {string} 本文
296
+ */
297
+ export function buildArchitectTaskBody({
298
+ prompt,
299
+ board,
300
+ repoPath,
301
+ jobId,
302
+ executionPolicy = DEFAULT_EXECUTION_POLICY,
303
+ suggestedSlug,
304
+ existingSpecs,
305
+ }) {
306
+ const policy = normalizeExecutionPolicy(executionPolicy)
307
+ const slug = String(suggestedSlug ?? '').trim() || suggestSpecSlug(prompt, jobId)
308
+ const specs = (Array.isArray(existingSpecs) ? existingSpecs : []).map((s) => String(s ?? '').trim()).filter(Boolean)
309
+ return [
310
+ `[hermes-pilot:architect job=${jobId}] Architect (Kanban native)`,
311
+ '',
312
+ prompt,
313
+ '',
314
+ '---',
315
+ '[Hermes Pilot Execution Contract]',
316
+ 'Mode: zero-stop',
317
+ `Execution Policy: ${policy} (applies to the batches of the SPEC you write)`,
318
+ 'Follow the `spec-architect` skill protocol for the seed above.',
319
+ `Suggested slug: ${slug} (use it for review/sheets/spec-${slug}-1.json and docs/SPEC-<SLUG>.md unless it clearly clashes)`,
320
+ specs.length
321
+ ? `Existing specs: ${specs.join(', ')} (do not reuse these file names; pick a distinct slug)`
322
+ : 'Existing specs: none in docs/ yet (the slug above is free)',
323
+ 'Round 1: write the Quick Review JSON sheet under review/sheets/',
324
+ '(spec-<slug>-1.json, "mode": "standard", 2-5 decisions) and file it as a blocked `[review]` task',
325
+ 'whose machine line is `mode=standard sheet=sheets/spec-<slug>-1.json`. Do not wait in chat.',
326
+ 'Round 1 speed: locate only the relevant symbols (rg/grep), skip running npm test / npm run verify / browser_exec during Round 1, write the JSON sheet and block immediately.',
327
+ 'Round 1 speed: skip bespoke HTML sheets and browser mockups (browser_exec screenshots) unless',
328
+ 'the question itself is a visual UI layout comparison; the JSON alone renders the native form.',
329
+ 'Round 2: after the answers arrive, write `docs/SPEC-<SLUG>.md` with `### Batch <ID>: <Title>` sections,',
330
+ 'each carrying **Execution Mode** / **目的** / **変更・新規ファイル** / **受入条件(Verify)**.',
331
+ ...executionPolicyLines(policy),
332
+ 'Stay inside the official local CLI: the only runner is `hermes kanban create` (no external AI CLI is launched).',
333
+ `Board: ${board}`,
334
+ `Repository: ${repoPath}`,
335
+ ].join('\n')
336
+ }
337
+
338
+ /**
339
+ * `hermes kanban create` の引数(`specs.js` / `capture.js` と同じ正規ルート)。
340
+ * @param {{board: string, title: string, body: string, assignee?: string}} input 入力
341
+ * @returns {string[]} 引数
342
+ */
343
+ export function buildKanbanCreateArgs({ board, title, body, assignee = 'mobile' }) {
344
+ return ['kanban', '--board', String(board ?? ''), 'create', String(title ?? ''), '--json', '--body', String(body ?? ''), '--assignee', String(assignee ?? 'mobile')]
345
+ }
346
+
347
+ /**
348
+ * 「[review] タスク」かどうか(タイトル・本文・ラベルを見る。読むだけ)。
349
+ * @param {object} task タスク
350
+ * @returns {boolean} review タスクなら true
351
+ */
352
+ export function isReviewTask(task) {
353
+ if (!task) return false
354
+ const labels = [task.label, ...(Array.isArray(task.labels) ? task.labels : [])].filter(Boolean).map((l) => String(l))
355
+ const text = [task.title, task.body].filter(Boolean).map((v) => String(v)).join('\n')
356
+ return /\[review\]/i.test(text) || labels.some((l) => /^\[?review\]?$/i.test(l.trim()))
357
+ }
358
+
359
+ /**
360
+ * ジョブが待っている Quick Review タスクを見つける(純関数)。
361
+ *
362
+ * 条件: ① `job.taskId` と一致するタスク、または `startedAt - 猶予` 以降に作られた `[review]` タスク。
363
+ * ② そのタスクが `blocked` で、`[review]` の印を持つ(=人の回答待ち)。
364
+ *
365
+ * @param {{taskId?: string|null, startedAt: number}} job ジョブ
366
+ * @param {Array<object>} tasks ボードのタスク
367
+ * @param {{slackMs?: number}} [opts] 制約
368
+ * @returns {{taskId: string, title: string, status: string}|null} 待機中タスク(無ければ null)
369
+ */
370
+ export function findJobReviewTask(job, tasks, { slackMs = SPEC_MTIME_SLACK_MS } = {}) {
371
+ const since = Number(job?.startedAt ?? 0) - slackMs
372
+ const ownId = job?.taskId ? String(job.taskId) : ''
373
+ const list = Array.isArray(tasks) ? tasks : []
374
+ for (const task of list) {
375
+ if (!task || !task.id) continue
376
+ const same = ownId && String(task.id) === ownId
377
+ const fresh = Number(task.createdAt ?? 0) >= since
378
+ if (!same && !fresh) continue
379
+ if (!isReviewTask(task)) continue
380
+ if (String(task.status ?? '') !== 'blocked') continue
381
+ return { taskId: String(task.id), title: String(task.title ?? ''), status: 'blocked' }
382
+ }
383
+ return null
384
+ }
385
+
386
+ /**
387
+ * ジョブ ID(`arch-<base36 時刻>-<乱数 4>`)。
388
+ * @param {number} [ms] 時刻
389
+ * @param {Function} [rand] 乱数(テスト用)
390
+ * @returns {string} ジョブ ID
391
+ */
392
+ export function makeJobId(ms = Date.now(), rand = Math.random) {
393
+ const tail = Math.floor(rand() * 36 ** 4)
394
+ .toString(36)
395
+ .padStart(4, '0')
396
+ return `arch-${ms.toString(36)}-${tail}`
397
+ }
398
+
399
+ /**
400
+ * 種の本文を整える(前後の空白だけ落とし、改行は保つ)。
401
+ * @param {unknown} value 入力
402
+ * @returns {string} 本文(不正なら空文字)
403
+ */
404
+ export function normalizeSeed(value) {
405
+ const text = String(value ?? '')
406
+ .replace(/\r\n?/g, '\n')
407
+ .trim()
408
+ if (text.length < SEED_MIN) return ''
409
+ return text.slice(0, SEED_MAX)
410
+ }
411
+
412
+ /**
413
+ * Architect へ渡すプロンプト(`spec-architect` プロトコル)。
414
+ *
415
+ * 長文の質問を並べるのではなく、Quick Review シート → 1 タップ承認 → SPEC 生成、の順を固定する。
416
+ * `executionPolicy` は**生成する SPEC の各バッチ**の既定 Execution Mode を決める(D35)。
417
+ * SPEC V11 D54: 推奨スラッグと既存 SPEC 一覧を先に渡し、Round 1 の探索と名前衝突を減らす。
418
+ * @param {{jobId: string, seedText: string, board: string, repoPath: string, autoStart?: boolean, executionPolicy?: string, lang?: string, suggestedSlug?: string, existingSpecs?: string[]}} input 入力
419
+ * @returns {string} プロンプト
420
+ */
421
+ export function buildSeedPrompt({
422
+ jobId,
423
+ seedText,
424
+ board,
425
+ repoPath,
426
+ autoStart = false,
427
+ executionPolicy = DEFAULT_EXECUTION_POLICY,
428
+ lang = 'ja',
429
+ suggestedSlug,
430
+ existingSpecs,
431
+ }) {
432
+ const auto = autoStart
433
+ ? 'The PWA will file the batches automatically as soon as this SPEC appears, so do not file them yourself.'
434
+ : 'Do not file anything yet: the user taps "File batches & start" once the SPEC is ready.'
435
+ const slug = String(suggestedSlug ?? '').trim() || suggestSpecSlug(seedText, jobId)
436
+ const specs = (Array.isArray(existingSpecs) ? existingSpecs : []).map((s) => String(s ?? '').trim()).filter(Boolean)
437
+ return [
438
+ `[hermes-pilot:architect job=${jobId}]`,
439
+ 'You are the spec-architect. Follow the `spec-architect` skill protocol (Round 1 → Round 2).',
440
+ '',
441
+ 'Seed (the user dictation, verbatim):',
442
+ '"""',
443
+ seedText,
444
+ '"""',
445
+ '',
446
+ `Repository: ${repoPath}`,
447
+ `Board: ${board}`,
448
+ `UI language: ${lang}`,
449
+ `Suggested slug: ${slug}`,
450
+ specs.length
451
+ ? `Existing specs: ${specs.join(', ')}`
452
+ : 'Existing specs: none in docs/ yet (the suggested slug is free)',
453
+ '',
454
+ 'Round 1 — instead of a wall of chat questions, write ONE structured sheet as JSON:',
455
+ `\`review/sheets/spec-${slug}-1.json\` with \`"mode": "standard"\` and 2-5 design decisions`,
456
+ '(each option marked `recommended: true` for the best one), then file it as a blocked [review]',
457
+ 'kanban task whose machine line reads',
458
+ `\`[review] label=spec-${slug} round=1 mode=standard sheet=sheets/spec-${slug}-1.json target=<repo>\``,
459
+ 'so the phone renders the native 1-tap form. Stop there.',
460
+ 'Do not reuse a file name from Existing specs above: pick a distinct slug if it would clash.',
461
+ '',
462
+ 'Round 1 speed rule — the JSON is the deliverable. Locate only the relevant symbols (rg/grep);',
463
+ 'do NOT run npm test / npm run verify, and do NOT hand-write a long bespoke HTML sheet or launch',
464
+ 'a headless browser (browser_exec or similar) to screenshot mockups unless the question itself is',
465
+ 'a visual UI-layout comparison (placement, density, colour) that words cannot settle; even then it',
466
+ 'is optional and comes after the JSON. For spec, logic, string, API and data questions just check',
467
+ 'the cited file:line, write the sheet and block immediately.',
468
+ 'Round 2 — after the answers arrive, write docs/SPEC-<SLUG>.md. Every batch heading',
469
+ '`### Batch <ID>: <Title>` must be followed by:',
470
+ ' - **Execution Mode**: [Mode: Zero-Stop | Fast-Track Review | Visual Gate]',
471
+ ' - **目的**: one paragraph of intent',
472
+ ' - **変更・新規ファイル**: the exact paths to touch',
473
+ ' - **受入条件(Verify)**: the command that proves it works',
474
+ '',
475
+ 'Execution policy for the batches you generate:',
476
+ ...executionPolicyLines(executionPolicy),
477
+ '',
478
+ auto,
479
+ ].join('\n')
480
+ }
481
+
482
+ /**
483
+ * 既定のランナー実行(公式 CLI の子プロセス。シェルは介さない)。
484
+ *
485
+ * `hermes kanban --board <b> create "[ARCH] …" --assignee mobile --json --body …` という
486
+ * **正規ルート**でカンバンに Architect タスクを起票する(自走ワーカーが着火する)。
487
+ * 外部 AI CLI のラッパー起動は SPEC V11 D50 で廃止した(`RUNNERS = ['hermes']` の 1 本だけ)。
488
+ * `PATH` は `buildAugmentedPath()` で補う(`launchd` の狭い PATH 対策)。
489
+ * @param {object} [cfg] 設定(`hermesBin`)
490
+ * @returns {Function} `({runnerId, prompt, repoPath, board, seedText, jobId, executionPolicy, suggestedSlug, existingSpecs, timeoutMs}) => Promise<{code,stdout,stderr}>`
491
+ */
492
+ export function createCliRunner(cfg = {}) {
493
+ return ({
494
+ runnerId,
495
+ prompt,
496
+ repoPath,
497
+ board = '',
498
+ seedText = '',
499
+ jobId = '',
500
+ executionPolicy = DEFAULT_EXECUTION_POLICY,
501
+ suggestedSlug,
502
+ existingSpecs,
503
+ timeoutMs = RUNNER_TIMEOUT_MS,
504
+ }) =>
505
+ new Promise((resolve) => {
506
+ const bin = cfg.hermesBin ?? resolveHermesBin()
507
+ const slug = String(suggestedSlug ?? '').trim() || suggestSpecSlug(seedText || prompt, jobId)
508
+ const title = buildArchitectTaskTitle({ seedText: seedText || prompt })
509
+ const body = buildArchitectTaskBody({
510
+ prompt,
511
+ board,
512
+ repoPath,
513
+ jobId,
514
+ executionPolicy,
515
+ suggestedSlug: slug,
516
+ existingSpecs,
517
+ })
518
+ const args = buildKanbanCreateArgs({ board, title, body })
519
+ execFile(
520
+ bin,
521
+ args,
522
+ { cwd: repoPath, timeout: timeoutMs, maxBuffer: 4_000_000, env: { ...process.env, PATH: buildAugmentedPath() } },
523
+ (err, stdout, stderr) => {
524
+ const code = err ? (typeof err.code === 'number' ? err.code : 1) : 0
525
+ resolve({ code, stdout: String(stdout ?? ''), stderr: String(stderr ?? ''), bin, args })
526
+ },
527
+ )
528
+ })
529
+ }
530
+
531
+ /**
532
+ * ジョブが作ったと見なせる SPEC を 1 つ選ぶ。
533
+ *
534
+ * 条件: バッチを持つ / `startedAt` 以降に更新された(猶予あり) / 他のジョブが先に取っていない。
535
+ * @param {{startedAt: number}} job ジョブ
536
+ * @param {Array<{path: string, title: string, mtime: number, batches: Array<object>}>} specs SPEC 一覧
537
+ * @param {{taken?: Set<string>, slackMs?: number}} [opts] 制約
538
+ * @returns {object|null} SPEC(無ければ null)
539
+ */
540
+ export function findJobSpec(job, specs, { taken = new Set(), slackMs = SPEC_MTIME_SLACK_MS } = {}) {
541
+ const since = Number(job?.startedAt ?? 0) - slackMs
542
+ const candidates = (Array.isArray(specs) ? specs : []).filter(
543
+ (s) => s && (s.batches ?? []).length > 0 && Number(s.mtime ?? 0) >= since && !taken.has(String(s.path)),
544
+ )
545
+ if (!candidates.length) return null
546
+ // 一番新しいもの(同じ秒に複数あればパス順で安定させる)
547
+ return [...candidates].sort((a, b) => Number(b.mtime) - Number(a.mtime) || String(a.path).localeCompare(String(b.path)))[0]
548
+ }
549
+
550
+ /**
551
+ * タスク一覧から「起票済みのバッチ ID」を集める(**状態を問わない**)。
552
+ *
553
+ * 完了済み(`done`)を未起票と数えると、バナーが「起票して開始」を出して
554
+ * 同じバッチをもう一度起票してしまう(`specs.launchSpec` がスキップするのは
555
+ * **未完了**の重複だけ)。ここは「タスクが 1 つでもあるか」で数える。
556
+ *
557
+ * @param {Array<{title?: string}>} tasks ボードのタスク
558
+ * @returns {Set<string>} バッチ ID
559
+ */
560
+ export function filedBatchIds(tasks) {
561
+ const out = new Set()
562
+ for (const task of Array.isArray(tasks) ? tasks : []) {
563
+ const m = /^\[([^\]]+)\]/.exec(String(task?.title ?? '').trim())
564
+ if (m && m[1].trim()) out.add(m[1].trim())
565
+ }
566
+ return out
567
+ }
568
+
569
+ /**
570
+ * 未起票の SPEC を数える(A2B の 1 タップ一括起票カード用)。
571
+ * @param {Array<object>} specs `specs.listSpecs` の結果
572
+ * @param {Array<{id: string, title: string, status?: string}>} tasks ボードのタスク
573
+ * @returns {Array<{path: string, title: string, batchCount: number, pendingCount: number, pending: string[], mtime: number}>} 未起票ありの SPEC
574
+ */
575
+ export function pendingSpecs(specs, tasks) {
576
+ const filed = filedBatchIds(tasks)
577
+ const out = []
578
+ for (const spec of Array.isArray(specs) ? specs : []) {
579
+ const batches = (spec?.batches ?? []).filter((b) => b?.id)
580
+ if (!batches.length) continue
581
+ const pending = batches.filter((b) => !filed.has(String(b.id))).map((b) => b.id)
582
+ if (!pending.length) continue
583
+ out.push({
584
+ path: String(spec.path),
585
+ title: String(spec.title ?? spec.path),
586
+ batchCount: batches.length,
587
+ pendingCount: pending.length,
588
+ pending,
589
+ mtime: Number(spec.mtime ?? 0),
590
+ })
591
+ }
592
+ return out.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path))
593
+ }
594
+
595
+ /**
596
+ * 親タスクの状態から「キュー待ち(queued)」と「実行中(running)」を判別する(SPEC V7 §3.1)。
597
+ *
598
+ * `ready` は着手中ではない=キュー待ち。`running` / `claimed` は実行中。
599
+ * 判定できない状態(`blocked` など)は `null`(UI は従来の表示にフォールバック)。
600
+ *
601
+ * @param {unknown} taskStatus 親 `[ARCH]` タスクの status
602
+ * @returns {'queued'|'running'|null} キュー状態
603
+ */
604
+ export function queueStateOf(taskStatus) {
605
+ const s = String(taskStatus ?? '')
606
+ .trim()
607
+ .toLowerCase()
608
+ if (['running', 'claimed', 'in_progress'].includes(s)) return 'running'
609
+ if (['ready', 'todo', 'scheduled', 'blocked'].includes(s)) return 'queued'
610
+ return null
611
+ }
612
+
613
+ /**
614
+ * `[review]` を探すボード(`[job.board, 'mobile']`・重複除去・空文字除外)。SPEC V9 D42。
615
+ * @param {unknown} jobBoard ジョブのボード
616
+ * @returns {string[]} 走査するボード(先頭がジョブ自身のボード)
617
+ */
618
+ export function reviewBoardsFor(jobBoard) {
619
+ const own = String(jobBoard ?? '').trim()
620
+ return [...new Set([own, DEFAULT_REVIEW_BOARD].filter(Boolean))]
621
+ }
622
+
623
+ /**
624
+ * `reviewDir/sheets/` の中で「このジョブが書いた」Round 1 シートを 1 枚選ぶ(SPEC V9 D42)。
625
+ *
626
+ * `spec-<slug>-1.json` のような JSON シートだけを見る(HTML は対象外)。
627
+ * `mtime >= job.startedAt - 猶予` の最新 1 枚を `sheets/<name>` の相対パスで返す。
628
+ *
629
+ * @param {string|null|undefined} reviewDir レビューディレクトリ(`sheets/` の親)
630
+ * @param {{startedAt?: number}} job ジョブ
631
+ * @param {{slackMs?: number}} [opts] 猶予(秒ズレ対策)
632
+ * @returns {string|null} 相対パス(無ければ null)
633
+ */
634
+ export function findRecentSheet(reviewDir, job, { slackMs = SPEC_MTIME_SLACK_MS } = {}) {
635
+ const dir = reviewDir ? path.join(String(reviewDir), 'sheets') : ''
636
+ if (!dir) return null
637
+ let entries = []
638
+ try {
639
+ entries = fs.readdirSync(dir, { withFileTypes: true })
640
+ } catch {
641
+ return null // ディレクトリが無い環境では無害に null
642
+ }
643
+ const since = Number(job?.startedAt ?? 0) - Number(slackMs)
644
+ let best = null
645
+ for (const entry of entries) {
646
+ if (!entry?.isFile?.()) continue
647
+ const name = String(entry.name ?? '')
648
+ if (!/^spec-.+\.json$/i.test(name)) continue
649
+ let mtime = 0
650
+ try {
651
+ mtime = Number(fs.statSync(path.join(dir, name)).mtimeMs)
652
+ } catch {
653
+ continue
654
+ }
655
+ if (mtime < since) continue
656
+ if (!best || mtime > best.mtime) best = { name, mtime }
657
+ }
658
+ return best ? `sheets/${best.name}` : null
659
+ }
660
+
661
+ /**
662
+ * ジョブの現在フェーズ(SPEC V9 D42)。`publicJob().phase` の実体。
663
+ * @param {object} job ジョブ
664
+ * @returns {'spawning'|'round1_sheet'|'awaiting_review'|'round2_spec'|'spec_ready'|'launched'|'failed'} フェーズ
665
+ */
666
+ export function computePhase(job) {
667
+ const status = String(job?.status ?? '').trim()
668
+ if (status === 'failed') return 'failed'
669
+ if (status === 'launched') return 'launched'
670
+ if (status === 'spec_ready') return 'spec_ready'
671
+ if (status === 'awaiting_review') return 'awaiting_review'
672
+ // 一度 Review を通過して回答後に `awaiting_spec` へ戻った = Round 2(SPEC 執筆中)
673
+ if (job?.reviewSeenOnce) return 'round2_spec'
674
+ if (job?.sheetPath) return 'round1_sheet'
675
+ return 'spawning'
676
+ }
677
+
678
+ /**
679
+ * ジョブが停滞しているか(SPEC V9 D42)。
680
+ *
681
+ * Hermes Native は起票後にカンバンタスクが動くので、`running` / `awaiting_spec` のまま
682
+ * `STALLED_AFTER_MS` を超えたら停滞とみなす(`queued` は人が着火待ちなので対象外)。
683
+ *
684
+ * @param {object} job ジョブ
685
+ * @param {number} [at] 現在時刻(ミリ秒)
686
+ * @returns {boolean} 停滞なら true
687
+ */
688
+ export function isJobStalled(job, at = Date.now()) {
689
+ const status = String(job?.status ?? '').trim()
690
+ if (!['running', 'awaiting_spec'].includes(status)) return false
691
+ if (String(job?.queueState ?? '').trim() === 'queued') return false
692
+ const since = Number(job?.startedAt ?? job?.createdAt ?? 0)
693
+ if (!Number.isFinite(since) || since <= 0) return false
694
+ const elapsed = Number(at) - since
695
+ return Number.isFinite(elapsed) && elapsed >= STALLED_AFTER_MS
696
+ }
697
+
698
+ /**
699
+ * 保存するジョブの形(機密を持たない。種は先頭 400 字だけ)。
700
+ * @param {object} job 内部ジョブ
701
+ * @param {{at?: number}} [opts] 現在時刻(`stalled` の算出に使う)
702
+ * @returns {object} 公開用
703
+ */
704
+ export function publicJob(job, { at = Date.now() } = {}) {
705
+ return {
706
+ id: job.id,
707
+ board: job.board,
708
+ status: job.status,
709
+ stage: job.stage ?? job.status,
710
+ runner: job.runner,
711
+ runnerLabel: runnerLabel(job.runner),
712
+ requestedRunner: job.requestedRunner ?? job.runner ?? null,
713
+ fallbackFrom: job.fallbackFrom ?? null,
714
+ fallbackReason: job.fallbackReason ?? null,
715
+ taskId: job.taskId ?? null,
716
+ taskStatus: job.taskStatus ?? null,
717
+ queueState: job.queueState ?? queueStateOf(job.taskStatus),
718
+ executionPolicy: normalizeExecutionPolicy(job.executionPolicy),
719
+ dismissed: Boolean(job.dismissed),
720
+ reviewTaskId: job.reviewTaskId ?? null,
721
+ reviewTitle: job.reviewTitle ?? null,
722
+ reviewBoard: job.reviewBoard ?? null,
723
+ phase: computePhase(job),
724
+ stalled: isJobStalled(job, at),
725
+ sheetPath: job.sheetPath ?? null,
726
+ autoStart: Boolean(job.autoStart),
727
+ seed: String(job.seedText ?? '').slice(0, 400),
728
+ lang: job.lang,
729
+ chat: job.chat ?? null,
730
+ createdAt: job.createdAt,
731
+ startedAt: job.startedAt,
732
+ finishedAt: job.finishedAt ?? null,
733
+ spec: job.spec ?? null,
734
+ completedSpec: job.completedSpec ?? null,
735
+ launched: job.launched ?? null,
736
+ error: job.error ?? null,
737
+ }
738
+ }
739
+
740
+ /**
741
+ * Architect を作る。
742
+ *
743
+ * @param {object} [cfg] 設定(`reviewDir` / `pluginDataDir` / `hermesBin` / `dataDir`)
744
+ * @param {object} [deps] 差し替え(テスト用)
745
+ * @param {Function} [deps.runner] ランナー(`createCliRunner` の形)
746
+ * @param {Function} [deps.listSpecs] SPEC 走査(既定 `specs.listSpecs`)
747
+ * @param {Function} [deps.readTasks] ボードのタスク読み取り
748
+ * @param {Function} [deps.launchSpec] 一括起票(既定 `specs.createSpecs().launchSpec`)
749
+ * @param {Function} [deps.appendReport] `chat-reports.jsonl` 追記
750
+ * @param {Function} [deps.now] 時刻
751
+ * @param {Function} [deps.statSync] ディレクトリ確認
752
+ * @returns {{seed: Function, jobs: Function, getConfig: Function, setConfig: Function, reset: Function}} 操作
753
+ */
754
+ export function createArchitect(cfg = {}, deps = {}) {
755
+ const now = typeof deps.now === 'function' ? deps.now : () => Date.now()
756
+ const runner = deps.runner ?? createCliRunner(cfg)
757
+ const listSpecsFn = deps.listSpecs ?? ((repoPath) => scanSpecs(repoPath))
758
+ const readTasks = deps.readTasks ?? (() => [])
759
+ const statSync = deps.statSync ?? ((p) => fs.statSync(p))
760
+ const report =
761
+ deps.appendReport ??
762
+ ((row) => {
763
+ try {
764
+ return appendChatReport(cfg, row)
765
+ } catch {
766
+ return null // 記録に失敗しても起票や検知は止めない
767
+ }
768
+ })
769
+
770
+ // 一括起票は specs.js の実装を使う(起票・スキップ判定・ラン記録を二重実装しない)
771
+ let launchSpec = deps.launchSpec ?? null
772
+
773
+ /** @type {Map<string, object>} */
774
+ const jobs = new Map()
775
+
776
+ const configPath = cfg.dataDir ? path.join(cfg.dataDir, 'architect-config.json') : null
777
+
778
+ // 破棄したジョブ(リロード・再起動で復活させない)。SPEC V7 §3.1②
779
+ const dismissedPath = cfg.dataDir ? path.join(cfg.dataDir, 'architect-dismissed.json') : null
780
+ /** @type {Set<string>} */
781
+ const dismissedIds = loadDismissed()
782
+
783
+ /**
784
+ * 破棄済みジョブ ID を読む(壊れた JSON・不在は空集合)。
785
+ * @returns {Set<string>} ID 集合
786
+ */
787
+ function loadDismissed() {
788
+ if (!dismissedPath) return new Set()
789
+ try {
790
+ const raw = JSON.parse(fs.readFileSync(dismissedPath, 'utf8'))
791
+ const list = Array.isArray(raw) ? raw : Array.isArray(raw?.ids) ? raw.ids : []
792
+ return new Set(list.map((v) => String(v ?? '').trim()).filter(Boolean))
793
+ } catch {
794
+ return new Set()
795
+ }
796
+ }
797
+
798
+ /**
799
+ * 破棄済みジョブ ID を保存する(最新 `DISMISSED_MAX` 件)。
800
+ * @returns {boolean} 保存できたら true(`dataDir` 未設定ならファイルを持たないので true)
801
+ */
802
+ function saveDismissed() {
803
+ if (!dismissedPath) return true
804
+ const ids = [...dismissedIds].slice(-DISMISSED_MAX)
805
+ try {
806
+ fs.mkdirSync(path.dirname(dismissedPath), { recursive: true })
807
+ fs.writeFileSync(dismissedPath, `${JSON.stringify({ ids }, null, 2)}\n`, { mode: 0o600 })
808
+ return true
809
+ } catch {
810
+ return false // 保存に失敗してもジョブはメモリ上で破棄済みにする(再取得で戻るのは次善)
811
+ }
812
+ }
813
+
814
+ /** ジョブが破棄済みか。 */
815
+ function isDismissed(job) {
816
+ return Boolean(job?.dismissed) || dismissedIds.has(String(job?.id ?? ''))
817
+ }
818
+
819
+ /** ジョブが終端(親 [ARCH] が done / archived)か。 */
820
+ function isTerminal(job) {
821
+ return TERMINAL_TASK_STATUSES.includes(String(job?.status ?? ''))
822
+ }
823
+
824
+ /**
825
+ * 設定(既定 `{runner:'hermes'}`)。壊れた JSON も未知の値も既定へ戻す。
826
+ * @returns {{runner: 'hermes'}} 設定
827
+ */
828
+ function getConfig() {
829
+ if (!configPath) return { runner: DEFAULT_RUNNER }
830
+ try {
831
+ const raw = JSON.parse(fs.readFileSync(configPath, 'utf8'))
832
+ return { runner: sanitizeRunner(raw?.runner) }
833
+ } catch {
834
+ return { runner: DEFAULT_RUNNER }
835
+ }
836
+ }
837
+
838
+ /**
839
+ * ランナーを保存する(**`hermes` 以外は受け付けない**。SPEC V11 D50)。
840
+ * @param {unknown} value ランナー
841
+ * @returns {{ok: boolean, runner?: string, code?: string, error?: string}} 結果
842
+ */
843
+ function setConfig(value) {
844
+ const raw = value?.runner ?? value
845
+ if (!isSupportedRunner(raw)) {
846
+ return { ok: false, code: 'INVALID_RUNNER', error: 'Only the Hermes Native runner is supported' }
847
+ }
848
+ if (configPath) {
849
+ try {
850
+ fs.mkdirSync(path.dirname(configPath), { recursive: true })
851
+ fs.writeFileSync(configPath, `${JSON.stringify({ runner: DEFAULT_RUNNER }, null, 2)}\n`, { mode: 0o600 })
852
+ } catch (e) {
853
+ return { ok: false, code: 'WRITE_FAILED', error: e.message }
854
+ }
855
+ }
856
+ return { ok: true, runner: DEFAULT_RUNNER }
857
+ }
858
+
859
+ /**
860
+ * 仕様の種を撒く(202 で即答し、ランナーは背後で走る)。
861
+ * @param {object} input `{repoPath, board, seedText, runner?, autoStart?, executionPolicy?, chat?, lang?}`
862
+ * @returns {Promise<object>} `{ok, jobId, status, runner, executionPolicy, autoStart}` または `{ok:false, code, error}`
863
+ */
864
+ async function seed(input = {}) {
865
+ const seedText = normalizeSeed(input.seedText)
866
+ if (!seedText) return { ok: false, code: 'INVALID_SEED', error: 'seedText is required' }
867
+
868
+ const board = String(input.board ?? '').trim()
869
+ if (!BOARD_RE.test(board)) return { ok: false, code: 'INVALID_BOARD', error: 'board is invalid' }
870
+
871
+ const repoPath = String(input.repoPath ?? '').trim()
872
+ if (!repoPath || !path.isAbsolute(repoPath)) {
873
+ return { ok: false, code: 'INVALID_REPO', error: 'repoPath must be an absolute path' }
874
+ }
875
+ try {
876
+ if (!statSync(repoPath)?.isDirectory?.()) {
877
+ return { ok: false, code: 'INVALID_REPO', error: 'repoPath is not a directory' }
878
+ }
879
+ } catch {
880
+ return { ok: false, code: 'INVALID_REPO', error: 'repoPath does not exist' }
881
+ }
882
+
883
+ if (!isSupportedRunner(input.runner ?? getConfig().runner)) {
884
+ return { ok: false, code: 'INVALID_RUNNER', error: 'Only the Hermes Native runner is supported' }
885
+ }
886
+ const runnerId = DEFAULT_RUNNER
887
+
888
+ const startedAt = now()
889
+ const executionPolicy = normalizeExecutionPolicy(input.executionPolicy)
890
+ const job = {
891
+ id: makeJobId(startedAt),
892
+ board,
893
+ repoPath,
894
+ status: 'running',
895
+ runner: runnerId,
896
+ requestedRunner: runnerId,
897
+ fallbackFrom: null,
898
+ fallbackReason: null,
899
+ taskId: null,
900
+ taskStatus: null,
901
+ queueState: null,
902
+ executionPolicy,
903
+ dismissed: false,
904
+ reviewTaskId: null,
905
+ reviewTitle: null,
906
+ mode: 'kanban',
907
+ prompt: '',
908
+ autoStart: Boolean(input.autoStart),
909
+ seedText,
910
+ lang: input.lang === 'en' ? 'en' : 'ja',
911
+ chat: input.chat ? String(input.chat).slice(0, 128) : null,
912
+ createdAt: startedAt,
913
+ startedAt,
914
+ finishedAt: null,
915
+ spec: null,
916
+ completedSpec: null,
917
+ launched: null,
918
+ launchStarted: false,
919
+ error: null,
920
+ }
921
+ jobs.set(job.id, job)
922
+ trimJobs()
923
+
924
+ // SPEC V11 D54: 推奨スラッグと既存 SPEC 一覧を先に決めてプロンプトへ入れる
925
+ // (Round 1 の探索ターンとファイル名衝突を減らす)。
926
+ const suggestedSlug = suggestSpecSlug(seedText, job.id)
927
+ const existingSpecs = recentSpecPaths(listSpecsFn, repoPath)
928
+ job.suggestedSlug = suggestedSlug
929
+
930
+ const prompt = buildSeedPrompt({
931
+ jobId: job.id,
932
+ seedText,
933
+ board,
934
+ repoPath,
935
+ autoStart: job.autoStart,
936
+ executionPolicy,
937
+ lang: job.lang,
938
+ suggestedSlug,
939
+ existingSpecs,
940
+ })
941
+ job.prompt = prompt
942
+
943
+ // 背後の実行。落ちてもジョブに理由を残すだけで、呼び出し元は待たない。
944
+ void Promise.resolve()
945
+ .then(() =>
946
+ runner({
947
+ runnerId,
948
+ prompt,
949
+ repoPath,
950
+ board,
951
+ seedText,
952
+ jobId: job.id,
953
+ executionPolicy,
954
+ suggestedSlug,
955
+ existingSpecs,
956
+ }),
957
+ )
958
+ .then(async (res) => {
959
+ job.finishedAt = now()
960
+ const code = typeof res?.code === 'number' ? res.code : 0
961
+ const taskId = res?.taskId ?? parseCreatedTask(res?.stdout)?.id ?? null
962
+ if (code !== 0) {
963
+ // 失敗しても自動で別経路の起票へ切り替えない(二重稼働・重複起票を根絶)。
964
+ // 再試行は UI の明示操作(1 タップ再試行)だけ。
965
+ const reason = String(res?.stderr || res?.stdout || `runner exited with ${code}`).trim()
966
+ job.status = 'failed'
967
+ job.error = reason.slice(0, 600)
968
+ return
969
+ }
970
+ if (taskId) job.taskId = taskId
971
+ job.status = 'awaiting_spec'
972
+ })
973
+ .catch((e) => {
974
+ job.finishedAt = now()
975
+ job.status = 'failed'
976
+ job.error = String(e?.message ?? e).slice(0, 600)
977
+ })
978
+
979
+ return {
980
+ ok: true,
981
+ jobId: job.id,
982
+ status: job.status,
983
+ runner: runnerId,
984
+ executionPolicy,
985
+ autoStart: job.autoStart,
986
+ }
987
+ }
988
+
989
+ /** 古いジョブを落とす(メモリだけの保持)。 */
990
+ function trimJobs() {
991
+ if (jobs.size <= JOBS_MAX) return
992
+ const ordered = [...jobs.values()].sort((a, b) => a.createdAt - b.createdAt)
993
+ while (ordered.length > JOBS_MAX) {
994
+ const old = ordered.shift()
995
+ jobs.delete(old.id)
996
+ }
997
+ }
998
+
999
+ /**
1000
+ * ジョブの進み具合と、完成 SPEC・未起票 SPEC を返す。
1001
+ * @param {{board?: string, repoPath?: string, include?: {repoPath?: string, board?: string}, includeDismissed?: boolean, strictBoard?: boolean}} [query] 絞り込み
1002
+ * `include` はジョブが 1 つも無いボードでも「未起票 SPEC」を数えるための追加走査先
1003
+ * `includeDismissed` は破棄済みジョブも返す(監査・テスト用。既定は除外)
1004
+ * `strictBoard` は選択中ボードと完全一致するジョブだけに絞る(V7 互換。既定はボード横断)
1005
+ * @returns {Promise<object>} `{ok, board, runner, capabilities, jobs, specReady, pending}`
1006
+ */
1007
+ async function jobsFor(query = {}) {
1008
+ const board = String(query.board ?? '').trim()
1009
+ const at = now()
1010
+ // D42: 既定は「アクティブで未破棄なジョブ」をボード・リポジトリ横断で返す。
1011
+ // 別ボードで撒いた種でも進行バーが消えないようにするため(`strictBoard: true` で V7 互換)。
1012
+ const mine = [...jobs.values()]
1013
+ .filter((j) => {
1014
+ const sameBoard = !board || j.board === board
1015
+ const sameRepo = !query.repoPath || j.repoPath === query.repoPath
1016
+ if (query.strictBoard === true) return sameBoard && sameRepo
1017
+ if (sameBoard && sameRepo) return true
1018
+ if (query.includeDismissed) return true
1019
+ return !isDismissed(j) && !isTerminal(j) && ACTIVE_JOB_STATUSES.includes(String(j.status ?? '').trim())
1020
+ })
1021
+ .sort((a, b) => b.createdAt - a.createdAt)
1022
+
1023
+ // リポジトリごとに 1 回だけ SPEC を走査する
1024
+ const specsByRepo = new Map()
1025
+ const specsOf = (repoPath) => {
1026
+ if (!specsByRepo.has(repoPath)) {
1027
+ let list = []
1028
+ try {
1029
+ list = listSpecsFn(repoPath) ?? []
1030
+ } catch {
1031
+ list = []
1032
+ }
1033
+ specsByRepo.set(repoPath, Array.isArray(list) ? list : [])
1034
+ }
1035
+ return specsByRepo.get(repoPath)
1036
+ }
1037
+
1038
+ // 先に「他のジョブが取った SPEC」を集める(新しいジョブが横取りしない)
1039
+ const taken = new Set()
1040
+ for (const job of [...mine].reverse()) {
1041
+ if (job.spec) taken.add(String(job.spec))
1042
+ }
1043
+
1044
+ for (const job of [...mine].reverse()) {
1045
+ if (!['awaiting_spec', 'awaiting_review', 'running'].includes(job.status) || job.spec) continue
1046
+ const found = findJobSpec(job, specsOf(job.repoPath), { taken })
1047
+ if (!found) continue
1048
+ taken.add(String(found.path))
1049
+ job.spec = found.path
1050
+ job.status = 'spec_ready'
1051
+ job.completedSpec = {
1052
+ path: found.path,
1053
+ title: found.title,
1054
+ batchCount: (found.batches ?? []).length,
1055
+ batches: (found.batches ?? []).map((b) => ({ id: b.id, title: b.title, mode: b.mode ?? null })),
1056
+ }
1057
+ report({
1058
+ kind: SPEC_READY_KIND,
1059
+ board: job.board,
1060
+ jobId: job.id,
1061
+ spec: found.path,
1062
+ title: found.title,
1063
+ batchCount: job.completedSpec.batchCount,
1064
+ autoStart: job.autoStart,
1065
+ originSessionId: job.chat,
1066
+ at: now(),
1067
+ })
1068
+ }
1069
+
1070
+ // カンバンのタスク状態をジョブへ写す(`awaiting_review` 検知・failed 同期。SPEC V6 §3.2)
1071
+ const tasksByBoard = new Map()
1072
+ const tasksOf = (slug) => {
1073
+ const key = String(slug ?? '')
1074
+ if (!tasksByBoard.has(key)) {
1075
+ let list = []
1076
+ try {
1077
+ list = readTasks(key) ?? []
1078
+ } catch {
1079
+ list = []
1080
+ }
1081
+ tasksByBoard.set(key, Array.isArray(list) ? list : [])
1082
+ }
1083
+ return tasksByBoard.get(key)
1084
+ }
1085
+
1086
+ // D42: Round 1 の中間シート(review/sheets/spec-*.json)を観測する(phase / sheetPath の材料)。
1087
+ // 早期フェーズのジョブだけ見る(毎ポーリングで全ジョブ分の readdir をしない)。
1088
+ if (cfg.reviewDir) {
1089
+ for (const job of mine) {
1090
+ if (job.sheetPath) continue
1091
+ if (!['running', 'awaiting_spec', 'awaiting_review'].includes(job.status)) continue
1092
+ try {
1093
+ job.sheetPath = findRecentSheet(cfg.reviewDir, job)
1094
+ } catch {
1095
+ job.sheetPath = null
1096
+ }
1097
+ }
1098
+ }
1099
+
1100
+ for (const job of mine) {
1101
+ if (!['running', 'awaiting_spec', 'awaiting_review'].includes(job.status)) continue
1102
+ const tasks = tasksOf(job.board)
1103
+ const self = job.taskId ? tasks.find((t) => t && String(t.id) === String(job.taskId)) ?? null : null
1104
+ job.taskStatus = self?.status ? String(self.status) : null
1105
+ job.queueState = queueStateOf(job.taskStatus)
1106
+ // 親 [ARCH] が終端(done / archived)なら、SPEC 未検知でもジョブを終端にする。
1107
+ // ここを落とすと「仕様書を書いています…」が進行バーに残り続ける(SPEC V7 §3.1②)。
1108
+ if (self && TERMINAL_TASK_STATUSES.includes(String(self.status))) {
1109
+ job.status = String(self.status)
1110
+ job.queueState = null
1111
+ job.reviewTaskId = null
1112
+ job.reviewTitle = null
1113
+ job.reviewBoard = null
1114
+ job.finishedAt = job.finishedAt ?? now()
1115
+ continue
1116
+ }
1117
+ if (self && self.status === 'failed') {
1118
+ job.status = 'failed'
1119
+ job.error = String(self.result || job.error || 'Architect task failed').slice(0, 600)
1120
+ continue
1121
+ }
1122
+ if (job.spec) continue // 完成 SPEC を検知済み(spec_ready / launched)
1123
+ // D42: `[review]` は job.board に加えて `mobile` ボードも探す(他ボード起点の種まき対策)
1124
+ let review = null
1125
+ for (const slug of reviewBoardsFor(job.board)) {
1126
+ const found = findJobReviewTask(job, tasksOf(slug))
1127
+ if (found) {
1128
+ review = { ...found, board: slug }
1129
+ break
1130
+ }
1131
+ }
1132
+ if (review) {
1133
+ job.status = 'awaiting_review'
1134
+ job.reviewTaskId = review.taskId
1135
+ job.reviewTitle = review.title
1136
+ job.reviewBoard = review.board
1137
+ // 一度でも回答待ちを観測した = 以降は Round 2(SPEC 執筆中)として扱う
1138
+ job.reviewSeenOnce = true
1139
+ continue
1140
+ }
1141
+ // 回答が返ってレビューが blocked でなくなったら「仕様書執筆中」へ戻す
1142
+ job.reviewTaskId = null
1143
+ job.reviewTitle = null
1144
+ job.reviewBoard = null
1145
+ if (job.status === 'awaiting_review') job.status = 'awaiting_spec'
1146
+ }
1147
+
1148
+ // 公開表現の `stage`(カンバンタスクが動いている間は running として見せる)
1149
+ for (const job of mine) {
1150
+ job.stage =
1151
+ job.status === 'awaiting_spec' && ['running', 'claimed'].includes(String(job.taskStatus ?? ''))
1152
+ ? 'running'
1153
+ : job.status
1154
+ }
1155
+
1156
+ // 進行バーに出すジョブ(破棄済み・終端は既定で落とす)。SPEC V7 §3.1②
1157
+ const visible = mine.filter((job) => !isTerminal(job) && (query.includeDismissed || !isDismissed(job)))
1158
+
1159
+ // autoStart: 完成 SPEC の未起票バッチを 1 回だけ起票する
1160
+ for (const job of visible) {
1161
+ if (!job.autoStart || job.status !== 'spec_ready' || job.launchStarted) continue
1162
+ job.launchStarted = true
1163
+ let tasks = []
1164
+ try {
1165
+ tasks = readTasks(job.board) ?? []
1166
+ } catch {
1167
+ tasks = []
1168
+ }
1169
+ const spec = specsOf(job.repoPath).find((s) => s.path === job.spec) ?? null
1170
+ const pending = spec ? pendingSpecs([spec], tasks) : []
1171
+ if (!spec || !pending.length) {
1172
+ // 既に起票済み(別経路で人が起票した)なら成功と同じ扱いで閉じる
1173
+ job.status = 'launched'
1174
+ job.launched = { ok: true, created: [], skipped: [], failed: [], reason: 'nothing-pending' }
1175
+ continue
1176
+ }
1177
+ try {
1178
+ if (!launchSpec) {
1179
+ const { createSpecs } = await import('./specs.js')
1180
+ launchSpec = createSpecs(cfg, { tasks: readTasks }).launchSpec
1181
+ }
1182
+ const res = await launchSpec({
1183
+ repoPath: job.repoPath,
1184
+ board: job.board,
1185
+ specRelPath: job.spec,
1186
+ batchIds: pending[0].pending,
1187
+ chat: job.chat ?? undefined,
1188
+ })
1189
+ job.status = 'launched'
1190
+ job.launched = {
1191
+ ok: Boolean(res?.ok),
1192
+ runId: res?.runId ?? null,
1193
+ created: (res?.created ?? []).map((c) => ({ id: c.id, taskId: c.taskId ?? null })),
1194
+ skipped: (res?.skipped ?? []).map((s) => ({ id: s.id, taskId: s.taskId ?? null })),
1195
+ failed: res?.failed ?? [],
1196
+ error: res?.error ?? null,
1197
+ }
1198
+ report({
1199
+ kind: SPEC_LAUNCH_KIND,
1200
+ board: job.board,
1201
+ jobId: job.id,
1202
+ spec: job.spec,
1203
+ created: job.launched.created.length,
1204
+ skipped: job.launched.skipped.length,
1205
+ failed: job.launched.failed.length,
1206
+ autoStart: true,
1207
+ originSessionId: job.chat,
1208
+ at: now(),
1209
+ })
1210
+ } catch (e) {
1211
+ job.status = 'spec_ready'
1212
+ job.launched = { ok: false, created: [], skipped: [], failed: [], error: String(e?.message ?? e).slice(0, 400) }
1213
+ }
1214
+ }
1215
+
1216
+ // 未起票の SPEC(Seed と関係なくても、新しく置かれた SPEC を拾う)
1217
+ const pending = []
1218
+ const seenRepo = new Set()
1219
+ const scans = visible.map((job) => ({ repoPath: job.repoPath, board: job.board }))
1220
+ if (query.include?.repoPath) scans.push({ repoPath: query.include.repoPath, board: query.include.board ?? board })
1221
+ for (const scan of scans) {
1222
+ if (seenRepo.has(scan.repoPath)) continue
1223
+ seenRepo.add(scan.repoPath)
1224
+ let tasks = []
1225
+ try {
1226
+ tasks = readTasks(scan.board) ?? []
1227
+ } catch {
1228
+ tasks = []
1229
+ }
1230
+ for (const row of pendingSpecs(specsOf(scan.repoPath), tasks)) {
1231
+ pending.push({ ...row, board: scan.board, repoPath: scan.repoPath })
1232
+ }
1233
+ }
1234
+
1235
+ const specReady = visible
1236
+ .filter((j) => j.completedSpec && (j.status === 'spec_ready' || j.status === 'launched'))
1237
+ .map((j) => ({
1238
+ jobId: j.id,
1239
+ board: j.board,
1240
+ repoPath: j.repoPath,
1241
+ spec: j.completedSpec.path,
1242
+ title: j.completedSpec.title,
1243
+ batchCount: j.completedSpec.batchCount,
1244
+ batches: j.completedSpec.batches,
1245
+ autoStart: j.autoStart,
1246
+ launched: j.status === 'launched',
1247
+ launchedCount: j.launched?.created?.length ?? 0,
1248
+ }))
1249
+
1250
+ return {
1251
+ ok: true,
1252
+ board: board || null,
1253
+ runner: getConfig().runner,
1254
+ jobs: visible.map((job) => publicJob(job, { at })),
1255
+ specReady,
1256
+ pending,
1257
+ }
1258
+ }
1259
+
1260
+ /**
1261
+ * ジョブを破棄する(サーバー側に永続化し、リロード・再起動で復活させない)。SPEC V7 §3.1②。
1262
+ *
1263
+ * 破棄は**監査のための記録**であってタスクの削除ではない(カンバン側は触らない)。
1264
+ * @param {unknown} jobId ジョブ ID
1265
+ * @returns {{ok: boolean, jobId?: string, persisted?: boolean, code?: string, error?: string}} 結果
1266
+ */
1267
+ function dismiss(jobId) {
1268
+ const id = String(jobId ?? '').trim()
1269
+ if (!id) return { ok: false, code: 'INVALID_JOB_ID', error: 'jobId is required' }
1270
+ const job = jobs.get(id) ?? null
1271
+ if (!job && !dismissedIds.has(id)) return { ok: false, code: 'JOB_NOT_FOUND', error: 'job not found' }
1272
+ if (job) {
1273
+ job.dismissed = true
1274
+ job.dismissedAt = now()
1275
+ }
1276
+ dismissedIds.add(id)
1277
+ trimDismissed()
1278
+ const persisted = saveDismissed() && dismissedPath !== null
1279
+ return { ok: true, jobId: id, persisted }
1280
+ }
1281
+
1282
+ /** 破棄 ID の保持数を上限へ丸める(古いものから落とす)。 */
1283
+ function trimDismissed() {
1284
+ while (dismissedIds.size > DISMISSED_MAX) {
1285
+ const oldest = dismissedIds.values().next().value
1286
+ if (oldest == null) break
1287
+ dismissedIds.delete(oldest)
1288
+ }
1289
+ }
1290
+
1291
+ /** テスト用にジョブを捨てる。 */
1292
+ function reset() {
1293
+ jobs.clear()
1294
+ dismissedIds.clear()
1295
+ }
1296
+
1297
+ return { seed, jobs: jobsFor, dismiss, getConfig, setConfig, reset }
1298
+ }