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,28 @@
1
+ import fs from 'node:fs'
2
+
3
+ /**
4
+ * ファイル末尾から最大 `maxBytes` バイトだけを読み込む。
5
+ * 肥大化したログや JSONL を全文 readFileSync しないための共通ヘルパー。
6
+ * 境界で切れた先頭の不完全な 1 行は切り捨てる。
7
+ *
8
+ * @param {string} filePath ファイルパス
9
+ * @param {number} [maxBytes] 読み込む最大バイト数
10
+ * @returns {string} テキスト
11
+ */
12
+ export function readTailText(filePath, maxBytes = 256 * 1024) {
13
+ const limit = Math.max(1024, Number(maxBytes) || 256 * 1024)
14
+ const stat = fs.statSync(filePath)
15
+ if (stat.size <= limit) {
16
+ return fs.readFileSync(filePath, 'utf8')
17
+ }
18
+ const fd = fs.openSync(filePath, 'r')
19
+ try {
20
+ const buf = Buffer.allocUnsafe(limit)
21
+ const bytesRead = fs.readSync(fd, buf, 0, limit, stat.size - limit)
22
+ const raw = buf.subarray(0, bytesRead).toString('utf8')
23
+ const nl = raw.indexOf('\n')
24
+ return nl >= 0 ? raw.slice(nl + 1) : raw
25
+ } finally {
26
+ fs.closeSync(fd)
27
+ }
28
+ }
@@ -0,0 +1,667 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { readTailText } from './tail.js'
4
+ import { readRuns, runsPathFor } from './specs.js'
5
+
6
+ /**
7
+ * Zero-Typing 実行サマリ(完了レシート)の集計(SPEC-PILOT-V5 §3.3 ③ / D26③)。
8
+ *
9
+ * ここは **読み取り専用** の集計だけを行う:
10
+ * - `state.db`(usage.js 経由・全プロファイル合算)… コスト / キャッシュ率 / トークン / ツール回数
11
+ * - `kanban` … 完了タスク数と所要時間(Spec ラン or ボード)
12
+ * - `review/pipeline-reports.jsonl` … 直近の完走レポート(counts・Markdown・タスク result)
13
+ * - `audit.jsonl` … 人間のタップ数(レビュー回答 / 1 タップ検収 / 赤入れ)と手入力文字数
14
+ *
15
+ * 方針:
16
+ * - **ファイル欠損・DB ロック・スキーマ違いで 500 を返さない**。欠けた項目は `null` に落とし、
17
+ * どのソースが読めなかったかを `missing` に列挙する(UI 側で「データ無し」を出す)。
18
+ * - 金額の推定は**保守的**に。`savedUsd` は「キャッシュヒット分の入力単価差額」の概算で、
19
+ * UI 注記(`receipt.savedNote`)で概算である旨を必ず出す。
20
+ */
21
+
22
+ /** 既定の集計窓(時間)。 */
23
+ export const DEFAULT_HOURS = 24
24
+
25
+ /**
26
+ * 手入力の「1 アクション」換算文字数。
27
+ * ゼロタイピング度合い(`zeroTypingScore`)で、打鍵をタップと同列に比較するための粗い換算。
28
+ */
29
+ export const TYPED_CHARS_PER_ACTION = 40
30
+
31
+ /**
32
+ * キャッシュヒットによる割引率(概算)。cache read は入力単価の約 1/10(≒90% 引き)で、
33
+ * その割引は **既に `cost` に反映済み**。よって節約見込額は実コストから逆算する
34
+ * (トークン数×単価で積むと、state.db の単価仮定と二重計上になって実コストを大きく超える)。
35
+ */
36
+ export const CACHE_SAVINGS_RATIO = 0.9
37
+
38
+ /** 1 タップと数える audit 種別(既定 1 回、`choiceCount` があればその数)。 */
39
+ const TAP_KINDS = new Set(['review.answer', 'review.approve', 'review.annotation', 'kanban.close', 'kanban.unblock'])
40
+
41
+ /** 赤入れ(Annotation 送信)として数える audit 種別。 */
42
+ const REDLINE_KINDS = new Set(['review.annotation'])
43
+
44
+ /** 手入力文字数として数える audit 種別(`chars` フィールドを持つもの)。 */
45
+ const TYPED_KINDS = new Set(['kanban.comment', 'kanban.create', 'review.reopen'])
46
+
47
+ /** audit.jsonl から読む末尾バイト数。 */
48
+ const AUDIT_TAIL_BYTES = 512 * 1024
49
+
50
+ /** テスト合格件数を拾う正規表現(英語・日本語の両方)。 */
51
+ const TEST_PATTERNS = [
52
+ /(\d+)\s*(?:tests?|テスト)\s*(?:green|passed|pass|ok|合格)/gi,
53
+ /(?:tests?|テスト)\s*[=::]?\s*(\d+)/gi,
54
+ /(\d+)\s*件の?テスト/gi,
55
+ ]
56
+
57
+ /** PWA チェック件数を拾う正規表現。 */
58
+ const PWA_PATTERNS = [/(?:checks?|チェック)\s*[=::]?\s*(\d+)/gi, /pwa[^\n]{0,24}?(\d+)/gi]
59
+
60
+ /**
61
+ * キャッシュヒット率(0〜1)。分母が 0 なら `null`。
62
+ *
63
+ * `usage.js` と同じ定義(`cacheRead / (input + cacheRead)`)を使う。
64
+ * @param {{input?: number, cacheRead?: number}|null} totals 合計
65
+ * @returns {number|null} 0〜1(算出不能なら null)
66
+ */
67
+ export function cacheHitRate(totals) {
68
+ if (!totals) return null
69
+ const input = Math.max(0, Number(totals.input) || 0)
70
+ const cacheRead = Math.max(0, Number(totals.cacheRead) || 0)
71
+ const denom = input + cacheRead
72
+ if (denom <= 0) return null
73
+ return cacheRead / denom
74
+ }
75
+
76
+ /**
77
+ * キャッシュ分の節約見込額(USD・概算)。
78
+ *
79
+ * `cost` に反映済みのキャッシュ割引を、キャッシュヒット率から保守的に逆算する:
80
+ * `cost × cacheHitRate × ratio`。実コストを超えないので「盛った数字」にならない。
81
+ *
82
+ * @param {{cost?: number, input?: number, cacheRead?: number}|null} totals 合計
83
+ * @param {{ratio?: number}} [opts] 割引率(テスト・将来の設定用)
84
+ * @returns {number|null} USD(算出不能なら null)
85
+ */
86
+ export function estimateSavedUsd(totals, opts = {}) {
87
+ if (!totals) return null
88
+ const cost = Math.max(0, Number(totals.cost) || 0)
89
+ const rate = cacheHitRate(totals)
90
+ if (!cost || rate === null || rate <= 0) return null
91
+ const ratio = Number.isFinite(Number(opts.ratio)) ? Math.min(1, Math.max(0, Number(opts.ratio))) : CACHE_SAVINGS_RATIO
92
+ // 4 桁で丸める(小口でも 0 に潰さない)
93
+ return Math.round((cost * rate * ratio + Number.EPSILON) * 10000) / 10000
94
+ }
95
+
96
+ /**
97
+ * ゼロタイピング度合い(0〜100 の整数・算出不能なら null)。
98
+ *
99
+ * タップ(人間の判断 1 回)と手入力を同じ土俵にするため、手入力は
100
+ * `TYPED_CHARS_PER_ACTION` 文字で 1 アクションに換算する。
101
+ * 例: タップ 20・赤入れ 2・入力 0 文字 → 100。
102
+ *
103
+ * @param {{humanTaps?: number, redlines?: number, typedChars?: number}} ops 操作メトリクス
104
+ * @returns {number|null} 0〜100
105
+ */
106
+ export function zeroTypingScore(ops = {}) {
107
+ const taps = Math.max(0, Number(ops.humanTaps) || 0) + Math.max(0, Number(ops.redlines) || 0)
108
+ const typed = Math.max(0, Number(ops.typedChars) || 0)
109
+ const typedActions = Math.ceil(typed / TYPED_CHARS_PER_ACTION)
110
+ const total = taps + typedActions
111
+ if (total <= 0) return null
112
+ return Math.round((taps / total) * 100)
113
+ }
114
+
115
+ /**
116
+ * audit.jsonl の行から操作メトリクスを集計する。
117
+ *
118
+ * @param {Array<string|object>} lines JSONL の行(文字列 or パース済みオブジェクト)
119
+ * @param {{since?: number}} [opts] この epoch ms より新しい行だけ数える
120
+ * @returns {{humanTaps: number, redlines: number, typedChars: number, entries: number}} 集計
121
+ */
122
+ export function summarizeAudit(lines, opts = {}) {
123
+ const since = Number(opts.since) || 0
124
+ const out = { humanTaps: 0, redlines: 0, typedChars: 0, entries: 0 }
125
+ for (const line of Array.isArray(lines) ? lines : []) {
126
+ let row = line
127
+ if (typeof line === 'string') {
128
+ if (!line.trim()) continue
129
+ try {
130
+ row = JSON.parse(line)
131
+ } catch {
132
+ continue
133
+ }
134
+ }
135
+ if (!row || typeof row !== 'object') continue
136
+ const kind = String(row.kind ?? '')
137
+ if (!kind) continue
138
+ const at = Date.parse(String(row.at ?? ''))
139
+ if (since > 0 && Number.isFinite(at) && at <= since) continue
140
+ out.entries += 1
141
+ if (TAP_KINDS.has(kind)) {
142
+ const n = Math.max(0, Number(row.choiceCount) || 0)
143
+ out.humanTaps += Math.max(1, n)
144
+ }
145
+ if (REDLINE_KINDS.has(kind) && row.ok !== false) out.redlines += 1
146
+ if (TYPED_KINDS.has(kind)) {
147
+ const chars = Number(row.chars)
148
+ if (Number.isFinite(chars) && chars > 0) out.typedChars += chars
149
+ }
150
+ }
151
+ return out
152
+ }
153
+
154
+ /**
155
+ * テキスト群からテスト合格件数・PWA チェック件数を拾う(最新の検証結果ヒント)。
156
+ *
157
+ * タスク `result` やレポート Markdown は自由文なので、**取れたら使う** 程度の扱い。
158
+ * 拾えなければ `null`。
159
+ *
160
+ * @param {Array<string|null|undefined>} texts 対象テキスト
161
+ * @returns {{tests: number|null, pwaChecks: number|null}} 件数
162
+ */
163
+ export function extractTestCounts(texts) {
164
+ const haystack = (Array.isArray(texts) ? texts : []).filter(Boolean).map(String).join('\n')
165
+ const maxOf = (patterns) => {
166
+ let best = null
167
+ for (const re of patterns) {
168
+ for (const m of haystack.matchAll(re)) {
169
+ const n = Number(m[1])
170
+ if (!Number.isFinite(n) || n <= 0) continue
171
+ if (best === null || n > best) best = n
172
+ }
173
+ }
174
+ return best
175
+ }
176
+ return { tests: maxOf(TEST_PATTERNS), pwaChecks: maxOf(PWA_PATTERNS) }
177
+ }
178
+
179
+ /**
180
+ * Spec パスの照合(`docs/SPEC-V5.md` と絶対パス・`./` 付きを同一視する)。
181
+ *
182
+ * @param {string|null|undefined} a レポート側の spec
183
+ * @param {string|null|undefined} b 要求側の spec
184
+ * @returns {boolean} 一致するか(要求が空なら true)
185
+ */
186
+ export function sameSpec(a, b) {
187
+ const want = String(b ?? '').trim()
188
+ if (!want) return true
189
+ const got = String(a ?? '').trim()
190
+ if (!got) return false
191
+ const norm = (s) => s.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
192
+ const x = norm(got)
193
+ const y = norm(want)
194
+ return x === y || x.endsWith(`/${y}`) || y.endsWith(`/${x}`)
195
+ }
196
+
197
+ /**
198
+ * 時刻値を epoch ms へ正規化する(epoch 秒・ms・ISO 文字列・不正値をすべて受ける)。
199
+ *
200
+ * カンバン DB は **秒**(`started_at`)、API 応答は **ms**(`startedAt`)なので、
201
+ * 1e12 未満は秒として扱う。0 以下・解釈不能は `0`(=区間なし)。
202
+ *
203
+ * @param {unknown} value 時刻
204
+ * @returns {number} epoch ms(不明なら 0)
205
+ */
206
+ export function toMs(value) {
207
+ if (value === null || value === undefined || value === '') return 0
208
+ if (typeof value === 'number') {
209
+ if (!Number.isFinite(value) || value <= 0) return 0
210
+ return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
211
+ }
212
+ const raw = String(value).trim()
213
+ if (!raw) return 0
214
+ if (/^\d+(\.\d+)?$/.test(raw)) return toMs(Number(raw))
215
+ const parsed = Date.parse(raw)
216
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
217
+ }
218
+
219
+ /** タスクの ID(camel / snake 両対応)。 */
220
+ function taskIdOf(task) {
221
+ return String(task?.id ?? task?.taskId ?? '').trim()
222
+ }
223
+
224
+ /** タスクの開始時刻(ms)。`startedAt` が無ければ `createdAt`。 */
225
+ function taskStartMs(task) {
226
+ return toMs(task?.startedAt ?? task?.started_at) || toMs(task?.createdAt ?? task?.created_at)
227
+ }
228
+
229
+ /** タスクの完了時刻(ms)。未完了は 0。 */
230
+ function taskEndMs(task) {
231
+ return toMs(task?.completedAt ?? task?.completed_at)
232
+ }
233
+
234
+ /** タスクが持つ Spec パス(命名ゆれを吸収)。 */
235
+ function taskSpecOf(task) {
236
+ return task?.specRelPath ?? task?.spec ?? task?.specPath ?? task?.spec_path ?? null
237
+ }
238
+
239
+ /** タイトル先頭の `[BatchID]`(無ければ null)。 */
240
+ function batchIdOf(task) {
241
+ const m = /^\s*\[([^\]]{1,32})\]/.exec(String(task?.title ?? ''))
242
+ return m ? m[1].trim() : null
243
+ }
244
+
245
+ /**
246
+ * 重なり合う区間を 1 本にマージする(並列タスクの二重計上を消す)。
247
+ *
248
+ * 例: `[[0, 60], [30, 90], [200, 230]]` → `[[0, 90], [200, 230]]`(合計 120 分。
249
+ * 単純な差分だと 150 分になる)。
250
+ *
251
+ * @param {Array<[number, number]>} intervals 区間(ms)
252
+ * @returns {Array<[number, number]>} マージ済み(開始昇順・負区間は捨てる)
253
+ */
254
+ export function mergeIntervals(intervals) {
255
+ const list = (Array.isArray(intervals) ? intervals : [])
256
+ .map((pair) => [Number(pair?.[0]) || 0, Number(pair?.[1]) || 0])
257
+ .filter(([s, e]) => e > s && s >= 0)
258
+ .sort((a, b) => a[0] - b[0])
259
+ const out = []
260
+ for (const [s, e] of list) {
261
+ const last = out[out.length - 1]
262
+ if (last && s <= last[1]) last[1] = Math.max(last[1], e)
263
+ else out.push([s, e])
264
+ }
265
+ return out
266
+ }
267
+
268
+ /**
269
+ * 対象 Spec / Run に属するタスクだけを残す(時間・バッチ計算の入口)。
270
+ *
271
+ * 優先順位:
272
+ * 1. `opts.taskIds`(`pipeline-runs.json` のラン記録)との ID 一致
273
+ * 2. タスク自身が持つ Spec パスと `opts.spec` の一致
274
+ * 3. タイトル先頭の `[BatchID]` が `opts.batchIds` に含まれる
275
+ *
276
+ * どれも指定されていなければ **絞り込まない**(ボード全体の集計)。Spec を指定して
277
+ * 1 件も一致しなければ空を返す(別タスクで補完しない)。
278
+ *
279
+ * @param {Array<object>} tasks タスク
280
+ * @param {{spec?: string|null, taskIds?: Array<string>, batchIds?: Array<string>}} [opts] スコープ
281
+ * @returns {{tasks: Array<object>, scoped: boolean, taskIds: Array<string>, batchIds: Array<string>}} 絞り込み結果
282
+ */
283
+ export function selectSpecTasks(tasks, opts = {}) {
284
+ const list = Array.isArray(tasks) ? tasks.filter(Boolean) : []
285
+ const spec = String(opts.spec ?? '').trim()
286
+ const taskIds = [...new Set((Array.isArray(opts.taskIds) ? opts.taskIds : []).map((v) => String(v)).filter(Boolean))]
287
+ const batchIds = [...new Set((Array.isArray(opts.batchIds) ? opts.batchIds : []).map((v) => String(v)).filter(Boolean))]
288
+ const idSet = new Set(taskIds)
289
+ const batchSet = new Set(batchIds)
290
+ if (!spec && !idSet.size && !batchSet.size) {
291
+ return { tasks: list, scoped: false, taskIds: [], batchIds: [] }
292
+ }
293
+ const matched = list.filter((task) => {
294
+ if (idSet.size && idSet.has(taskIdOf(task))) return true
295
+ if (spec && sameSpec(taskSpecOf(task), spec)) return true
296
+ const batch = batchIdOf(task)
297
+ return Boolean(batch && batchSet.has(batch))
298
+ })
299
+ return { tasks: matched, scoped: true, taskIds, batchIds }
300
+ }
301
+
302
+ /**
303
+ * `pipeline-runs.json` のラン記録から対象 Spec / ボードのランを選ぶ(最新優先)。
304
+ *
305
+ * @param {Array<object>} runs ラン記録
306
+ * @param {{spec?: string|null, board?: string|null, tasks?: Array<object>}} [opts] 条件
307
+ * @returns {object|null} ラン(無ければ null)
308
+ */
309
+ export function pickSpecRun(runs, opts = {}) {
310
+ const list = (Array.isArray(runs) ? runs : []).filter((r) => r && typeof r === 'object')
311
+ if (!list.length) return null
312
+ const spec = String(opts.spec ?? '').trim()
313
+ const board = String(opts.board ?? '').trim()
314
+ const onBoard = list.filter((r) => !board || !r.board || String(r.board) === board)
315
+ const newest = (arr) =>
316
+ arr.slice().sort((a, b) => (Number(b.createdAt ?? 0) || 0) - (Number(a.createdAt ?? 0) || 0))[0] ?? null
317
+ if (spec) {
318
+ const hit = onBoard.filter((r) => sameSpec(r.specRelPath ?? r.spec, spec))
319
+ if (hit.length) return newest(hit)
320
+ }
321
+ const ids = new Set((Array.isArray(opts.tasks) ? opts.tasks : []).map(taskIdOf).filter(Boolean))
322
+ if (ids.size) {
323
+ const hit = onBoard.filter((r) => Array.isArray(r.taskIds) && r.taskIds.some((id) => ids.has(String(id))))
324
+ if (hit.length) return newest(hit)
325
+ }
326
+ return null
327
+ }
328
+
329
+ /**
330
+ * タスク群から status 件数と所要時間を出す。
331
+ *
332
+ * 所要時間は **並列区間をマージした実稼働時間**(`durationMin` = `activeDurationMin`)と
333
+ * 単純経過時間(`wallDurationMin`)の 2 本立て:
334
+ * - 実稼働: 各タスクの `[start, end]` を昇順ソートし、重なり(`a2 <= b1`)をマージした合計
335
+ * - 経過: `min(start)` 〜 `max(end)`(参考値)
336
+ *
337
+ * 集計窓(`since`)より前に始まった区間は窓の開始へ切り上げ、`durationCapped` を立てる
338
+ * (「33,000 分」のような数字を出さないための既存の安全弁)。実行中タスクの終端は
339
+ * `opts.now` が渡されたときだけ `now` で閉じる(渡さないと際限なく伸びるため)。
340
+ *
341
+ * @param {Array<object>} tasks タスク(camel / snake 両対応)
342
+ * @param {{since?: number, now?: number, spec?: string|null, taskIds?: Array<string>, batchIds?: Array<string>}} [opts] 条件
343
+ * @returns {{
344
+ * batchesDone: number, batchesTotal: number, durationMin: number|null,
345
+ * activeDurationMin: number|null, wallDurationMin: number|null,
346
+ * durationCapped: boolean, intervalCount: number, startMs: number, endMs: number, scoped: boolean
347
+ * }} 集計
348
+ */
349
+ export function summarizeTasks(tasks, opts = {}) {
350
+ const since = Number(opts.since) || 0
351
+ const nowMs = Number(opts.now) || 0
352
+ const scoped = selectSpecTasks(tasks, opts)
353
+ const list = scoped.tasks
354
+ const done = list.filter((t) => String(t?.status ?? '') === 'done').length
355
+ const intervals = []
356
+ let capped = false
357
+ for (const task of list) {
358
+ const start = taskStartMs(task)
359
+ const end = taskEndMs(task)
360
+ let s = 0
361
+ let e = 0
362
+ if (start > 0 && end > start) {
363
+ s = start
364
+ e = end
365
+ } else if (start > 0 && end <= 0 && nowMs > start) {
366
+ // 実行中(completedAt がまだ無い): now が分かっているときだけ閉じる
367
+ s = start
368
+ e = nowMs
369
+ } else {
370
+ continue
371
+ }
372
+ if (since > 0 && s < since) {
373
+ capped = true
374
+ s = since
375
+ }
376
+ if (nowMs > 0 && e > nowMs) e = nowMs
377
+ if (e > s) intervals.push([s, e])
378
+ }
379
+ const merged = mergeIntervals(intervals)
380
+ const activeMs = merged.reduce((acc, [s, e]) => acc + (e - s), 0)
381
+ const toMin = (ms) => (ms > 0 ? Math.max(1, Math.round(ms / 60000)) : null)
382
+ const durationMin = toMin(activeMs)
383
+ const first = merged.length ? merged[0][0] : 0
384
+ const last = merged.length ? merged[merged.length - 1][1] : 0
385
+ const batchesTotal = list.length || (Array.isArray(opts.batchIds) ? opts.batchIds.length : 0)
386
+ return {
387
+ batchesDone: done,
388
+ batchesTotal,
389
+ durationMin,
390
+ activeDurationMin: durationMin,
391
+ wallDurationMin: toMin(last - first),
392
+ durationCapped: capped,
393
+ intervalCount: merged.length,
394
+ startMs: first,
395
+ endMs: last,
396
+ scoped: scoped.scoped,
397
+ }
398
+ }
399
+
400
+ /**
401
+ * `usage.scoped()` の結果から KPI 用の 2 値(API コール数・合計トークン数)を取り出す。
402
+ *
403
+ * 合計トークンは `input + output + cacheRead + cacheWrite`(`usage.js` と同じ定義)。
404
+ * スコープ集計が失敗していれば `null`(=「—」。0 と区別する)。
405
+ *
406
+ * @param {{ok?: boolean, apiCalls?: number, totalTokens?: number, totals?: object}|null} scope スコープ集計
407
+ * @returns {{apiCalls: number|null, totalTokens: number|null, sessions: number|null}} KPI 値
408
+ */
409
+ export function usageKpis(scope) {
410
+ if (!scope) return { apiCalls: null, totalTokens: null, sessions: null }
411
+ if (scope.ok === false) return { apiCalls: null, totalTokens: null, sessions: null }
412
+ const totals = scope.totals ?? {}
413
+ const num = (v) => Math.max(0, Number(v) || 0)
414
+ const apiCalls = Number.isFinite(Number(scope.apiCalls)) ? num(scope.apiCalls) : num(totals.calls)
415
+ const totalTokens = Number.isFinite(Number(scope.totalTokens))
416
+ ? num(scope.totalTokens)
417
+ : num(totals.input) + num(totals.output) + num(totals.cacheRead) + num(totals.cacheWrite)
418
+ return { apiCalls, totalTokens, sessions: num(totals.sessions) }
419
+ }
420
+
421
+ /**
422
+ * 集計済みの材料から Receipt データを組み立てる(純関数・テスト対象)。
423
+ *
424
+ * @param {{
425
+ * board?: string|null,
426
+ * spec?: string|null,
427
+ * label?: string|null,
428
+ * generatedAt?: number,
429
+ * hours?: number,
430
+ * taskIds?: Array<string>,
431
+ * batchIds?: Array<string>,
432
+ * usage?: {totals?: object, cacheHitRate?: number|null, models?: Array<object>}|null,
433
+ * usageScope?: {ok?: boolean, apiCalls?: number, totalTokens?: number, totals?: object, scope?: object}|null,
434
+ * report?: {status?: string, label?: string|null, markdown?: string, counts?: object|null, at?: number}|null,
435
+ * tasks?: Array<object>,
436
+ * ops?: {humanTaps?: number, redlines?: number, typedChars?: number}|null,
437
+ * missing?: Array<string>,
438
+ * }} input 材料
439
+ * @returns {object} `/api/telemetry/receipt` の応答
440
+ */
441
+ export function buildReceipt(input = {}) {
442
+ const generatedAt = Number(input.generatedAt) || Date.now()
443
+ const hours = Math.min(Math.max(Number(input.hours) || DEFAULT_HOURS, 1), 24 * 30)
444
+ const totals = input.usage?.totals ?? null
445
+ const rate = Number.isFinite(Number(input.usage?.cacheHitRate)) ? Number(input.usage.cacheHitRate) : cacheHitRate(totals)
446
+ const savedUsd = estimateSavedUsd(totals)
447
+ const ops = {
448
+ humanTaps: Math.max(0, Number(input.ops?.humanTaps) || 0),
449
+ redlines: Math.max(0, Number(input.ops?.redlines) || 0),
450
+ typedChars: Math.max(0, Number(input.ops?.typedChars) || 0),
451
+ }
452
+ // Spec / Run スコープに厳密に絞る(別タスクの startedAt〜completedAt を混ぜない)
453
+ const taskSummary = summarizeTasks(input.tasks ?? [], {
454
+ since: generatedAt - hours * 3600 * 1000,
455
+ now: generatedAt,
456
+ spec: input.spec,
457
+ taskIds: input.taskIds,
458
+ batchIds: input.batchIds,
459
+ })
460
+ // API コール数・トークン数は usage.js のスコープ集計(セッション群 or 時間窓)から取る
461
+ const scoped = usageKpis(input.usageScope)
462
+ const scopedOk = Boolean(input.usageScope && input.usageScope.ok !== false)
463
+ const fallbackCalls = totals ? Math.max(0, Number(totals.calls) || 0) : null
464
+ const fallbackTokens = totals
465
+ ? Math.max(0, Number(totals.input) || 0) +
466
+ Math.max(0, Number(totals.output) || 0) +
467
+ Math.max(0, Number(totals.cacheRead) || 0) +
468
+ Math.max(0, Number(totals.cacheWrite) || 0)
469
+ : null
470
+ const reportCounts = input.report?.counts && typeof input.report.counts === 'object' ? input.report.counts : null
471
+ const tests = extractTestCounts([
472
+ input.report?.markdown ?? '',
473
+ ...(Array.isArray(input.tasks) ? input.tasks.map((t) => t?.result ?? '') : []),
474
+ ])
475
+ const missing = Array.isArray(input.missing) ? [...new Set(input.missing.filter(Boolean))] : []
476
+
477
+ return {
478
+ ok: true,
479
+ generatedAt,
480
+ board: input.board ? String(input.board) : null,
481
+ spec: input.spec ? String(input.spec) : null,
482
+ label: input.label ? String(input.label) : null,
483
+ windowHours: hours,
484
+ status: input.report?.status ? String(input.report.status) : null,
485
+ scope: {
486
+ // どのタスクが時間・バッチ計算に入ったか(監査用。数字の根拠を追えるようにする)
487
+ scoped: taskSummary.scoped,
488
+ taskIds: Array.isArray(input.taskIds) ? input.taskIds.map(String) : [],
489
+ batchIds: Array.isArray(input.batchIds) ? input.batchIds.map(String) : [],
490
+ tasks: taskSummary.batchesTotal,
491
+ intervals: taskSummary.intervalCount,
492
+ usage: input.usageScope?.scope ?? null,
493
+ usageScoped: scopedOk,
494
+ },
495
+ kpi: {
496
+ costUsd: totals ? Math.round((Number(totals.cost) || 0) * 10000) / 10000 : null,
497
+ cacheHitRate: rate,
498
+ cachePct: rate === null ? null : Math.round(rate * 100),
499
+ savedUsd,
500
+ savedRatio: CACHE_SAVINGS_RATIO,
501
+ cacheReadTokens: totals ? Number(totals.cacheRead) || 0 : null,
502
+ inputTokens: totals ? Number(totals.input) || 0 : null,
503
+ outputTokens: totals ? Number(totals.output) || 0 : null,
504
+ toolCalls: totals ? Number(totals.tools) || 0 : null,
505
+ sessions: totals ? Number(totals.sessions) || 0 : null,
506
+ humanTaps: ops.humanTaps,
507
+ redlines: ops.redlines,
508
+ typedChars: ops.typedChars,
509
+ zeroTypingScore: zeroTypingScore(ops),
510
+ batchesDone: reportCounts ? Number(reportCounts.done) || 0 : taskSummary.batchesDone,
511
+ batchesTotal: reportCounts
512
+ ? Number(reportCounts.total) || taskSummary.batchesTotal
513
+ : taskSummary.batchesTotal || null,
514
+ // 主指標は「重複区間をマージした実稼働時間」。経過時間は参考値として併記する
515
+ durationMin: taskSummary.durationMin,
516
+ activeDurationMin: taskSummary.activeDurationMin,
517
+ wallDurationMin: taskSummary.wallDurationMin,
518
+ durationCapped: taskSummary.durationCapped,
519
+ apiCalls: scopedOk ? scoped.apiCalls : fallbackCalls,
520
+ totalTokens: scopedOk ? scoped.totalTokens : fallbackTokens,
521
+ tests: tests.tests,
522
+ pwaChecks: tests.pwaChecks,
523
+ },
524
+ missing,
525
+ }
526
+ }
527
+
528
+ /**
529
+ * テレメトリ集計器を作る。
530
+ *
531
+ * @param {object} cfg ブリッジ設定(`reviewDir` / `auditPath` / `stateDb` / `pluginDataDir`)
532
+ * @param {{
533
+ * usage?: {summary: Function, scoped?: Function},
534
+ * reports?: (opts: object) => Array<object>,
535
+ * tasks?: (board: string) => Array<object>,
536
+ * runs?: () => Array<object>,
537
+ * now?: () => number,
538
+ * }} [deps] 差し替え(テスト用)
539
+ * @returns {{receipt: Function}} 集計器
540
+ */
541
+ export function createTelemetry(cfg = {}, deps = {}) {
542
+ const reviewDir = String(cfg.reviewDir ?? '')
543
+ const auditPath = String(cfg.auditPath ?? '')
544
+ const now = typeof deps.now === 'function' ? deps.now : () => Date.now()
545
+ const readRunsFn = typeof deps.runs === 'function' ? deps.runs : () => readRuns(runsPathFor(cfg))
546
+
547
+ /**
548
+ * `GET /api/telemetry/receipt` の本体。ファイル欠損は握りつぶして `missing` に積む。
549
+ *
550
+ * Spec が指定されたときは `pipeline-runs.json` のラン(`taskIds` / `batchIds`)で
551
+ * タスクを絞り、そのセッション群(取れなければ Run の時間窓)で `apiCalls` /
552
+ * `totalTokens` を `usage.scoped()` から集計する。
553
+ *
554
+ * @param {{board?: string, spec?: string, hours?: number, dbs?: Array<object>}} [opts] 条件
555
+ * @returns {object} Receipt データ
556
+ */
557
+ function receipt(opts = {}) {
558
+ const hours = Math.min(Math.max(Number(opts.hours) || DEFAULT_HOURS, 1), 24 * 30)
559
+ const board = String(opts.board ?? '').trim()
560
+ const spec = String(opts.spec ?? '').trim()
561
+ const generatedAt = now()
562
+ const missing = []
563
+
564
+ let usage = null
565
+ try {
566
+ const u = deps.usage?.summary?.({ hours, dbs: opts.dbs ?? [] })
567
+ if (u?.ok) usage = u
568
+ else missing.push('usage')
569
+ } catch {
570
+ missing.push('usage')
571
+ }
572
+
573
+ let report = null
574
+ try {
575
+ const rows = typeof deps.reports === 'function' ? deps.reports({ board, limit: 100 }) : []
576
+ report = (Array.isArray(rows) ? rows : []).find((r) => sameSpec(r?.spec, spec)) ?? null
577
+ if (!report) missing.push('report')
578
+ } catch {
579
+ missing.push('report')
580
+ }
581
+
582
+ let tasks = []
583
+ if (board && typeof deps.tasks === 'function') {
584
+ try {
585
+ tasks = deps.tasks(board) ?? []
586
+ } catch {
587
+ missing.push('tasks')
588
+ }
589
+ } else {
590
+ missing.push('tasks')
591
+ }
592
+
593
+ // ランレコード(Spec スコープの ID 群)→ 対象タスクの絞り込み。
594
+ // Spec 未指定(ボード全体のレシート)ではランに寄せず、ボード全体をそのまま集計する。
595
+ let runs = []
596
+ try {
597
+ const r = readRunsFn()
598
+ runs = Array.isArray(r) ? r : []
599
+ } catch {
600
+ runs = []
601
+ }
602
+ const run = spec ? pickSpecRun(runs, { spec, board, tasks }) : null
603
+ const taskIds = Array.isArray(run?.taskIds) ? run.taskIds.map(String) : []
604
+ const batchIds = Array.isArray(run?.batchIds) ? run.batchIds.map(String) : []
605
+ const scopedTasks = selectSpecTasks(tasks, { spec, taskIds, batchIds }).tasks
606
+
607
+ const timing = summarizeTasks(scopedTasks, {
608
+ since: generatedAt - hours * 3600 * 1000,
609
+ now: generatedAt,
610
+ })
611
+ const sessionIds = [
612
+ ...new Set(
613
+ scopedTasks
614
+ .map((t) => String(t?.sessionId ?? t?.session_id ?? t?.session ?? '').trim())
615
+ .concat(String(run?.originSessionId ?? '').trim())
616
+ .filter(Boolean),
617
+ ),
618
+ ]
619
+
620
+ let usageScope = null
621
+ if (typeof deps.usage?.scoped === 'function') {
622
+ try {
623
+ const r = deps.usage.scoped({
624
+ sessionIds,
625
+ // セッションが取れないときは Run の実区間(無ければ集計窓)で安全にフォールバックする
626
+ sinceMs: timing.startMs || generatedAt - hours * 3600 * 1000,
627
+ untilMs: timing.endMs || generatedAt,
628
+ dbs: opts.dbs ?? [],
629
+ })
630
+ if (r?.ok) usageScope = r
631
+ else missing.push('usageScope')
632
+ } catch {
633
+ missing.push('usageScope')
634
+ }
635
+ }
636
+
637
+ let ops = { humanTaps: 0, redlines: 0, typedChars: 0 }
638
+ try {
639
+ const file = auditPath || path.join(String(cfg.dataDir ?? ''), 'audit.jsonl')
640
+ if (!fs.existsSync(file)) throw new Error('missing')
641
+ const raw = readTailText(file, AUDIT_TAIL_BYTES)
642
+ ops = summarizeAudit(raw.split('\n'), { since: generatedAt - hours * 3600 * 1000 })
643
+ } catch {
644
+ missing.push('audit')
645
+ }
646
+
647
+ const built = buildReceipt({
648
+ board,
649
+ spec,
650
+ label: report?.label ?? null,
651
+ generatedAt,
652
+ hours,
653
+ taskIds,
654
+ batchIds,
655
+ usage,
656
+ usageScope,
657
+ report,
658
+ tasks: scopedTasks,
659
+ ops,
660
+ missing,
661
+ })
662
+ // 同じファイル群を二重に読まないよう、レビューディレクトリは参照だけ持たせる(将来の拡張用)
663
+ return { ...built, reviewDir: reviewDir || null }
664
+ }
665
+
666
+ return { receipt }
667
+ }