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.
- package/LICENSE +21 -0
- package/README.ja.md +419 -0
- package/README.md +428 -2
- package/__init__.py +15 -0
- package/apps/bridge/src/api-errors.js +165 -0
- package/apps/bridge/src/architect.js +1298 -0
- package/apps/bridge/src/auth.js +202 -0
- package/apps/bridge/src/capabilities.js +256 -0
- package/apps/bridge/src/capture.js +145 -0
- package/apps/bridge/src/chat-profile.js +95 -0
- package/apps/bridge/src/config.js +73 -0
- package/apps/bridge/src/discord.js +89 -0
- package/apps/bridge/src/gitinfo.js +211 -0
- package/apps/bridge/src/hermes.js +97 -0
- package/apps/bridge/src/inbox.js +347 -0
- package/apps/bridge/src/kanban.js +361 -0
- package/apps/bridge/src/lang.js +60 -0
- package/apps/bridge/src/live.js +285 -0
- package/apps/bridge/src/memos.js +150 -0
- package/apps/bridge/src/ops.js +201 -0
- package/apps/bridge/src/pair-codes.js +125 -0
- package/apps/bridge/src/pipeline-optimizer.js +513 -0
- package/apps/bridge/src/pipeline-watcher.js +1022 -0
- package/apps/bridge/src/qr.js +808 -0
- package/apps/bridge/src/repos.js +544 -0
- package/apps/bridge/src/review-watcher.js +271 -0
- package/apps/bridge/src/review.js +1749 -0
- package/apps/bridge/src/search.js +162 -0
- package/apps/bridge/src/server.js +1745 -0
- package/apps/bridge/src/snippets.js +373 -0
- package/apps/bridge/src/specs.js +806 -0
- package/apps/bridge/src/tail.js +28 -0
- package/apps/bridge/src/telemetry.js +667 -0
- package/apps/bridge/src/term-snippets.js +228 -0
- package/apps/bridge/src/transcript.js +231 -0
- package/apps/bridge/src/usage.js +294 -0
- package/apps/bridge/src/workerFeed.js +72 -0
- package/apps/dashboard/index.js +2014 -0
- package/apps/dashboard/manifest.json +14 -0
- package/apps/dashboard/pilot_dashboard.py +1466 -0
- package/apps/dashboard/plugin_api.py +237 -0
- package/apps/dashboard/plugin_init.py +15 -0
- package/apps/dashboard/style.css +928 -0
- package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
- package/apps/web/dist/assets/TermPane-q4f5Zu0I.js +12 -0
- package/apps/web/dist/assets/index-BzUof8lw.js +94 -0
- package/apps/web/dist/assets/index-DwZdbPU7.css +1 -0
- package/apps/web/dist/favicon.ico +0 -0
- package/apps/web/dist/icon-180-v6.png +0 -0
- package/apps/web/dist/icon-192-v6.png +0 -0
- package/apps/web/dist/icon-512-v6.png +0 -0
- package/apps/web/dist/icon-maskable-192-v6.png +0 -0
- package/apps/web/dist/icon-maskable-512-v6.png +0 -0
- package/apps/web/dist/icon-v6.svg +15 -0
- package/apps/web/dist/index.html +21 -0
- package/apps/web/dist/manifest.webmanifest +49 -0
- package/apps/web/dist/sw.js +69 -0
- package/bin/hermes-pilot.mjs +964 -0
- package/dashboard/dist/index.js +2014 -0
- package/dashboard/dist/style.css +928 -0
- package/dashboard/manifest.json +14 -0
- package/dashboard/pilot_dashboard.py +1466 -0
- package/dashboard/plugin_api.py +237 -0
- package/package.json +75 -4
- package/plugin.json +70 -0
- package/plugin.yaml +4 -0
- package/scripts/deploy.mjs +58 -0
- package/scripts/migrate-to-hermes-pilot.mjs +472 -0
- package/scripts/postinstall.mjs +32 -0
- package/scripts/sync-dashboard.mjs +98 -0
- package/skills/annotation/SKILL.md +138 -0
- package/skills/quick-review/SKILL.md +200 -0
- package/skills/quick-review/assets/sheet-template.html +175 -0
- package/skills/spec-architect/SKILL.md +226 -0
|
@@ -0,0 +1,806 @@
|
|
|
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
|
+
/**
|
|
98
|
+
* 抽象ロールの語彙(D60)。公開コードは**この 4 つだけ**を知り、実モデル名は知らない
|
|
99
|
+
* (プロファイルメモリの割当表が実モデルを決める)。
|
|
100
|
+
*/
|
|
101
|
+
export const ABSTRACT_ROLES = ['role:planner', 'role:builder', 'role:visual-reviewer', 'role:decision-framer']
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* バッチ本文の推奨ロール宣言行(`- **Recommended Role**: \`role:builder\`` / `- **推奨ロール**: role:planner`)。
|
|
105
|
+
* バックティック・大小文字・全角コロンを許容する。
|
|
106
|
+
*/
|
|
107
|
+
export const RECOMMENDED_ROLE_RE = /^[-*]?\s*\*\*\s*(?:Recommended Role|推奨ロール)\s*\*\*\s*[::]\s*(.+)$/im
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 推奨ロール表記を正規化する(未知・未宣言は `null`)。
|
|
111
|
+
*
|
|
112
|
+
* `role:` 接頭辞の有無、バックティック、前後の空白・句読点を吸収する。
|
|
113
|
+
* 抽象ロール 4 つ以外は**推測せず** `null`(後方互換)。
|
|
114
|
+
*
|
|
115
|
+
* @param {unknown} raw `role:builder` / `builder` / `` `role:planner` `` など
|
|
116
|
+
* @returns {'role:planner'|'role:builder'|'role:visual-reviewer'|'role:decision-framer'|null} 正規化したロール
|
|
117
|
+
*/
|
|
118
|
+
export function normalizeRecommendedRole(raw) {
|
|
119
|
+
const text = String(raw ?? '')
|
|
120
|
+
.replace(/[`'"「」]/g, '')
|
|
121
|
+
.trim()
|
|
122
|
+
.toLowerCase()
|
|
123
|
+
if (!text) return null
|
|
124
|
+
// 行末に説明が続く場合(`role:builder — 通常実装`)は最初の語だけを見る。
|
|
125
|
+
const token = text.split(/[\s,;/|、。]+/)[0].replace(/^role\s*[::]\s*/, '')
|
|
126
|
+
const role = `role:${token}`
|
|
127
|
+
return ABSTRACT_ROLES.includes(role) ? role : null
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* バッチ本文から推奨ロールを読む(未宣言は `null`=後方互換)。
|
|
132
|
+
*
|
|
133
|
+
* @param {string[]|string} section バッチ本文の行(または本文)
|
|
134
|
+
* @returns {'role:planner'|'role:builder'|'role:visual-reviewer'|'role:decision-framer'|null} ロール
|
|
135
|
+
*/
|
|
136
|
+
export function extractRecommendedRole(section) {
|
|
137
|
+
const text = Array.isArray(section) ? section.join('\n') : String(section ?? '')
|
|
138
|
+
const m = RECOMMENDED_ROLE_RE.exec(text)
|
|
139
|
+
return m ? normalizeRecommendedRole(m[1]) : null
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** モード別の行動契約(`buildTaskBody` が本文末尾へ注入する)。 */
|
|
143
|
+
export const MODE_CONTRACTS = {
|
|
144
|
+
'zero-stop': [
|
|
145
|
+
'- Do not ask confirmation questions in chat.',
|
|
146
|
+
'- Repair autonomously until `npm run verify` (tests, build, checks) passes, then mark the task done.',
|
|
147
|
+
'- Only when a design contradiction is unresolvable, file a `quick-review` sheet and block on it.',
|
|
148
|
+
],
|
|
149
|
+
'fast-track-review': [
|
|
150
|
+
'- 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.',
|
|
151
|
+
'- Everything else proceeds without asking: implement, run `npm run verify`, then mark the task done.',
|
|
152
|
+
],
|
|
153
|
+
'visual-gate': [
|
|
154
|
+
'- After implementing, run `npm run deploy` and verify the real screen at `390×844` and `820×1180`; capture the screenshots.',
|
|
155
|
+
'- If the rendered result differs from the intent, file an `annotation` review (screenshot + marks) and wait for it.',
|
|
156
|
+
'- `npm run verify` must pass before you mark the task done.',
|
|
157
|
+
],
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* モード別の行動契約ブロック(`[Hermes Pilot Execution Contract]`)を組み立てる。
|
|
162
|
+
*
|
|
163
|
+
* モード未宣言でも `recommendedRole` があれば契約を出す(ロール指針だけは届ける)。
|
|
164
|
+
* `recommendedRole` 指定時・`visual-gate` のときは、ネイティブ `delegate_task` +
|
|
165
|
+
* フォールバックと外部 AI CLI 禁止を 2 行だけ添える(D61 / D63)。
|
|
166
|
+
*
|
|
167
|
+
* @param {string} mode 正規化済みモード
|
|
168
|
+
* @param {{recommendedRole?: string|null}} [opts] 推奨ロール(未宣言は `null`)
|
|
169
|
+
* @returns {string} 本文末尾に足すブロック(モードもロールも無ければ空文字=後方互換)
|
|
170
|
+
*/
|
|
171
|
+
export function buildExecutionContract(mode, { recommendedRole = null } = {}) {
|
|
172
|
+
const key = normalizeExecutionMode(mode)
|
|
173
|
+
const role = normalizeRecommendedRole(recommendedRole)
|
|
174
|
+
const gate = key === 'visual-gate'
|
|
175
|
+
if (!key && !role) return ''
|
|
176
|
+
const rules = key ? (MODE_CONTRACTS[key] ?? []) : []
|
|
177
|
+
|
|
178
|
+
const delegation = []
|
|
179
|
+
if (role) {
|
|
180
|
+
delegation.push(
|
|
181
|
+
`- Recommended role: \`${role}\` — resolve it against the profile's abstract-role table before starting.`,
|
|
182
|
+
)
|
|
183
|
+
} else if (gate) {
|
|
184
|
+
delegation.push(
|
|
185
|
+
'- Recommended role: `role:visual-reviewer` — delegate screenshot / annotated-image review through native delegation.',
|
|
186
|
+
)
|
|
187
|
+
}
|
|
188
|
+
if (role || gate) {
|
|
189
|
+
delegation.push(
|
|
190
|
+
'- Delegate only through Hermes native delegation; on error, rate limit, timeout or an unsupported model, continue down the fallback chain instead of blocking.',
|
|
191
|
+
'- Never launch an external AI CLI as a subprocess (no wrapped CLI runs); native providers only.',
|
|
192
|
+
)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return [
|
|
196
|
+
'',
|
|
197
|
+
CONTRACT_HEADER,
|
|
198
|
+
'',
|
|
199
|
+
...(key ? [`Mode: ${key}`, ''] : []),
|
|
200
|
+
'This task was filed by the Hermes Pilot Spec Launchpad. The contract below overrides any habit of asking first.',
|
|
201
|
+
...rules,
|
|
202
|
+
...delegation,
|
|
203
|
+
'- Finish with a short report: what changed, the verification command and its exit code, and what is still unverified.',
|
|
204
|
+
].join('\n')
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** タイトル行(`# …`)。 */
|
|
208
|
+
const TITLE_RE = /^#\s+(.+?)\s*$/
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 仕様書 1 枚を解析してタイトルとバッチを返す(純粋関数)。
|
|
212
|
+
*
|
|
213
|
+
* @param {string} text Markdown
|
|
214
|
+
* @returns {{title: string, batches: Array<{id: string, title: string, objective: string, section: string}>, valid: boolean}} 解析結果
|
|
215
|
+
*/
|
|
216
|
+
export function parseSpec(text) {
|
|
217
|
+
const lines = String(text ?? '').split(/\r?\n/)
|
|
218
|
+
let title = ''
|
|
219
|
+
for (const line of lines) {
|
|
220
|
+
const m = TITLE_RE.exec(line)
|
|
221
|
+
if (m) {
|
|
222
|
+
title = m[1]
|
|
223
|
+
break
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** @type {Array<{id: string, title: string, objective: string, section: string}>} */
|
|
228
|
+
const batches = []
|
|
229
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
230
|
+
const m = BATCH_HEADING_RE.exec(lines[i])
|
|
231
|
+
if (!m || !BATCH_ID_RE.test(m[1])) continue
|
|
232
|
+
// 同じ ID が 2 回出たら最初のものを採る(目次・参照の重複見出し対策)
|
|
233
|
+
if (batches.some((b) => b.id === m[1])) continue
|
|
234
|
+
let end = lines.length
|
|
235
|
+
for (let j = i + 1; j < lines.length; j += 1) {
|
|
236
|
+
if (SECTION_END_RE.test(lines[j])) {
|
|
237
|
+
end = j
|
|
238
|
+
break
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
const body = lines.slice(i + 1, end)
|
|
242
|
+
batches.push({
|
|
243
|
+
id: m[1],
|
|
244
|
+
title: m[2].trim(),
|
|
245
|
+
objective: extractObjective(body),
|
|
246
|
+
// 実行モード(未宣言の過去 SPEC は null=後方互換)
|
|
247
|
+
mode: extractExecutionMode(body),
|
|
248
|
+
// 推奨ロール(未宣言は null。抽象ロール 4 つ以外も null に正規化する)
|
|
249
|
+
recommendedRole: extractRecommendedRole(body),
|
|
250
|
+
// 末尾の区切り線(`---`)は本文に含めない
|
|
251
|
+
section: trimTrailingRule(body.join('\n')),
|
|
252
|
+
})
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return { title, batches, valid: Boolean(title) || batches.length > 0 }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* 抜粋から「目的」だけ取り出す。無ければ最初の意味のある行。
|
|
260
|
+
* @param {string[]} lines セクションの行
|
|
261
|
+
* @returns {string} 目的(無ければ空文字)
|
|
262
|
+
*/
|
|
263
|
+
function extractObjective(lines) {
|
|
264
|
+
for (const line of lines) {
|
|
265
|
+
const m = OBJECTIVE_RE.exec(line)
|
|
266
|
+
if (m) return m[1].trim()
|
|
267
|
+
}
|
|
268
|
+
for (const line of lines) {
|
|
269
|
+
const t = line.trim()
|
|
270
|
+
if (!t || t.startsWith('#') || t.startsWith('|') || t === '---') continue
|
|
271
|
+
return t.replace(/^[-*]\s*/, '').slice(0, 200)
|
|
272
|
+
}
|
|
273
|
+
return ''
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 末尾の区切り線と空行を落とす。
|
|
278
|
+
* @param {string} text 本文
|
|
279
|
+
* @returns {string} 整形後
|
|
280
|
+
*/
|
|
281
|
+
function trimTrailingRule(text) {
|
|
282
|
+
const lines = String(text ?? '').split('\n')
|
|
283
|
+
while (lines.length && (/^\s*$/.test(lines[lines.length - 1]) || /^\s*-{3,}\s*$/.test(lines[lines.length - 1]))) {
|
|
284
|
+
lines.pop()
|
|
285
|
+
}
|
|
286
|
+
return lines.join('\n').trim()
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* リポジトリ内の SPEC を走査する。
|
|
291
|
+
*
|
|
292
|
+
* @param {string} repoPath リポジトリの絶対パス
|
|
293
|
+
* @param {{readdir?: Function, stat?: Function, read?: Function}} [deps] 差し替え(テスト用)
|
|
294
|
+
* @returns {Array<{path: string, title: string, mtime: number, batches: Array<object>, valid: boolean}>} mtime の新しい順
|
|
295
|
+
*/
|
|
296
|
+
export function listSpecs(repoPath, deps = {}) {
|
|
297
|
+
const readdir = deps.readdir ?? ((dir) => fs.readdirSync(dir))
|
|
298
|
+
const stat = deps.stat ?? ((file) => fs.statSync(file))
|
|
299
|
+
const read = deps.read ?? ((file) => fs.readFileSync(file, 'utf8'))
|
|
300
|
+
const root = path.resolve(String(repoPath ?? ''))
|
|
301
|
+
if (!root) return []
|
|
302
|
+
|
|
303
|
+
const out = []
|
|
304
|
+
const seen = new Set()
|
|
305
|
+
for (const dir of SPEC_DIRS) {
|
|
306
|
+
const abs = dir ? path.join(root, dir) : root
|
|
307
|
+
let names = []
|
|
308
|
+
try {
|
|
309
|
+
names = readdir(abs)
|
|
310
|
+
} catch {
|
|
311
|
+
continue
|
|
312
|
+
}
|
|
313
|
+
for (const name of names) {
|
|
314
|
+
if (!SPEC_FILE_RE.test(name)) continue
|
|
315
|
+
const file = path.join(abs, name)
|
|
316
|
+
let st
|
|
317
|
+
try {
|
|
318
|
+
st = stat(file)
|
|
319
|
+
} catch {
|
|
320
|
+
continue
|
|
321
|
+
}
|
|
322
|
+
// ディレクトリ(`SPEC-dir.md/` のような変な名前)は無視する
|
|
323
|
+
if (typeof st?.isFile === 'function' && !st.isFile()) continue
|
|
324
|
+
const rel = path.relative(root, file).split(path.sep).join('/')
|
|
325
|
+
if (seen.has(rel)) continue
|
|
326
|
+
let text = ''
|
|
327
|
+
try {
|
|
328
|
+
text = String(read(file))
|
|
329
|
+
} catch {
|
|
330
|
+
continue
|
|
331
|
+
}
|
|
332
|
+
const parsed = parseSpec(text)
|
|
333
|
+
seen.add(rel)
|
|
334
|
+
out.push({
|
|
335
|
+
path: rel,
|
|
336
|
+
title: parsed.title || name.replace(/\.md$/i, ''),
|
|
337
|
+
mtime: Number(st?.mtimeMs ?? st?.mtime ?? 0),
|
|
338
|
+
batches: parsed.batches,
|
|
339
|
+
valid: parsed.valid,
|
|
340
|
+
})
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
return out.sort((a, b) => b.mtime - a.mtime || a.path.localeCompare(b.path))
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* 起票するタスクのタイトル(`[<BatchID>] <BatchTitle>`)。
|
|
349
|
+
* @param {{id: string, title: string}} batch バッチ
|
|
350
|
+
* @returns {string} タイトル
|
|
351
|
+
*/
|
|
352
|
+
export function buildTaskTitle(batch) {
|
|
353
|
+
return `[${batch?.id ?? ''}] ${batch?.title ?? ''}`.trim().slice(0, 200)
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* 起票するタスクの本文(spec パス・target・抜粋・受入条件)。
|
|
358
|
+
*
|
|
359
|
+
* @param {{specRelPath: string, repoPath: string, board: string, batch: {id: string, title: string, objective: string, section: string}, chat?: string}} input 入力
|
|
360
|
+
* @returns {string} 本文
|
|
361
|
+
*/
|
|
362
|
+
export function buildTaskBody({ specRelPath, repoPath, board, batch, chat }) {
|
|
363
|
+
const chatId = sanitizeSpecChat(chat)
|
|
364
|
+
const mode = normalizeExecutionMode(batch?.mode)
|
|
365
|
+
const head = [
|
|
366
|
+
`Spec: ${specRelPath}`,
|
|
367
|
+
`Target: ${repoPath}`,
|
|
368
|
+
`Board: ${board}`,
|
|
369
|
+
`Batch: ${batch?.id ?? ''} — ${batch?.title ?? ''}`,
|
|
370
|
+
...(chatId ? [`Chat: ${chatId}`] : []),
|
|
371
|
+
...(mode ? [`Mode: ${mode}`] : []),
|
|
372
|
+
'',
|
|
373
|
+
'## 目的',
|
|
374
|
+
'',
|
|
375
|
+
batch?.objective || '(バッチ本文の抜粋を参照)',
|
|
376
|
+
'',
|
|
377
|
+
'## 抜粋(受入条件 / Verify を含む)',
|
|
378
|
+
'',
|
|
379
|
+
].join('\n')
|
|
380
|
+
// 契約ブロックは**末尾に必ず残す**(抜粋だけを切り詰める)。6000 字上限で契約が消えると
|
|
381
|
+
// 自走の保証が壊れるため、順序は「見出し → 抜粋 → 契約」で固定する。
|
|
382
|
+
const contract = buildExecutionContract(mode, { recommendedRole: batch?.recommendedRole })
|
|
383
|
+
const room = Math.max(0, BODY_MAX - head.length - contract.length)
|
|
384
|
+
const section = String(batch?.section ?? '').slice(0, room)
|
|
385
|
+
return `${head}${section}${contract}`.slice(0, BODY_MAX)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* 既存タスクの中に同じバッチの未完了タスクがあるか。
|
|
390
|
+
*
|
|
391
|
+
* @param {Array<{title?: string, status?: string, id?: string}>} tasks 同じボードのタスク
|
|
392
|
+
* @param {string} batchId バッチ ID
|
|
393
|
+
* @returns {{id: string, title: string, status: string}|null} 見つかった未完了タスク
|
|
394
|
+
*/
|
|
395
|
+
export function findOpenBatchTask(tasks, batchId) {
|
|
396
|
+
const want = `[${String(batchId ?? '').trim()}]`
|
|
397
|
+
if (!want || want === '[]') return null
|
|
398
|
+
for (const t of Array.isArray(tasks) ? tasks : []) {
|
|
399
|
+
if (!t) continue
|
|
400
|
+
if (CLOSED_STATUSES.has(String(t.status ?? ''))) continue
|
|
401
|
+
if (!String(t.title ?? '').trim().startsWith(want)) continue
|
|
402
|
+
return { id: String(t.id ?? ''), title: String(t.title ?? ''), status: String(t.status ?? '') }
|
|
403
|
+
}
|
|
404
|
+
return null
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* `repoPath` 配下に収まる形で相対パスを解決する(`../` で外へ出る指定は拒否)。
|
|
409
|
+
*
|
|
410
|
+
* @param {string} repoPath リポジトリの絶対パス
|
|
411
|
+
* @param {string} relPath 相対パス
|
|
412
|
+
* @returns {string} 絶対パス
|
|
413
|
+
* @throws {Error} 不正なパス(statusCode 400)
|
|
414
|
+
*/
|
|
415
|
+
export function resolveSpecPath(repoPath, relPath) {
|
|
416
|
+
const root = path.resolve(String(repoPath ?? ''))
|
|
417
|
+
const rel = String(relPath ?? '').trim()
|
|
418
|
+
if (!rel) throw new ApiError('SPEC_PATH_REQUIRED', {}, 400)
|
|
419
|
+
if (path.isAbsolute(rel)) throw new ApiError('SPEC_PATH_NOT_RELATIVE', {}, 400)
|
|
420
|
+
const abs = path.resolve(root, rel)
|
|
421
|
+
if (abs !== root && !abs.startsWith(root + path.sep)) {
|
|
422
|
+
throw new ApiError('SPEC_PATH_OUTSIDE', {}, 400)
|
|
423
|
+
}
|
|
424
|
+
return abs
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** 本文取得の上限(256KB)。超えた分は切り詰め、`truncated: true` で知らせる。 */
|
|
428
|
+
export const SPEC_CONTENT_MAX = 256 * 1024
|
|
429
|
+
|
|
430
|
+
/** 本文として読める拡張子(`.md` のみ)。 */
|
|
431
|
+
const MARKDOWN_RE = /\.md$/i
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* 1 枚の SPEC の全文を読む(リポジトリ境界内・`.md` のみ・256KB 上限)。
|
|
435
|
+
*
|
|
436
|
+
* パスの検証は `resolveSpecPath` に任せる(`../` や絶対パスは 400)。
|
|
437
|
+
* 上限で切り詰めたときは `truncated: true` を立て、`markdown` は 256KB までに収める
|
|
438
|
+
* (UTF-8 の途中で切れた 1 文字は落とす=壊れた文字を混ぜない)。
|
|
439
|
+
*
|
|
440
|
+
* @param {string} repoPath リポジトリの絶対パス
|
|
441
|
+
* @param {string} specRelPath リポジトリからの相対パス(`docs/SPEC-….md`)
|
|
442
|
+
* @returns {{ok: true, path: string, title: string, mtime: number, batchCount: number, truncated: boolean, markdown: string, bytes: number}} 本文
|
|
443
|
+
* @throws {ApiError} 不正パス(400)/非 `.md`(400)/未検出・読めない(404)
|
|
444
|
+
*/
|
|
445
|
+
export function readSpecContent(repoPath, specRelPath) {
|
|
446
|
+
const rel = String(specRelPath ?? '').trim().split(path.sep).join('/')
|
|
447
|
+
const abs = resolveSpecPath(repoPath, rel)
|
|
448
|
+
if (!MARKDOWN_RE.test(abs)) throw new ApiError('SPEC_NOT_MARKDOWN', { path: rel }, 400)
|
|
449
|
+
|
|
450
|
+
let st
|
|
451
|
+
try {
|
|
452
|
+
st = fs.statSync(abs)
|
|
453
|
+
} catch {
|
|
454
|
+
throw new ApiError('SPEC_READ_FAILED', { path: rel }, 404)
|
|
455
|
+
}
|
|
456
|
+
if (typeof st?.isFile === 'function' && !st.isFile()) {
|
|
457
|
+
throw new ApiError('SPEC_READ_FAILED', { path: rel }, 404)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
let buf
|
|
461
|
+
try {
|
|
462
|
+
buf = fs.readFileSync(abs)
|
|
463
|
+
} catch {
|
|
464
|
+
throw new ApiError('SPEC_READ_FAILED', { path: rel }, 404)
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
const truncated = buf.length > SPEC_CONTENT_MAX
|
|
468
|
+
let markdown = (truncated ? buf.subarray(0, SPEC_CONTENT_MAX) : buf).toString('utf8')
|
|
469
|
+
// 上限で切れた位置が UTF-8 の途中だと U+FFFD が末尾に残る。1 文字だけ落とす。
|
|
470
|
+
if (truncated && markdown.endsWith('\uFFFD')) markdown = markdown.slice(0, -1)
|
|
471
|
+
|
|
472
|
+
const parsed = parseSpec(markdown)
|
|
473
|
+
return {
|
|
474
|
+
ok: true,
|
|
475
|
+
path: rel,
|
|
476
|
+
title: parsed.title || path.basename(abs).replace(/\.md$/i, ''),
|
|
477
|
+
mtime: Number(st?.mtimeMs ?? st?.mtime ?? 0),
|
|
478
|
+
batchCount: parsed.batches.length,
|
|
479
|
+
truncated,
|
|
480
|
+
markdown,
|
|
481
|
+
// 実際に返した本文のバイト数(PWA が「切り詰め」を出せるように)
|
|
482
|
+
bytes: Buffer.byteLength(markdown, 'utf8'),
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* 起票元チャット ID をサニタイズする(書式に合わなければ空=`Chat:` 行を書かない)。
|
|
488
|
+
*
|
|
489
|
+
* @param {unknown} raw 入力(セッション ID 等)
|
|
490
|
+
* @returns {string} 安全な ID(無効なら空文字)
|
|
491
|
+
*/
|
|
492
|
+
export function sanitizeSpecChat(raw) {
|
|
493
|
+
const s = String(raw ?? '').trim()
|
|
494
|
+
return SPEC_CHAT_RE.test(s) ? s : ''
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* `pipeline-runs.json` のパス(レビューディレクトリ配下。`review-watcher` と同じ解決規則)。
|
|
499
|
+
*
|
|
500
|
+
* @param {object} cfg ブリッジ設定(`reviewDir` / `pluginDataDir` / `kanbanRoot`)
|
|
501
|
+
* @returns {string} 絶対パス
|
|
502
|
+
*/
|
|
503
|
+
export function runsPathFor(cfg = {}) {
|
|
504
|
+
const root =
|
|
505
|
+
cfg.reviewDir ??
|
|
506
|
+
path.join(
|
|
507
|
+
cfg.pluginDataDir ?? path.join(cfg.kanbanRoot ?? '.', '..', 'plugin-data', 'hermes-pilot'),
|
|
508
|
+
'review',
|
|
509
|
+
)
|
|
510
|
+
return path.join(root, 'pipeline-runs.json')
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* ラン記録を読む(壊れていても空。補助情報なので落とさない)。
|
|
515
|
+
*
|
|
516
|
+
* @param {string} file パス
|
|
517
|
+
* @returns {Array<object>} ラン(新しい順は保証しない)
|
|
518
|
+
*/
|
|
519
|
+
export function readRuns(file) {
|
|
520
|
+
let raw = ''
|
|
521
|
+
try {
|
|
522
|
+
raw = fs.readFileSync(file, 'utf8')
|
|
523
|
+
} catch {
|
|
524
|
+
return []
|
|
525
|
+
}
|
|
526
|
+
try {
|
|
527
|
+
const j = JSON.parse(raw)
|
|
528
|
+
const list = Array.isArray(j) ? j : j?.runs
|
|
529
|
+
if (!Array.isArray(list)) return []
|
|
530
|
+
return list.filter((r) => r && typeof r === 'object' && String(r.id ?? '').trim())
|
|
531
|
+
} catch {
|
|
532
|
+
return []
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* 上限まで剪定する(**古い完了分から**落とす。未報告ランは最後まで残す)。
|
|
538
|
+
*
|
|
539
|
+
* @param {Array<object>} runs ラン
|
|
540
|
+
* @param {number} [max] 上限(既定 50)
|
|
541
|
+
* @returns {Array<object>} 剪定後(元の順序を保つ)
|
|
542
|
+
*/
|
|
543
|
+
export function pruneRuns(runs, max = RUNS_MAX) {
|
|
544
|
+
const list = Array.isArray(runs) ? runs.slice() : []
|
|
545
|
+
let over = list.length - Math.max(0, Number(max) || 0)
|
|
546
|
+
if (over <= 0) return list
|
|
547
|
+
const byAge = list.slice().sort((a, b) => Number(a?.createdAt ?? 0) - Number(b?.createdAt ?? 0))
|
|
548
|
+
const drop = new Set()
|
|
549
|
+
for (const r of byAge) {
|
|
550
|
+
if (over <= 0) break
|
|
551
|
+
if (!r?.reportedAt) continue
|
|
552
|
+
drop.add(r)
|
|
553
|
+
over -= 1
|
|
554
|
+
}
|
|
555
|
+
for (const r of byAge) {
|
|
556
|
+
if (over <= 0) break
|
|
557
|
+
if (drop.has(r)) continue
|
|
558
|
+
drop.add(r)
|
|
559
|
+
over -= 1
|
|
560
|
+
}
|
|
561
|
+
return list.filter((r) => !drop.has(r))
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* ラン記録を `.tmp` → `renameSync` でアトミックに書く。
|
|
566
|
+
*
|
|
567
|
+
* @param {string} file パス
|
|
568
|
+
* @param {Array<object>} runs ラン
|
|
569
|
+
* @returns {void}
|
|
570
|
+
*/
|
|
571
|
+
export function writeRuns(file, runs) {
|
|
572
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
573
|
+
const tmp = `${file}.tmp`
|
|
574
|
+
fs.writeFileSync(tmp, JSON.stringify({ version: 1, runs: pruneRuns(runs) }, null, 2), 'utf8')
|
|
575
|
+
fs.renameSync(tmp, file)
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* ランを 1 件追記する(同じ ID は置き換え)。
|
|
580
|
+
*
|
|
581
|
+
* @param {object} cfg ブリッジ設定
|
|
582
|
+
* @param {object} run ラン
|
|
583
|
+
* @returns {Array<object>} 書いた内容
|
|
584
|
+
*/
|
|
585
|
+
export function appendRun(cfg, run) {
|
|
586
|
+
const file = runsPathFor(cfg)
|
|
587
|
+
const runs = readRuns(file)
|
|
588
|
+
const next = [...runs.filter((r) => r.id !== run.id), run]
|
|
589
|
+
writeRuns(file, next)
|
|
590
|
+
return pruneRuns(next)
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
/**
|
|
594
|
+
* ランの ID(`run_<UTC 秒>_<乱数 4>`)。同じ秒に 2 回落としても衝突しない。
|
|
595
|
+
* @param {number} [ms] epoch ms
|
|
596
|
+
* @returns {string} ID
|
|
597
|
+
*/
|
|
598
|
+
export function makeRunId(ms = Date.now()) {
|
|
599
|
+
const stamp = new Date(ms).toISOString().replace(/[-:]/g, '').replace(/\..+$/, '')
|
|
600
|
+
const tail = Math.random().toString(36).slice(2, 6).padEnd(4, '0')
|
|
601
|
+
return `run_${stamp}_${tail}`
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* 起票の実行(既定は `hermes kanban create`、テストでは差し替え)。
|
|
606
|
+
*
|
|
607
|
+
* @param {object} cfg 設定(`hermesBin`)
|
|
608
|
+
* @param {Function} [runner] 差し替え
|
|
609
|
+
* @returns {Function} 実行関数
|
|
610
|
+
*/
|
|
611
|
+
function defaultRunner(cfg = {}, runner) {
|
|
612
|
+
if (runner) return runner
|
|
613
|
+
return (args) =>
|
|
614
|
+
new Promise((resolve) => {
|
|
615
|
+
execFile(
|
|
616
|
+
cfg.hermesBin ?? resolveHermesBin(),
|
|
617
|
+
args,
|
|
618
|
+
{ timeout: 30_000, maxBuffer: 2_000_000, env: { ...process.env, PATH: buildAugmentedPath() } },
|
|
619
|
+
(err, stdout, stderr) => {
|
|
620
|
+
resolve({ code: err ? (err.code ?? 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
|
|
621
|
+
},
|
|
622
|
+
)
|
|
623
|
+
})
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* `hermes kanban create` の出力からタスク ID を取り出す。
|
|
628
|
+
* @param {string} stdout 標準出力
|
|
629
|
+
* @returns {{id: string}|null} タスク(取れなければ null)
|
|
630
|
+
*/
|
|
631
|
+
export function parseCreatedTask(stdout) {
|
|
632
|
+
const text = String(stdout ?? '')
|
|
633
|
+
const at = text.indexOf('{')
|
|
634
|
+
if (at >= 0) {
|
|
635
|
+
try {
|
|
636
|
+
const obj = JSON.parse(text.slice(at))
|
|
637
|
+
if (obj?.id) return { id: String(obj.id), title: obj.title ?? null, status: obj.status ?? null }
|
|
638
|
+
} catch {
|
|
639
|
+
/* 下の正規表現へ */
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
const m = /Created (t_[0-9a-zA-Z]+)/.exec(text)
|
|
643
|
+
return m ? { id: m[1] } : null
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Spec Launchpad(読み取り + 起票)。
|
|
648
|
+
*
|
|
649
|
+
* @param {object} cfg 設定(`hermesBin`)
|
|
650
|
+
* @param {{
|
|
651
|
+
* runner?: Function,
|
|
652
|
+
* tasks?: (board: string) => Array<object>,
|
|
653
|
+
* listSpecs?: Function,
|
|
654
|
+
* recordRun?: (run: object) => void,
|
|
655
|
+
* now?: () => number,
|
|
656
|
+
* }} [deps] 差し替え(テスト用)
|
|
657
|
+
* @returns {{listSpecs: Function, launchSpec: Function, resolveSpecPath: Function, readSpecContent: Function}} 操作
|
|
658
|
+
*/
|
|
659
|
+
export function createSpecs(cfg = {}, deps = {}) {
|
|
660
|
+
const run = defaultRunner(cfg, deps.runner)
|
|
661
|
+
// 既存タスクの読み取り(サーバでは kanban.tasks を渡す。テストでは [] か一時 DB)
|
|
662
|
+
const readTasks = deps.tasks ?? (() => [])
|
|
663
|
+
const scan = deps.listSpecs ?? (() => [])
|
|
664
|
+
const now = typeof deps.now === 'function' ? deps.now : () => Date.now()
|
|
665
|
+
// ラン記録(既定は `review/pipeline-runs.json`。テストでは差し替え)。
|
|
666
|
+
// 出力先が分からない cfg(テストの `{}` など)では何もしない(リポジトリを汚さない)。
|
|
667
|
+
const canRecord = Boolean(cfg.reviewDir || cfg.pluginDataDir || cfg.kanbanRoot)
|
|
668
|
+
const recordRun =
|
|
669
|
+
deps.recordRun ?? (canRecord ? (r) => appendRun(cfg, r) : () => {})
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* バッチをカンバンへ一括起票する。
|
|
673
|
+
*
|
|
674
|
+
* @param {{
|
|
675
|
+
* repoPath: string,
|
|
676
|
+
* board: string,
|
|
677
|
+
* specRelPath: string,
|
|
678
|
+
* batchIds?: string[],
|
|
679
|
+
* assignee?: string,
|
|
680
|
+
* dryRun?: boolean,
|
|
681
|
+
* limit?: number,
|
|
682
|
+
* }} input 入力
|
|
683
|
+
* @returns {Promise<{ok: boolean, created: Array<object>, skipped: Array<object>, failed: Array<object>, spec?: string, board?: string, error?: string}>} 結果
|
|
684
|
+
*/
|
|
685
|
+
async function launchSpec(input = {}) {
|
|
686
|
+
const board = String(input.board ?? '').trim()
|
|
687
|
+
if (!/^[a-z0-9][a-z0-9._-]{0,63}$/i.test(board)) {
|
|
688
|
+
return { ok: false, created: [], skipped: [], failed: [], code: 'BOARD_NAME_INVALID' }
|
|
689
|
+
}
|
|
690
|
+
const repoPath = String(input.repoPath ?? '').trim()
|
|
691
|
+
if (!repoPath || !path.isAbsolute(repoPath)) {
|
|
692
|
+
return { ok: false, created: [], skipped: [], failed: [], code: 'INVALID_REPO' }
|
|
693
|
+
}
|
|
694
|
+
const specRelPath = String(input.specRelPath ?? '').trim()
|
|
695
|
+
let file = ''
|
|
696
|
+
try {
|
|
697
|
+
file = resolveSpecPath(repoPath, specRelPath)
|
|
698
|
+
} catch (e) {
|
|
699
|
+
return { ok: false, created: [], skipped: [], failed: [], code: e.code, params: e.params, error: e.message }
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
let text = ''
|
|
703
|
+
try {
|
|
704
|
+
text = fs.readFileSync(file, 'utf8')
|
|
705
|
+
} catch {
|
|
706
|
+
return { ok: false, created: [], skipped: [], failed: [], code: 'SPEC_READ_FAILED', params: { path: specRelPath } }
|
|
707
|
+
}
|
|
708
|
+
const parsed = parseSpec(text)
|
|
709
|
+
if (!parsed.batches.length) {
|
|
710
|
+
return { ok: false, created: [], skipped: [], failed: [], code: 'SPEC_BATCH_HEADING_MISSING' }
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const wanted = Array.isArray(input.batchIds) ? new Set(input.batchIds.map((x) => String(x ?? '').trim())) : null
|
|
714
|
+
const batches = parsed.batches.filter((b) => !wanted || wanted.size === 0 || wanted.has(b.id))
|
|
715
|
+
if (!batches.length) {
|
|
716
|
+
return { ok: false, created: [], skipped: [], failed: [], code: 'SPEC_BATCH_NOT_FOUND' }
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const assignee = String(input.assignee ?? '').trim()
|
|
720
|
+
const dryRun = Boolean(input.dryRun)
|
|
721
|
+
// 起票元チャット(`Chat:` 行+ラン記録の originSessionId)。書式外は黙って捨てる。
|
|
722
|
+
const chat = sanitizeSpecChat(input.chat)
|
|
723
|
+
|
|
724
|
+
let existing = []
|
|
725
|
+
try {
|
|
726
|
+
existing = readTasks(board) ?? []
|
|
727
|
+
} catch {
|
|
728
|
+
existing = []
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
const created = []
|
|
732
|
+
const skipped = []
|
|
733
|
+
const failed = []
|
|
734
|
+
for (const batch of batches) {
|
|
735
|
+
const open = findOpenBatchTask(existing, batch.id)
|
|
736
|
+
if (open) {
|
|
737
|
+
skipped.push({ id: batch.id, title: batch.title, reason: 'exists', taskId: open.id, status: open.status })
|
|
738
|
+
continue
|
|
739
|
+
}
|
|
740
|
+
const title = buildTaskTitle(batch)
|
|
741
|
+
const body = buildTaskBody({ specRelPath, repoPath, board, batch, chat })
|
|
742
|
+
if (dryRun) {
|
|
743
|
+
created.push({ id: batch.id, title, taskId: null, dryRun: true })
|
|
744
|
+
continue
|
|
745
|
+
}
|
|
746
|
+
const args = ['kanban', '--board', board, 'create', title, '--json', '--body', body]
|
|
747
|
+
if (assignee) args.push('--assignee', assignee)
|
|
748
|
+
const res = await run(args)
|
|
749
|
+
if (res.code !== 0) {
|
|
750
|
+
failed.push({
|
|
751
|
+
id: batch.id,
|
|
752
|
+
title,
|
|
753
|
+
code: 'CREATE_FAILED',
|
|
754
|
+
error: (res.stderr || res.stdout || '').trim().slice(0, 400),
|
|
755
|
+
})
|
|
756
|
+
continue
|
|
757
|
+
}
|
|
758
|
+
const task = parseCreatedTask(res.stdout)
|
|
759
|
+
if (!task?.id) {
|
|
760
|
+
failed.push({ id: batch.id, title, code: 'TASK_ID_MISSING' })
|
|
761
|
+
continue
|
|
762
|
+
}
|
|
763
|
+
created.push({ id: batch.id, title, taskId: task.id, status: task.status ?? 'ready' })
|
|
764
|
+
// 同じバッチを 2 回起票しないよう、今回作った分も既存扱いにする
|
|
765
|
+
existing = [...existing, { id: task.id, title, status: task.status ?? 'ready' }]
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
const ok = failed.length === 0
|
|
769
|
+
|
|
770
|
+
// ラン記録(1 件以上起票 or 既存へ紐づけできたときだけ)。記録失敗で起票を失敗させない。
|
|
771
|
+
let runRecord = null
|
|
772
|
+
if (!dryRun && (created.length > 0 || skipped.length > 0)) {
|
|
773
|
+
const taskIds = [...created.map((c) => c.taskId), ...skipped.map((s) => s.taskId)].filter(Boolean)
|
|
774
|
+
runRecord = {
|
|
775
|
+
id: makeRunId(now()),
|
|
776
|
+
board,
|
|
777
|
+
repoPath,
|
|
778
|
+
specRelPath,
|
|
779
|
+
title: parsed.title || specRelPath,
|
|
780
|
+
batchIds: batches.map((b) => b.id),
|
|
781
|
+
taskIds: [...new Set(taskIds)],
|
|
782
|
+
originSessionId: chat || null,
|
|
783
|
+
createdAt: now(),
|
|
784
|
+
reportedAt: null,
|
|
785
|
+
}
|
|
786
|
+
try {
|
|
787
|
+
recordRun(runRecord)
|
|
788
|
+
} catch {
|
|
789
|
+
runRecord = null
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
return {
|
|
794
|
+
ok,
|
|
795
|
+
spec: specRelPath,
|
|
796
|
+
board,
|
|
797
|
+
created,
|
|
798
|
+
skipped,
|
|
799
|
+
failed,
|
|
800
|
+
runId: runRecord?.id ?? null,
|
|
801
|
+
...(ok ? {} : { error: failed.map((f) => `${f.id}: ${f.error}`).join(' / ') }),
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
return { listSpecs: scan, launchSpec, resolveSpecPath, readSpecContent }
|
|
806
|
+
}
|