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,1022 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import crypto from 'node:crypto'
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
5
|
+
import { readRuns, runsPathFor, writeRuns } from './specs.js'
|
|
6
|
+
import { summarizeTasks } from './telemetry.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* パイプライン完走ウォッチャー(SPEC §3.2 / D20 / D21)。
|
|
10
|
+
*
|
|
11
|
+
* カンバン DB を**読み取り専用**で 10 秒ごとに見て、次の 2 種類の「波」が収束した瞬間に
|
|
12
|
+
* 統合 Markdown レポートを 1 回だけ合成し、起票元チャットへ届ける。
|
|
13
|
+
*
|
|
14
|
+
* - **A. Spec ラン単位**: 本文の `Spec: <rel>` 行(または `pipeline-runs.json` の `taskIds`)で
|
|
15
|
+
* 同じ `(board, spec)` に属するタスク群
|
|
16
|
+
* - **B. ボードウェーブ単位**: `Spec:` を持たない通常タスク(チャット起票など)で、
|
|
17
|
+
* `[review]` / `[akapen]` は個別レビュー報告と重複するので除外する
|
|
18
|
+
*
|
|
19
|
+
* 大事な性質(review-watcher と同じ設計方針):
|
|
20
|
+
* - **初回起動はベースライン確立のみ**(過去分を遡って通知しない。スパム防止)
|
|
21
|
+
* - **取りこぼし防止**: ティック間に起票→完了したタスクも `completed_at >= startedAtSec` で拾う
|
|
22
|
+
* - **重複通知なし**: `reportedKeys` に状態キー(Spec は最新完了時刻、ウェーブはタスク ID のハッシュ)
|
|
23
|
+
* - **`review/feed.jsonl` には書かない**(Review タブの通知を汚さない)。書く先は
|
|
24
|
+
* `review/chat-reports.jsonl`(`kind: 'pipeline'`)と `review/pipeline-reports.jsonl`
|
|
25
|
+
* - **アトミック**: 状態は `.tmp` → `renameSync`。JSONL は 1 行完結の append
|
|
26
|
+
*
|
|
27
|
+
* @param {object} cfg ブリッジ設定(kanbanRoot / reviewDir / stateDb / hermesHome)
|
|
28
|
+
* @param {{
|
|
29
|
+
* intervalMs?: number,
|
|
30
|
+
* now?: () => number,
|
|
31
|
+
* logger?: object,
|
|
32
|
+
* dbPaths?: Array<{board: string|null, path: string}>,
|
|
33
|
+
* stateDbs?: string[],
|
|
34
|
+
* boardWorkdir?: (board: string) => string|null,
|
|
35
|
+
* gitinfo?: {forTask: Function, diffSummary: Function},
|
|
36
|
+
* runsPath?: string,
|
|
37
|
+
* readRuns?: (file: string) => Array<object>,
|
|
38
|
+
* writeRuns?: (file: string, runs: Array<object>) => void,
|
|
39
|
+
* }} [opts] 差し替え(テスト用)
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
/** レポート種別(`chat-reports.jsonl` の `kind`)。 */
|
|
43
|
+
export const PIPELINE_KIND = 'pipeline'
|
|
44
|
+
|
|
45
|
+
/** 「まだ動いている」状態。これが 0 になったら収束。 */
|
|
46
|
+
const OPEN_STATUSES = new Set(['running', 'ready', 'todo'])
|
|
47
|
+
|
|
48
|
+
/** 個別レビュー報告と重複するタグ(ウェーブ集計から除外する)。 */
|
|
49
|
+
const REVIEW_TAGS = ['[review]', '[akapen]']
|
|
50
|
+
|
|
51
|
+
/** 未実施・残課題として拾う語(英語・日本語の両方を 1 つの正規表現で)。 */
|
|
52
|
+
const NOISE_RE = /(TODO|FIXME|未実施|残課題|スキップ|blocked|skipped|failed|remaining|warning|⚠)/i
|
|
53
|
+
|
|
54
|
+
/** 抽出する課題行の上限。 */
|
|
55
|
+
const ISSUE_LIMIT = 8
|
|
56
|
+
|
|
57
|
+
/** 保持する状態キーの上限(育ちすぎないようにする)。 */
|
|
58
|
+
const REPORTED_KEYS_MAX = 200
|
|
59
|
+
|
|
60
|
+
/** 1 DB から読むタスク数(直近 300 件。古いタスクは完了検知の対象外)。 */
|
|
61
|
+
const TASKS_PER_DB = 300
|
|
62
|
+
|
|
63
|
+
/** `Spec:` 行。 */
|
|
64
|
+
const SPEC_LINE_RE = /^Spec:\s*(.+?)\s*$/m
|
|
65
|
+
|
|
66
|
+
/** `Chat:` 行。 */
|
|
67
|
+
const CHAT_LINE_RE = /^Chat:\s*(.+?)\s*$/m
|
|
68
|
+
|
|
69
|
+
/** チャット ID の書式(`specs.js` の `SPEC_CHAT_RE` と同じ規則)。 */
|
|
70
|
+
const CHAT_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* パス比較用に正規化する(末尾の `/` を落とし、絶対パス化する)。
|
|
74
|
+
* @param {unknown} p パス
|
|
75
|
+
* @returns {string} 正規化後(空なら空文字)
|
|
76
|
+
*/
|
|
77
|
+
export function normalizePath(p) {
|
|
78
|
+
const s = String(p ?? '').trim()
|
|
79
|
+
if (!s) return ''
|
|
80
|
+
return path.resolve(s).replace(/[\\/]+$/, '') || '/'
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 本文から `Spec: <rel>` を読む。
|
|
85
|
+
* @param {unknown} body タスク本文
|
|
86
|
+
* @returns {string|null} spec の相対パス(無ければ null)
|
|
87
|
+
*/
|
|
88
|
+
export function specRelFromBody(body) {
|
|
89
|
+
const m = SPEC_LINE_RE.exec(String(body ?? ''))
|
|
90
|
+
return m ? m[1].trim() : null
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 本文から `Chat: <session_id>` を読む(書式外は null)。
|
|
95
|
+
* @param {unknown} body タスク本文
|
|
96
|
+
* @returns {string|null} セッション ID
|
|
97
|
+
*/
|
|
98
|
+
export function chatFromBody(body) {
|
|
99
|
+
const m = CHAT_LINE_RE.exec(String(body ?? ''))
|
|
100
|
+
if (!m) return null
|
|
101
|
+
const id = m[1].trim()
|
|
102
|
+
return CHAT_ID_RE.test(id) ? id : null
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* 個別レビュー報告の対象タスクか(`[review]` / `[akapen]` を含む)。
|
|
107
|
+
* @param {unknown} body タスク本文
|
|
108
|
+
* @returns {boolean} レビュータスクなら true
|
|
109
|
+
*/
|
|
110
|
+
export function isReviewBody(body) {
|
|
111
|
+
const text = String(body ?? '')
|
|
112
|
+
return REVIEW_TAGS.some((tag) => text.includes(tag))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 1 行に潰す(長すぎる本文は切る)。 */
|
|
116
|
+
function oneLine(text, max = 220) {
|
|
117
|
+
const s = String(text ?? '')
|
|
118
|
+
.replace(/\s+/g, ' ')
|
|
119
|
+
.trim()
|
|
120
|
+
return s.length > max ? `${s.slice(0, max - 1)}…` : s
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 状態ごとの件数。 */
|
|
124
|
+
function countStatuses(tasks) {
|
|
125
|
+
const counts = { done: 0, blocked: 0, failed: 0, running: 0, ready: 0, todo: 0, other: 0, total: 0 }
|
|
126
|
+
for (const t of Array.isArray(tasks) ? tasks : []) {
|
|
127
|
+
const s = String(t?.status ?? '')
|
|
128
|
+
counts.total += 1
|
|
129
|
+
if (s in counts) counts[s] += 1
|
|
130
|
+
else counts.other += 1
|
|
131
|
+
}
|
|
132
|
+
return counts
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 経過時間の表示(`12m` / `1h 5m`)。 */
|
|
136
|
+
function elapsedLabel(fromMs, toMs) {
|
|
137
|
+
const a = Number(fromMs)
|
|
138
|
+
const b = Number(toMs)
|
|
139
|
+
if (!Number.isFinite(a) || !Number.isFinite(b) || a <= 0 || b <= a) return ''
|
|
140
|
+
const minutes = Math.max(1, Math.round((b - a) / 60_000))
|
|
141
|
+
if (minutes < 60) return `${minutes}m`
|
|
142
|
+
return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* `task.result` と `blocked` / `failed` から未実施・発見課題を抽出する(純関数)。
|
|
147
|
+
*
|
|
148
|
+
* blocked / failed は**理由ごと優先表示**し、次に各 result の該当行を拾う
|
|
149
|
+
* (`TODO` / `未実施` / `残課題` / `blocked` / `warning` / `⚠` など最大 8 件、重複除去)。
|
|
150
|
+
*
|
|
151
|
+
* @param {Array<{id: string, title?: string, status?: string, result?: string}>} tasks タスク
|
|
152
|
+
* @param {{limit?: number}} [opts] 上限
|
|
153
|
+
* @returns {Array<{taskId: string, title: string, kind: string, text: string}>} 課題
|
|
154
|
+
*/
|
|
155
|
+
export function extractIssuesAndRemaining(tasks, opts = {}) {
|
|
156
|
+
const limit = Math.max(1, Number(opts.limit) || ISSUE_LIMIT)
|
|
157
|
+
const out = []
|
|
158
|
+
const seen = new Set()
|
|
159
|
+
const push = (taskId, title, kind, text) => {
|
|
160
|
+
const key = oneLine(text, 200).toLowerCase()
|
|
161
|
+
if (!key || seen.has(key)) return
|
|
162
|
+
seen.add(key)
|
|
163
|
+
out.push({ taskId, title: oneLine(title, 90), kind, text: oneLine(text, 220) })
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const list = Array.isArray(tasks) ? tasks : []
|
|
167
|
+
// 1) 停止したタスク(理由が最も重要)
|
|
168
|
+
for (const t of list) {
|
|
169
|
+
const status = String(t?.status ?? '')
|
|
170
|
+
if (status !== 'blocked' && status !== 'failed') continue
|
|
171
|
+
const reason = oneLine(t.result) || `${status}(理由の記録なし)`
|
|
172
|
+
push(String(t.id), t.title, status, reason)
|
|
173
|
+
}
|
|
174
|
+
// 2) result 本文の残課題・警告行
|
|
175
|
+
for (const t of list) {
|
|
176
|
+
const lines = String(t?.result ?? '').split(/\r?\n/)
|
|
177
|
+
for (const line of lines) {
|
|
178
|
+
const text = line.replace(/^[\s>*+-]+/, '').trim()
|
|
179
|
+
if (!text || text.length < 4) continue
|
|
180
|
+
if (!NOISE_RE.test(text)) continue
|
|
181
|
+
push(String(t.id), t.title, 'note', text)
|
|
182
|
+
if (out.length >= limit) return out.slice(0, limit)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return out.slice(0, limit)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 状況に応じた推奨ネクストステップ(純関数・最大 3 件)。
|
|
190
|
+
*
|
|
191
|
+
* @param {{status: string, board?: string, specRelPath?: string|null, tasks?: Array<object>, issues?: Array<object>, counts?: object}} input 入力
|
|
192
|
+
* @returns {string[]} 次の一手
|
|
193
|
+
*/
|
|
194
|
+
export function buildNextSteps({ status, board, specRelPath, tasks = [], issues = [], counts } = {}) {
|
|
195
|
+
const c = counts ?? countStatuses(tasks)
|
|
196
|
+
const out = []
|
|
197
|
+
if (status === 'halted') {
|
|
198
|
+
const stuck = c.blocked + c.failed
|
|
199
|
+
out.push(`⚠ ${stuck} 件の blocked/failed タスクの理由を確認し、指示を出して再開する(board: ${board})`)
|
|
200
|
+
}
|
|
201
|
+
if (issues.length > 0) {
|
|
202
|
+
out.push(`抽出された残課題 ${issues.length} 件を確認し、着手可能なものを次のタスクにする`)
|
|
203
|
+
}
|
|
204
|
+
if (specRelPath) {
|
|
205
|
+
out.push(`${specRelPath} の残バッチを Spec Launchpad から起動する(${board})`)
|
|
206
|
+
}
|
|
207
|
+
if (status !== 'halted') {
|
|
208
|
+
out.push('`npm run verify` と実機/画面の最終確認を行い、リリース判断をする')
|
|
209
|
+
}
|
|
210
|
+
if (out.length < 2) out.push(`変更内容をレビューし、次の一手を相談する(board: ${board})`)
|
|
211
|
+
return out.slice(0, 3)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Git 情報 1 行(`\`abc1234\`, +84/-12 · 4 files`)。 */
|
|
215
|
+
function gitLine(git) {
|
|
216
|
+
if (!git) return ''
|
|
217
|
+
const bits = []
|
|
218
|
+
const sha = String(git.head ?? '').slice(0, 7)
|
|
219
|
+
if (sha) bits.push(`\`${sha}\``)
|
|
220
|
+
const add = Number(git.total?.add ?? 0)
|
|
221
|
+
const del = Number(git.total?.del ?? 0)
|
|
222
|
+
if (add || del) bits.push(`+${add}/-${del}`)
|
|
223
|
+
const files = Array.isArray(git.files) ? git.files.length : 0
|
|
224
|
+
if (files) bits.push(`${files} file${files === 1 ? '' : 's'}`)
|
|
225
|
+
return bits.length ? ` (${bits.join(', ')})` : ''
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 分を「42 分」「1 時間 5 分」へ整形する(レポート用・0 は null)。
|
|
230
|
+
* @param {number|null|undefined} min 分
|
|
231
|
+
* @returns {string|null} 表示文字列
|
|
232
|
+
*/
|
|
233
|
+
export function fmtDurationMin(min) {
|
|
234
|
+
const n = Number(min)
|
|
235
|
+
if (!Number.isFinite(n) || n <= 0) return null
|
|
236
|
+
if (n < 60) return `${Math.round(n)} 分`
|
|
237
|
+
return `${Math.floor(n / 60)} 時間 ${Math.round(n % 60)} 分`
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* トークン数を `950` / `480K` / `1.2M` へ整形する(レシート Canvas と同じ規則)。
|
|
242
|
+
* @param {number|null|undefined} value トークン数
|
|
243
|
+
* @returns {string|null} 表示文字列
|
|
244
|
+
*/
|
|
245
|
+
export function fmtTokenCount(value) {
|
|
246
|
+
const n = Number(value)
|
|
247
|
+
if (!Number.isFinite(n) || n < 0) return null
|
|
248
|
+
if (n >= 1e6) return `${Math.round((n / 1e6) * 10) / 10}M`
|
|
249
|
+
if (n >= 1e3) return `${Math.round(n / 1e3)}K`
|
|
250
|
+
return String(Math.round(n))
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 統合 Markdown レポートを組み立てる(純関数)。
|
|
255
|
+
*
|
|
256
|
+
* 所要時間は `telemetry.js` の `summarizeTasks()` を共有し、並列タスクの重なりを
|
|
257
|
+
* マージした **実稼働時間**(主指標)と単純経過時間を併記する。`usage` が渡された
|
|
258
|
+
* ときは Spec / Run スコープの API コール数・トークン数も出力する。
|
|
259
|
+
*
|
|
260
|
+
* @param {{
|
|
261
|
+
* status: 'done'|'halted',
|
|
262
|
+
* label: string,
|
|
263
|
+
* board: string,
|
|
264
|
+
* specRelPath?: string|null,
|
|
265
|
+
* tasks?: Array<object>,
|
|
266
|
+
* gitMap?: Record<string, object>,
|
|
267
|
+
* startedAt?: number,
|
|
268
|
+
* now?: number,
|
|
269
|
+
* usage?: {apiCalls?: number|null, totalTokens?: number|null, totals?: object|null, scope?: object|null}|null,
|
|
270
|
+
* }} input 入力
|
|
271
|
+
* @returns {{text: string, markdown: string, followUpPrompt: string, counts: object, issues: Array<object>, nextSteps: string[], timing: object}} レポート
|
|
272
|
+
*/
|
|
273
|
+
export function buildPipelineReport({
|
|
274
|
+
status = 'done',
|
|
275
|
+
label = '',
|
|
276
|
+
board = '',
|
|
277
|
+
specRelPath = null,
|
|
278
|
+
tasks = [],
|
|
279
|
+
gitMap = {},
|
|
280
|
+
startedAt = 0,
|
|
281
|
+
now: nowMs = Date.now(),
|
|
282
|
+
usage = null,
|
|
283
|
+
} = {}) {
|
|
284
|
+
const counts = countStatuses(tasks)
|
|
285
|
+
const elapsed = elapsedLabel(startedAt, nowMs)
|
|
286
|
+
const issues = extractIssuesAndRemaining(tasks)
|
|
287
|
+
const nextSteps = buildNextSteps({ status, board, specRelPath, tasks, issues, counts })
|
|
288
|
+
const title = String(label || board || specRelPath || 'pipeline')
|
|
289
|
+
const halted = status === 'halted'
|
|
290
|
+
|
|
291
|
+
// 時間は Spec / Run スコープのタスク区間から(重なりはマージして二重計上しない)
|
|
292
|
+
const timing = summarizeTasks(tasks, { now: nowMs })
|
|
293
|
+
const activeLabel = fmtDurationMin(timing.durationMin)
|
|
294
|
+
const wallLabel = fmtDurationMin(timing.wallDurationMin)
|
|
295
|
+
const callsLabel = usage && Number.isFinite(Number(usage.apiCalls)) ? Number(usage.apiCalls) : null
|
|
296
|
+
const tokensLabel = usage && Number.isFinite(Number(usage.totalTokens)) ? Number(usage.totalTokens) : null
|
|
297
|
+
const usageBits = [
|
|
298
|
+
callsLabel === null ? null : `🔌 ${callsLabel} API`,
|
|
299
|
+
tokensLabel === null ? null : `🪙 ${fmtTokenCount(tokensLabel)} tokens`,
|
|
300
|
+
].filter(Boolean)
|
|
301
|
+
const timeBits = [
|
|
302
|
+
activeLabel ? `⏱ 実稼働 ${activeLabel}` : null,
|
|
303
|
+
wallLabel ? `経過 ${wallLabel}` : null,
|
|
304
|
+
].filter(Boolean)
|
|
305
|
+
const summaryBits = [...timeBits, ...usageBits]
|
|
306
|
+
|
|
307
|
+
const headBase = halted
|
|
308
|
+
? `### ⚠️ Action Required: ${title} (${counts.done} done · ${counts.blocked} blocked` +
|
|
309
|
+
`${counts.failed ? ` · ${counts.failed} failed` : ''}${elapsed ? ` · ${elapsed}` : ''})`
|
|
310
|
+
: `### 🎉 Pipeline Completed: ${title} (${counts.done}/${counts.total} done${elapsed ? ` · ${elapsed}` : ''})`
|
|
311
|
+
const head = summaryBits.length ? `${headBase} · ${summaryBits.join(' · ')}` : headBase
|
|
312
|
+
|
|
313
|
+
const doneLines = []
|
|
314
|
+
for (const t of tasks) {
|
|
315
|
+
if (String(t?.status ?? '') !== 'done') continue
|
|
316
|
+
const summary = oneLine(t.result, 200)
|
|
317
|
+
doneLines.push(`- **${oneLine(t.title, 120)}**${gitLine(gitMap[String(t.id)])}`)
|
|
318
|
+
if (summary) doneLines.push(` - ${summary}`)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const issueLines = issues.length
|
|
322
|
+
? issues.map((i) => `- **[${i.kind}] ${i.title}** — ${i.text}`)
|
|
323
|
+
: ['- **無し(全項目クリーン完走)**']
|
|
324
|
+
|
|
325
|
+
const nextLines = nextSteps.map((s) => `- ${s}`)
|
|
326
|
+
|
|
327
|
+
const usageLines = [
|
|
328
|
+
`- 実稼働(重複区間をマージ): ${activeLabel ?? '—'}`,
|
|
329
|
+
`- 経過時間: ${wallLabel ?? '—'}`,
|
|
330
|
+
`- API コール数: ${callsLabel === null ? '—' : String(callsLabel)}`,
|
|
331
|
+
`- トークン数: ${tokensLabel === null ? '—' : `${fmtTokenCount(tokensLabel)}(入力 ${fmtTokenCount(usage?.totals?.input ?? 0)} · 出力 ${fmtTokenCount(usage?.totals?.output ?? 0)} · キャッシュ読取 ${fmtTokenCount(usage?.totals?.cacheRead ?? 0)})`}`,
|
|
332
|
+
]
|
|
333
|
+
|
|
334
|
+
const markdown = [
|
|
335
|
+
head,
|
|
336
|
+
'',
|
|
337
|
+
'#### ⏱ 所要時間・使用量 / Time & Usage',
|
|
338
|
+
...usageLines,
|
|
339
|
+
'',
|
|
340
|
+
'#### ✅ 完了タスク / Completed Tasks',
|
|
341
|
+
...(doneLines.length ? doneLines : ['- (完了タスクなし)']),
|
|
342
|
+
'',
|
|
343
|
+
'#### ⚠️ 未実施項目・発見課題 / Issues & Remaining Items',
|
|
344
|
+
...issueLines,
|
|
345
|
+
'',
|
|
346
|
+
'#### 🚀 次のステップ / Recommended Next Steps',
|
|
347
|
+
...nextLines,
|
|
348
|
+
].join('\n')
|
|
349
|
+
|
|
350
|
+
const textBase = halted
|
|
351
|
+
? `⚠️ ${title} (${counts.done} done · ${counts.blocked} blocked)`
|
|
352
|
+
: `🎉 ${title} (${counts.done}/${counts.total} done)`
|
|
353
|
+
const text = summaryBits.length ? `${textBase} · ${summaryBits.join(' · ')}` : textBase
|
|
354
|
+
|
|
355
|
+
const promptLines = [
|
|
356
|
+
`先ほどのパイプライン「${title}」(board: ${board}${specRelPath ? ` / ${specRelPath}` : ''})の結果を確認してください。`,
|
|
357
|
+
`完了 ${counts.done} 件 / blocked ${counts.blocked} 件 / failed ${counts.failed} 件(全 ${counts.total} 件)。`,
|
|
358
|
+
...issues.slice(0, 3).map((i) => `- [${i.kind}] ${i.text}`),
|
|
359
|
+
'次の一手(実装・検証・リリース判断)を一緒に決めたいです。具体的な手順とコマンドを提示してください。',
|
|
360
|
+
]
|
|
361
|
+
|
|
362
|
+
return {
|
|
363
|
+
text,
|
|
364
|
+
markdown,
|
|
365
|
+
followUpPrompt: promptLines.join('\n').slice(0, 1200),
|
|
366
|
+
counts: {
|
|
367
|
+
done: counts.done,
|
|
368
|
+
blocked: counts.blocked,
|
|
369
|
+
failed: counts.failed,
|
|
370
|
+
total: counts.total,
|
|
371
|
+
},
|
|
372
|
+
issues,
|
|
373
|
+
nextSteps,
|
|
374
|
+
timing: {
|
|
375
|
+
activeDurationMin: timing.durationMin,
|
|
376
|
+
wallDurationMin: timing.wallDurationMin,
|
|
377
|
+
intervals: timing.intervalCount,
|
|
378
|
+
durationCapped: timing.durationCapped,
|
|
379
|
+
},
|
|
380
|
+
usage: {
|
|
381
|
+
apiCalls: callsLabel,
|
|
382
|
+
totalTokens: tokensLabel,
|
|
383
|
+
scope: usage?.scope ?? null,
|
|
384
|
+
},
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* `pipeline-reports.jsonl` を読む(新しい順・ボードで絞れる)。API 用。
|
|
390
|
+
*
|
|
391
|
+
* @param {string} rootDir レビューディレクトリ(`review/`)
|
|
392
|
+
* @param {{board?: string|null, limit?: number}} [opts] 絞り込み
|
|
393
|
+
* @returns {Array<object>} レポート(`at` は epoch ms、camelCase)
|
|
394
|
+
*/
|
|
395
|
+
export function readPipelineReports(rootDir, opts = {}) {
|
|
396
|
+
const file = path.join(String(rootDir ?? ''), 'pipeline-reports.jsonl')
|
|
397
|
+
const limit = Math.min(Math.max(Number(opts.limit) || 20, 1), 100)
|
|
398
|
+
const board = String(opts.board ?? '').trim()
|
|
399
|
+
let raw = ''
|
|
400
|
+
try {
|
|
401
|
+
raw = fs.readFileSync(file, 'utf8')
|
|
402
|
+
} catch {
|
|
403
|
+
return []
|
|
404
|
+
}
|
|
405
|
+
const out = []
|
|
406
|
+
for (const line of raw.split('\n')) {
|
|
407
|
+
if (!line.trim()) continue
|
|
408
|
+
try {
|
|
409
|
+
const j = JSON.parse(line)
|
|
410
|
+
const at = Date.parse(String(j.at ?? ''))
|
|
411
|
+
if (!Number.isFinite(at)) continue
|
|
412
|
+
if (board && String(j.board ?? '') !== board) continue
|
|
413
|
+
out.push({
|
|
414
|
+
at,
|
|
415
|
+
kind: String(j.kind ?? PIPELINE_KIND),
|
|
416
|
+
status: String(j.status ?? ''),
|
|
417
|
+
sessionId: String(j.session_id ?? ''),
|
|
418
|
+
taskId: String(j.task_id ?? ''),
|
|
419
|
+
label: j.label ?? null,
|
|
420
|
+
board: j.board ?? null,
|
|
421
|
+
spec: j.spec ?? null,
|
|
422
|
+
repoPath: j.repo_path ?? null,
|
|
423
|
+
text: String(j.text ?? ''),
|
|
424
|
+
markdown: String(j.markdown ?? ''),
|
|
425
|
+
followUpPrompt: String(j.follow_up_prompt ?? ''),
|
|
426
|
+
counts: j.counts ?? null,
|
|
427
|
+
})
|
|
428
|
+
} catch {
|
|
429
|
+
/* 書きかけ・壊れた行は捨てる(補助情報) */
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return out.sort((a, b) => b.at - a.at).slice(0, limit)
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** 1 行の末尾改行を保証して追記する(JSONL が連結しないように)。 */
|
|
436
|
+
function appendJsonl(file, obj) {
|
|
437
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
438
|
+
let prefix = ''
|
|
439
|
+
try {
|
|
440
|
+
const st = fs.statSync(file)
|
|
441
|
+
if (st.size > 0) {
|
|
442
|
+
const fd = fs.openSync(file, 'r')
|
|
443
|
+
const buf = Buffer.alloc(1)
|
|
444
|
+
fs.readSync(fd, buf, 0, 1, st.size - 1)
|
|
445
|
+
fs.closeSync(fd)
|
|
446
|
+
if (buf.toString() !== '\n') prefix = '\n'
|
|
447
|
+
}
|
|
448
|
+
} catch {
|
|
449
|
+
/* 無ければそのまま作る */
|
|
450
|
+
}
|
|
451
|
+
fs.appendFileSync(file, `${prefix}${JSON.stringify(obj)}\n`)
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** タスク ID 群の短いハッシュ(ウェーブの状態キー)。 */
|
|
455
|
+
function waveHash(tasks) {
|
|
456
|
+
const ids = (Array.isArray(tasks) ? tasks : []).map((t) => String(t?.id ?? '')).sort()
|
|
457
|
+
return crypto.createHash('sha1').update(ids.join(',')).digest('hex').slice(0, 10)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* `review/` のルート(`chat-reports.jsonl` などの置き場)。
|
|
462
|
+
*
|
|
463
|
+
* SPEC V5-3 の Architect(`architect.js`)も同じファイルへ `spec_ready` を書くため、
|
|
464
|
+
* 解決規則をここ 1 箇所に寄せる。
|
|
465
|
+
* @param {object} [cfg] 設定(`reviewDir` / `pluginDataDir` / `kanbanRoot`)
|
|
466
|
+
* @returns {string} ディレクトリ
|
|
467
|
+
*/
|
|
468
|
+
export function reviewRootFor(cfg = {}) {
|
|
469
|
+
return (
|
|
470
|
+
cfg.reviewDir ??
|
|
471
|
+
path.join(
|
|
472
|
+
cfg.pluginDataDir ?? path.join(cfg.kanbanRoot ?? '.', '..', 'plugin-data', 'hermes-pilot'),
|
|
473
|
+
'review',
|
|
474
|
+
)
|
|
475
|
+
)
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* `chat-reports.jsonl` へ 1 行追記する(パイプライン完了と Architect の仕様完成が同じ列に並ぶ)。
|
|
480
|
+
* @param {object} [cfg] 設定
|
|
481
|
+
* @param {object} row 行(`kind` を持つ)
|
|
482
|
+
* @returns {string} 書き込んだファイル
|
|
483
|
+
*/
|
|
484
|
+
export function appendChatReport(cfg = {}, row = {}) {
|
|
485
|
+
const file = path.join(reviewRootFor(cfg), 'chat-reports.jsonl')
|
|
486
|
+
appendJsonl(file, row)
|
|
487
|
+
return file
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
export function createPipelineWatcher(cfg = {}, opts = {}) {
|
|
491
|
+
const intervalMs = Math.max(1000, Number(opts.intervalMs) || 10_000)
|
|
492
|
+
const now = typeof opts.now === 'function' ? opts.now : () => Date.now()
|
|
493
|
+
const log = opts.logger ?? console
|
|
494
|
+
const reviewRoot = reviewRootFor(cfg)
|
|
495
|
+
const statePath = path.join(reviewRoot, 'pipeline-watcher-state.json')
|
|
496
|
+
const chatReportsPath = path.join(reviewRoot, 'chat-reports.jsonl')
|
|
497
|
+
const reportsPath = path.join(reviewRoot, 'pipeline-reports.jsonl')
|
|
498
|
+
const feedPath = path.join(reviewRoot, 'feed.jsonl') // 触らない(テストで不変を確認する)
|
|
499
|
+
const runsFile = opts.runsPath ?? runsPathFor(cfg)
|
|
500
|
+
const readRunsFn = opts.readRuns ?? readRuns
|
|
501
|
+
const writeRunsFn = opts.writeRuns ?? writeRuns
|
|
502
|
+
|
|
503
|
+
let timer = null
|
|
504
|
+
let running = false
|
|
505
|
+
let ticks = 0
|
|
506
|
+
let lastError = null
|
|
507
|
+
|
|
508
|
+
/** 状態を読む(無ければ null = 初回起動)。壊れていても null 扱い(ベースラインからやり直す)。 */
|
|
509
|
+
function readState() {
|
|
510
|
+
try {
|
|
511
|
+
const j = JSON.parse(fs.readFileSync(statePath, 'utf8'))
|
|
512
|
+
if (!j || typeof j !== 'object') return null
|
|
513
|
+
if (typeof j.knownTaskIds !== 'object' || j.knownTaskIds === null) return null
|
|
514
|
+
return {
|
|
515
|
+
version: 1,
|
|
516
|
+
startedAtSec: Number(j.startedAtSec) || 0,
|
|
517
|
+
knownTaskIds: j.knownTaskIds,
|
|
518
|
+
activeGroups: j.activeGroups && typeof j.activeGroups === 'object' ? j.activeGroups : {},
|
|
519
|
+
reportedKeys: Array.isArray(j.reportedKeys) ? j.reportedKeys : [],
|
|
520
|
+
updatedAt: j.updatedAt ?? null,
|
|
521
|
+
}
|
|
522
|
+
} catch {
|
|
523
|
+
return null
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** `.tmp` → rename でアトミックに書く。 */
|
|
528
|
+
function writeState(state) {
|
|
529
|
+
fs.mkdirSync(path.dirname(statePath), { recursive: true })
|
|
530
|
+
const tmp = `${statePath}.tmp`
|
|
531
|
+
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8')
|
|
532
|
+
fs.renameSync(tmp, statePath)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** 監視対象の DB(ボードごとの `kanban.db` + ルート `kanban.db`)。 */
|
|
536
|
+
function dbPaths() {
|
|
537
|
+
if (Array.isArray(opts.dbPaths)) return opts.dbPaths
|
|
538
|
+
const out = []
|
|
539
|
+
const boardsDir = path.join(cfg.kanbanRoot, 'boards')
|
|
540
|
+
try {
|
|
541
|
+
for (const e of fs.readdirSync(boardsDir, { withFileTypes: true })) {
|
|
542
|
+
if (!e.isDirectory()) continue
|
|
543
|
+
const p = path.join(boardsDir, e.name, 'kanban.db')
|
|
544
|
+
if (fs.existsSync(p)) out.push({ board: e.name, path: p })
|
|
545
|
+
}
|
|
546
|
+
} catch {
|
|
547
|
+
/* boards が無い環境では何もしない */
|
|
548
|
+
}
|
|
549
|
+
const rootDb = path.join(cfg.kanbanRoot, 'kanban.db')
|
|
550
|
+
if (fs.existsSync(rootDb)) out.push({ board: null, path: rootDb })
|
|
551
|
+
return out
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/** 1 つの DB から非アーカイブタスクを読む(読み取り専用・失敗は空)。 */
|
|
555
|
+
function readTasks(dbPath) {
|
|
556
|
+
let db
|
|
557
|
+
try {
|
|
558
|
+
db = new DatabaseSync(dbPath, { readOnly: true })
|
|
559
|
+
} catch {
|
|
560
|
+
return []
|
|
561
|
+
}
|
|
562
|
+
try {
|
|
563
|
+
return db
|
|
564
|
+
.prepare(
|
|
565
|
+
`SELECT id, title, body, status, result, created_at, started_at, completed_at, session_id
|
|
566
|
+
FROM tasks
|
|
567
|
+
WHERE COALESCE(status, '') != 'archived'
|
|
568
|
+
ORDER BY COALESCE(completed_at, created_at) DESC
|
|
569
|
+
LIMIT ${TASKS_PER_DB}`,
|
|
570
|
+
)
|
|
571
|
+
.all()
|
|
572
|
+
} catch {
|
|
573
|
+
return []
|
|
574
|
+
} finally {
|
|
575
|
+
try {
|
|
576
|
+
db.close()
|
|
577
|
+
} catch {
|
|
578
|
+
/* noop */
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** 全 DB のタスクを 1 本の配列にする(同じ ID は最初の 1 件)。 */
|
|
584
|
+
function readAllTasks() {
|
|
585
|
+
const out = []
|
|
586
|
+
const seen = new Set()
|
|
587
|
+
for (const { board, path: dbPath } of dbPaths()) {
|
|
588
|
+
for (const t of readTasks(dbPath)) {
|
|
589
|
+
const id = String(t.id ?? '')
|
|
590
|
+
if (!id || seen.has(id)) continue
|
|
591
|
+
seen.add(id)
|
|
592
|
+
out.push({ ...t, id, board: board ?? 'default' })
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
return out
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/** ボードの表示名(`board.json` の name。無ければ slug)。 */
|
|
599
|
+
function boardLabel(board) {
|
|
600
|
+
try {
|
|
601
|
+
const meta = JSON.parse(
|
|
602
|
+
fs.readFileSync(path.join(cfg.kanbanRoot, 'boards', String(board), 'board.json'), 'utf8'),
|
|
603
|
+
)
|
|
604
|
+
return String(meta?.name ?? board)
|
|
605
|
+
} catch {
|
|
606
|
+
return String(board)
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/** ボードの作業ディレクトリ(`board.json` の `default_workdir`)。 */
|
|
611
|
+
function boardWorkdir(board) {
|
|
612
|
+
if (typeof opts.boardWorkdir === 'function') return opts.boardWorkdir(board)
|
|
613
|
+
try {
|
|
614
|
+
const meta = JSON.parse(
|
|
615
|
+
fs.readFileSync(path.join(cfg.kanbanRoot, 'boards', String(board), 'board.json'), 'utf8'),
|
|
616
|
+
)
|
|
617
|
+
return meta?.default_workdir ? String(meta.default_workdir) : null
|
|
618
|
+
} catch {
|
|
619
|
+
return null
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** 宛先解決の候補になる `state.db`(既定 + `profiles/<name>/state.db`)。 */
|
|
624
|
+
function stateDbs() {
|
|
625
|
+
if (Array.isArray(opts.stateDbs)) return opts.stateDbs
|
|
626
|
+
const out = []
|
|
627
|
+
if (cfg.stateDb) out.push(cfg.stateDb)
|
|
628
|
+
const profilesDir = path.join(cfg.hermesHome ?? cfg.home ?? '.', 'profiles')
|
|
629
|
+
try {
|
|
630
|
+
for (const e of fs.readdirSync(profilesDir, { withFileTypes: true })) {
|
|
631
|
+
if (!e.isDirectory()) continue
|
|
632
|
+
const p = path.join(profilesDir, e.name, 'state.db')
|
|
633
|
+
if (fs.existsSync(p)) out.push(p)
|
|
634
|
+
}
|
|
635
|
+
} catch {
|
|
636
|
+
/* profiles が無い環境では既定だけ */
|
|
637
|
+
}
|
|
638
|
+
return out
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** `state.db` から cwd 一致の最新通常セッション `{ id, at }` を 1 件返す。 */
|
|
642
|
+
function latestSessionForCwd(dbPath, workdir) {
|
|
643
|
+
let db
|
|
644
|
+
try {
|
|
645
|
+
db = new DatabaseSync(dbPath, { readOnly: true })
|
|
646
|
+
} catch {
|
|
647
|
+
return null
|
|
648
|
+
}
|
|
649
|
+
const want = normalizePath(workdir)
|
|
650
|
+
try {
|
|
651
|
+
const sql = (order) =>
|
|
652
|
+
`SELECT id, cwd, ${order} AS ts FROM sessions
|
|
653
|
+
WHERE cwd IS NOT NULL AND id NOT LIKE 'local-%'
|
|
654
|
+
ORDER BY ${order} DESC LIMIT 300`
|
|
655
|
+
let rows = []
|
|
656
|
+
try {
|
|
657
|
+
rows = db.prepare(sql('COALESCE(last_activity_at, started_at)')).all()
|
|
658
|
+
} catch {
|
|
659
|
+
rows = db.prepare(sql('started_at')).all()
|
|
660
|
+
}
|
|
661
|
+
for (const r of rows) {
|
|
662
|
+
if (normalizePath(r.cwd) === want) {
|
|
663
|
+
return { id: String(r.id), at: Number(r.ts) || 0 }
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return null
|
|
667
|
+
} catch {
|
|
668
|
+
return null
|
|
669
|
+
} finally {
|
|
670
|
+
try {
|
|
671
|
+
db.close()
|
|
672
|
+
} catch {
|
|
673
|
+
/* noop */
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* タスク群を「Spec ラン」と「ボードウェーブ」に分ける。
|
|
680
|
+
*
|
|
681
|
+
* @param {Array<object>} rows 全タスク
|
|
682
|
+
* @param {Array<object>} runs ラン記録
|
|
683
|
+
* @returns {Array<{base: string, board: string, spec: string|null, tasks: Array<object>, run: object|null}>} グループ
|
|
684
|
+
*/
|
|
685
|
+
function groupTasks(rows, runs) {
|
|
686
|
+
const specs = new Map()
|
|
687
|
+
const waves = new Map()
|
|
688
|
+
for (const row of rows) {
|
|
689
|
+
const spec = specRelFromBody(row.body)
|
|
690
|
+
if (spec) {
|
|
691
|
+
const base = `spec:${row.board}:${spec}`
|
|
692
|
+
if (!specs.has(base)) specs.set(base, { base, board: row.board, spec, tasks: [], run: null })
|
|
693
|
+
specs.get(base).tasks.push(row)
|
|
694
|
+
continue
|
|
695
|
+
}
|
|
696
|
+
if (isReviewBody(row.body)) continue // 個別レビュー報告と二重にしない
|
|
697
|
+
if (!waves.has(row.board)) waves.set(row.board, { base: `wave:${row.board}`, board: row.board, spec: null, tasks: [], run: null })
|
|
698
|
+
waves.get(row.board).tasks.push(row)
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// ラン記録との紐付け(taskIds 一致を優先し、無ければ同一 board+spec の最新ラン)
|
|
702
|
+
for (const g of [...specs.values(), ...waves.values()]) {
|
|
703
|
+
if (!g.spec) {
|
|
704
|
+
const ids = new Set(g.tasks.map((t) => String(t.id)))
|
|
705
|
+
const hit = runs
|
|
706
|
+
.filter((r) => Array.isArray(r.taskIds) && r.taskIds.some((id) => ids.has(String(id))))
|
|
707
|
+
.sort((a, b) => Number(b.createdAt ?? 0) - Number(a.createdAt ?? 0))[0]
|
|
708
|
+
g.run = hit ?? null
|
|
709
|
+
continue
|
|
710
|
+
}
|
|
711
|
+
const byTasks = runs
|
|
712
|
+
.filter((r) => Array.isArray(r.taskIds) && r.taskIds.some((id) => g.tasks.some((t) => String(t.id) === String(id))))
|
|
713
|
+
.sort((a, b) => Number(b.createdAt ?? 0) - Number(a.createdAt ?? 0))[0]
|
|
714
|
+
const byKey = runs
|
|
715
|
+
.filter((r) => String(r.board ?? '') === String(g.board) && String(r.specRelPath ?? '') === String(g.spec))
|
|
716
|
+
.sort((a, b) => Number(b.createdAt ?? 0) - Number(a.createdAt ?? 0))[0]
|
|
717
|
+
g.run = byTasks ?? byKey ?? null
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
return [...specs.values(), ...waves.values()]
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* 宛先チャットの解決(D20②)。
|
|
725
|
+
* `Chat:` → ランの `originSessionId` → `state.db` の cwd 一致最新 → `'__latest__'`。
|
|
726
|
+
*
|
|
727
|
+
* @param {object} group グループ
|
|
728
|
+
* @returns {string} セッション ID
|
|
729
|
+
*/
|
|
730
|
+
function resolveTargetSessionId(group) {
|
|
731
|
+
for (const t of group.tasks) {
|
|
732
|
+
const c = chatFromBody(t.body)
|
|
733
|
+
if (c) return c
|
|
734
|
+
}
|
|
735
|
+
const origin = String(group.run?.originSessionId ?? '').trim()
|
|
736
|
+
if (CHAT_ID_RE.test(origin)) return origin
|
|
737
|
+
const workdir = boardWorkdir(group.board)
|
|
738
|
+
if (workdir) {
|
|
739
|
+
let best = null
|
|
740
|
+
for (const dbPath of stateDbs()) {
|
|
741
|
+
const hit = latestSessionForCwd(dbPath, workdir)
|
|
742
|
+
if (hit && (!best || hit.at > best.at)) best = hit
|
|
743
|
+
}
|
|
744
|
+
if (best) return best.id
|
|
745
|
+
}
|
|
746
|
+
return '__latest__'
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/** spec ファイルのタイトル(読めなければ null)。 */
|
|
750
|
+
function specTitleFromFile(group) {
|
|
751
|
+
const repo = group.run?.repoPath ?? boardWorkdir(group.board)
|
|
752
|
+
if (!repo || !group.spec) return null
|
|
753
|
+
try {
|
|
754
|
+
const text = fs.readFileSync(path.resolve(String(repo), String(group.spec)), 'utf8')
|
|
755
|
+
const m = /^#\s+(.+?)\s*$/m.exec(text)
|
|
756
|
+
return m ? m[1] : null
|
|
757
|
+
} catch {
|
|
758
|
+
return null
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/** Git 情報を集める(gitinfo が無ければ空。失敗は握り潰す)。 */
|
|
763
|
+
async function collectGit(tasks) {
|
|
764
|
+
const out = {}
|
|
765
|
+
const gitinfo = opts.gitinfo
|
|
766
|
+
if (!gitinfo || typeof gitinfo.forTask !== 'function') return out
|
|
767
|
+
for (const t of tasks) {
|
|
768
|
+
try {
|
|
769
|
+
const info = await gitinfo.forTask(String(t.id))
|
|
770
|
+
if (!info) continue
|
|
771
|
+
let diff = null
|
|
772
|
+
if (typeof gitinfo.diffSummary === 'function') {
|
|
773
|
+
diff = await gitinfo.diffSummary(String(t.id))
|
|
774
|
+
if (diff && diff.ok === false) diff = null
|
|
775
|
+
}
|
|
776
|
+
out[String(t.id)] = {
|
|
777
|
+
head: info.head ?? diff?.head ?? '',
|
|
778
|
+
repo: info.repo ?? '',
|
|
779
|
+
total: diff?.total ?? { add: 0, del: 0 },
|
|
780
|
+
files: diff?.files ?? [],
|
|
781
|
+
subject: diff?.subject ?? info.subject ?? '',
|
|
782
|
+
}
|
|
783
|
+
} catch {
|
|
784
|
+
/* git が無い環境でもレポートは出す */
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
return out
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* Spec / Run グループの使用量(API コール数・トークン数)を `usage.js` のスコープ集計で取る。
|
|
792
|
+
*
|
|
793
|
+
* セッション ID がタスク・ランから取れればその群のみ、取れなければグループの実区間で
|
|
794
|
+
* 時間窓フォールバックする(`telemetry.js` のレシートと同じ共通関数を使う)。
|
|
795
|
+
*
|
|
796
|
+
* @param {{tasks: Array<object>, run?: object|null}} group グループ
|
|
797
|
+
* @param {number} nowMs 現在時刻(ms)
|
|
798
|
+
* @returns {object|null} `usage.scoped()` の結果(未設定・失敗時は null)
|
|
799
|
+
*/
|
|
800
|
+
function scopedUsage(group, nowMs) {
|
|
801
|
+
const u = opts.usage
|
|
802
|
+
if (!u || typeof u.scoped !== 'function') return null
|
|
803
|
+
try {
|
|
804
|
+
const sessionIds = [
|
|
805
|
+
...new Set(
|
|
806
|
+
(Array.isArray(group?.tasks) ? group.tasks : [])
|
|
807
|
+
.map((t) => String(t?.session_id ?? '').trim())
|
|
808
|
+
.concat(String(group?.run?.originSessionId ?? '').trim())
|
|
809
|
+
.filter((id) => id && id !== '__latest__'),
|
|
810
|
+
),
|
|
811
|
+
]
|
|
812
|
+
const startSec = (Array.isArray(group?.tasks) ? group.tasks : []).reduce((acc, t) => {
|
|
813
|
+
const v = Number(t?.started_at ?? t?.created_at ?? 0) || 0
|
|
814
|
+
if (!v) return acc
|
|
815
|
+
return acc === 0 ? v : Math.min(acc, v)
|
|
816
|
+
}, 0)
|
|
817
|
+
const r = u.scoped({
|
|
818
|
+
sessionIds,
|
|
819
|
+
sinceMs: startSec * 1000 || nowMs - 24 * 3600 * 1000,
|
|
820
|
+
untilMs: nowMs,
|
|
821
|
+
// state.db のパス一覧(usage.js は {profile, path} を受ける)
|
|
822
|
+
dbs: stateDbs().map((p, i) => ({ profile: i === 0 ? 'default' : `profile${i}`, path: p })),
|
|
823
|
+
})
|
|
824
|
+
return r?.ok ? r : null
|
|
825
|
+
} catch {
|
|
826
|
+
return null
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/** 1 ティック分の走査。テストから直接 await できる。 */
|
|
831
|
+
async function tick() {
|
|
832
|
+
ticks += 1
|
|
833
|
+
const stored = readState()
|
|
834
|
+
const baseline = stored === null
|
|
835
|
+
const nowMs = now()
|
|
836
|
+
const state =
|
|
837
|
+
stored ?? { version: 1, startedAtSec: 0, knownTaskIds: {}, activeGroups: {}, reportedKeys: [], updatedAt: null }
|
|
838
|
+
let dirty = baseline
|
|
839
|
+
|
|
840
|
+
const rows = readAllTasks()
|
|
841
|
+
const runs = readRunsFn(runsFile)
|
|
842
|
+
const groups = groupTasks(rows, runs)
|
|
843
|
+
|
|
844
|
+
if (baseline) {
|
|
845
|
+
// ベースライン: 既存の完了分は通知しない。稼働中の波だけ覚えて完了を待つ。
|
|
846
|
+
state.startedAtSec = Math.floor(nowMs / 1000)
|
|
847
|
+
for (const r of rows) state.knownTaskIds[String(r.id)] = { board: r.board, status: String(r.status ?? '') }
|
|
848
|
+
for (const g of groups) {
|
|
849
|
+
const open = g.tasks.filter((t) => OPEN_STATUSES.has(String(t.status ?? ''))).length
|
|
850
|
+
if (open > 0) state.activeGroups[g.base] = true
|
|
851
|
+
}
|
|
852
|
+
state.updatedAt = new Date(nowMs).toISOString()
|
|
853
|
+
writeState(state)
|
|
854
|
+
return { baseline: true, groups: groups.length, reported: [], statePath }
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const reported = []
|
|
858
|
+
const touchedRuns = new Map()
|
|
859
|
+
|
|
860
|
+
for (const g of groups) {
|
|
861
|
+
const counts = countStatuses(g.tasks)
|
|
862
|
+
const open = counts.running + counts.ready + counts.todo
|
|
863
|
+
const settled = counts.done + counts.blocked + counts.failed
|
|
864
|
+
|
|
865
|
+
if (open > 0) {
|
|
866
|
+
if (!state.activeGroups[g.base]) {
|
|
867
|
+
state.activeGroups[g.base] = true
|
|
868
|
+
dirty = true
|
|
869
|
+
}
|
|
870
|
+
continue
|
|
871
|
+
}
|
|
872
|
+
const wasActive = Boolean(state.activeGroups[g.base])
|
|
873
|
+
if (wasActive) {
|
|
874
|
+
delete state.activeGroups[g.base]
|
|
875
|
+
dirty = true
|
|
876
|
+
}
|
|
877
|
+
if (settled === 0) continue
|
|
878
|
+
|
|
879
|
+
const latestCompletedAt = g.tasks.reduce((a, t) => Math.max(a, Number(t.completed_at ?? 0) || 0), 0)
|
|
880
|
+
const key = g.spec
|
|
881
|
+
? `spec:${g.board}:${g.spec}:${latestCompletedAt}`
|
|
882
|
+
: `wave:${g.board}:${waveHash(g.tasks)}`
|
|
883
|
+
if (state.reportedKeys.includes(key)) continue
|
|
884
|
+
|
|
885
|
+
// ティック間に起票→完了したタスクの取りこぼし防止
|
|
886
|
+
const hasNew = g.tasks.some(
|
|
887
|
+
(t) =>
|
|
888
|
+
!state.knownTaskIds[String(t.id)] && Number(t.completed_at ?? 0) >= Number(state.startedAtSec ?? 0),
|
|
889
|
+
)
|
|
890
|
+
const runPending = Boolean(g.run && !g.run.reportedAt)
|
|
891
|
+
if (!wasActive && !hasNew && !runPending) continue
|
|
892
|
+
|
|
893
|
+
const status = counts.blocked + counts.failed > 0 ? 'halted' : 'done'
|
|
894
|
+
const label = g.spec
|
|
895
|
+
? String(g.run?.title ?? specTitleFromFile(g) ?? g.spec)
|
|
896
|
+
: boardLabel(g.board)
|
|
897
|
+
const gitMap = await collectGit(g.tasks)
|
|
898
|
+
const usageScope = scopedUsage(g, nowMs)
|
|
899
|
+
const report = buildPipelineReport({
|
|
900
|
+
status,
|
|
901
|
+
label,
|
|
902
|
+
board: g.board,
|
|
903
|
+
specRelPath: g.spec,
|
|
904
|
+
tasks: g.tasks,
|
|
905
|
+
gitMap,
|
|
906
|
+
usage: usageScope,
|
|
907
|
+
startedAt: g.tasks.reduce((a, t) => {
|
|
908
|
+
const v = Number(t.started_at ?? t.created_at ?? 0) || 0
|
|
909
|
+
return a === 0 ? v : Math.min(a, v || a)
|
|
910
|
+
}, 0) * 1000 || state.startedAtSec * 1000,
|
|
911
|
+
now: nowMs,
|
|
912
|
+
})
|
|
913
|
+
const sessionId = resolveTargetSessionId(g)
|
|
914
|
+
const at = new Date(nowMs).toISOString()
|
|
915
|
+
const row = {
|
|
916
|
+
at,
|
|
917
|
+
kind: PIPELINE_KIND,
|
|
918
|
+
status,
|
|
919
|
+
session_id: sessionId,
|
|
920
|
+
task_id: `pipeline:${g.board}:${g.run?.id ?? waveHash(g.tasks)}`,
|
|
921
|
+
label,
|
|
922
|
+
board: g.board,
|
|
923
|
+
spec: g.spec,
|
|
924
|
+
repo_path: boardWorkdir(g.board) ?? g.run?.repoPath ?? null,
|
|
925
|
+
text: report.text,
|
|
926
|
+
markdown: report.markdown,
|
|
927
|
+
follow_up_prompt: report.followUpPrompt,
|
|
928
|
+
counts: report.counts,
|
|
929
|
+
}
|
|
930
|
+
appendJsonl(chatReportsPath, row)
|
|
931
|
+
appendJsonl(reportsPath, row)
|
|
932
|
+
if (g.run && !g.run.reportedAt) {
|
|
933
|
+
g.run.reportedAt = at
|
|
934
|
+
touchedRuns.set(String(g.run.id), g.run)
|
|
935
|
+
}
|
|
936
|
+
state.reportedKeys.push(key)
|
|
937
|
+
if (state.reportedKeys.length > REPORTED_KEYS_MAX) {
|
|
938
|
+
state.reportedKeys = state.reportedKeys.slice(-REPORTED_KEYS_MAX)
|
|
939
|
+
}
|
|
940
|
+
dirty = true
|
|
941
|
+
reported.push({ kind: PIPELINE_KIND, status, board: g.board, spec: g.spec, sessionId, taskId: row.task_id })
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// 既知タスクを更新(次ティックで「新規」と誤認しない)
|
|
945
|
+
for (const r of rows) {
|
|
946
|
+
const id = String(r.id)
|
|
947
|
+
const prev = state.knownTaskIds[id]
|
|
948
|
+
if (!prev) {
|
|
949
|
+
state.knownTaskIds[id] = { board: r.board, status: String(r.status ?? '') }
|
|
950
|
+
dirty = true
|
|
951
|
+
continue
|
|
952
|
+
}
|
|
953
|
+
if (prev.status !== String(r.status ?? '')) {
|
|
954
|
+
prev.status = String(r.status ?? '')
|
|
955
|
+
prev.board = r.board
|
|
956
|
+
dirty = true
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
if (touchedRuns.size > 0) {
|
|
961
|
+
try {
|
|
962
|
+
const fresh = readRunsFn(runsFile)
|
|
963
|
+
const merged = fresh.map((r) => touchedRuns.get(String(r.id)) ?? r)
|
|
964
|
+
writeRunsFn(runsFile, merged)
|
|
965
|
+
} catch (err) {
|
|
966
|
+
log.warn?.(`[pipeline-watcher] ランの reportedAt 更新に失敗: ${err?.message ?? err}`)
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
if (dirty) {
|
|
971
|
+
state.updatedAt = new Date(nowMs).toISOString()
|
|
972
|
+
writeState(state)
|
|
973
|
+
}
|
|
974
|
+
return { baseline: false, groups: groups.length, reported, statePath }
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** 例外でプロセスを落とさないティック(定期実行用)。 */
|
|
978
|
+
async function safeTick() {
|
|
979
|
+
if (running) return null
|
|
980
|
+
running = true
|
|
981
|
+
try {
|
|
982
|
+
const r = await tick()
|
|
983
|
+
lastError = null
|
|
984
|
+
return r
|
|
985
|
+
} catch (err) {
|
|
986
|
+
lastError = String(err?.message ?? err)
|
|
987
|
+
log.warn?.(`[pipeline-watcher] ${lastError}`)
|
|
988
|
+
return null
|
|
989
|
+
} finally {
|
|
990
|
+
running = false
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
/** 監視を始める(初回は即ティック=ベースライン確立)。 */
|
|
995
|
+
function start() {
|
|
996
|
+
if (timer) return
|
|
997
|
+
safeTick()
|
|
998
|
+
timer = setInterval(safeTick, intervalMs)
|
|
999
|
+
// ブリッジの停止を妨げない(テストや CLI が終われなくなるため)
|
|
1000
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
function stop() {
|
|
1004
|
+
if (!timer) return
|
|
1005
|
+
clearInterval(timer)
|
|
1006
|
+
timer = null
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
return {
|
|
1010
|
+
intervalMs,
|
|
1011
|
+
statePath,
|
|
1012
|
+
chatReportsPath,
|
|
1013
|
+
reportsPath,
|
|
1014
|
+
feedPath,
|
|
1015
|
+
runsPath: runsFile,
|
|
1016
|
+
tick,
|
|
1017
|
+
start,
|
|
1018
|
+
stop,
|
|
1019
|
+
reports: (o = {}) => readPipelineReports(reviewRoot, o),
|
|
1020
|
+
status: () => ({ running: Boolean(timer), ticks, lastError, statePath }),
|
|
1021
|
+
}
|
|
1022
|
+
}
|