hermes-pilot 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +390 -0
  3. package/README.md +398 -2
  4. package/__init__.py +15 -0
  5. package/apps/bridge/src/api-errors.js +165 -0
  6. package/apps/bridge/src/architect.js +1298 -0
  7. package/apps/bridge/src/auth.js +202 -0
  8. package/apps/bridge/src/capabilities.js +256 -0
  9. package/apps/bridge/src/capture.js +145 -0
  10. package/apps/bridge/src/chat-profile.js +95 -0
  11. package/apps/bridge/src/config.js +73 -0
  12. package/apps/bridge/src/discord.js +89 -0
  13. package/apps/bridge/src/gitinfo.js +211 -0
  14. package/apps/bridge/src/hermes.js +97 -0
  15. package/apps/bridge/src/inbox.js +347 -0
  16. package/apps/bridge/src/kanban.js +361 -0
  17. package/apps/bridge/src/lang.js +60 -0
  18. package/apps/bridge/src/live.js +285 -0
  19. package/apps/bridge/src/memos.js +150 -0
  20. package/apps/bridge/src/ops.js +201 -0
  21. package/apps/bridge/src/pair-codes.js +125 -0
  22. package/apps/bridge/src/pipeline-optimizer.js +358 -0
  23. package/apps/bridge/src/pipeline-watcher.js +1018 -0
  24. package/apps/bridge/src/qr.js +808 -0
  25. package/apps/bridge/src/repos.js +544 -0
  26. package/apps/bridge/src/review-watcher.js +271 -0
  27. package/apps/bridge/src/review.js +1749 -0
  28. package/apps/bridge/src/search.js +162 -0
  29. package/apps/bridge/src/server.js +1738 -0
  30. package/apps/bridge/src/snippets.js +373 -0
  31. package/apps/bridge/src/specs.js +734 -0
  32. package/apps/bridge/src/tail.js +28 -0
  33. package/apps/bridge/src/telemetry.js +667 -0
  34. package/apps/bridge/src/term-snippets.js +228 -0
  35. package/apps/bridge/src/transcript.js +231 -0
  36. package/apps/bridge/src/usage.js +294 -0
  37. package/apps/bridge/src/workerFeed.js +72 -0
  38. package/apps/dashboard/index.js +2014 -0
  39. package/apps/dashboard/manifest.json +14 -0
  40. package/apps/dashboard/pilot_dashboard.py +1466 -0
  41. package/apps/dashboard/plugin_api.py +237 -0
  42. package/apps/dashboard/plugin_init.py +15 -0
  43. package/apps/dashboard/style.css +928 -0
  44. package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
  45. package/apps/web/dist/assets/TermPane-U500JD2P.js +12 -0
  46. package/apps/web/dist/assets/index-6iFDsB0G.css +1 -0
  47. package/apps/web/dist/assets/index-X4Bi2FWB.js +94 -0
  48. package/apps/web/dist/favicon.ico +0 -0
  49. package/apps/web/dist/icon-180-v6.png +0 -0
  50. package/apps/web/dist/icon-192-v6.png +0 -0
  51. package/apps/web/dist/icon-512-v6.png +0 -0
  52. package/apps/web/dist/icon-maskable-192-v6.png +0 -0
  53. package/apps/web/dist/icon-maskable-512-v6.png +0 -0
  54. package/apps/web/dist/icon-v6.svg +15 -0
  55. package/apps/web/dist/index.html +21 -0
  56. package/apps/web/dist/manifest.webmanifest +49 -0
  57. package/apps/web/dist/sw.js +69 -0
  58. package/bin/hermes-pilot.mjs +964 -0
  59. package/dashboard/dist/index.js +2014 -0
  60. package/dashboard/dist/style.css +928 -0
  61. package/dashboard/manifest.json +14 -0
  62. package/dashboard/pilot_dashboard.py +1466 -0
  63. package/dashboard/plugin_api.py +237 -0
  64. package/package.json +75 -4
  65. package/plugin.json +70 -0
  66. package/plugin.yaml +4 -0
  67. package/scripts/deploy.mjs +58 -0
  68. package/scripts/migrate-to-hermes-pilot.mjs +472 -0
  69. package/scripts/postinstall.mjs +32 -0
  70. package/scripts/sync-dashboard.mjs +98 -0
  71. package/skills/annotation/SKILL.md +103 -0
  72. package/skills/quick-review/SKILL.md +170 -0
  73. package/skills/quick-review/assets/sheet-template.html +175 -0
  74. package/skills/spec-architect/SKILL.md +175 -0
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 言語解決の共通ロジック(ブリッジ側)。
3
+ *
4
+ * - `?lang=ja` などのクエリが最優先(明示指定)
5
+ * - 次に `Accept-Language`(q 値の高い順。`ja` で始まれば ja、それ以外は en)
6
+ * - どちらも無ければ既定 `en`(フォールバック言語・SPEC §6.1)
7
+ */
8
+
9
+ export const LANGS = ['en', 'ja']
10
+ export const DEFAULT_LANG = 'en'
11
+
12
+ /**
13
+ * 1 つの言語タグを `en` / `ja` に落とす(未知は null)。
14
+ * @param {unknown} value タグ
15
+ * @returns {'en'|'ja'|null} 正規化
16
+ */
17
+ export function normalizeLang(value) {
18
+ if (value == null) return null
19
+ const s = String(value).trim().toLowerCase()
20
+ if (!s) return null
21
+ if (s.startsWith('ja')) return 'ja'
22
+ if (s.startsWith('en')) return 'en'
23
+ return null
24
+ }
25
+
26
+ /**
27
+ * Accept-Language ヘッダーを解釈する。
28
+ * q 値の降順で最初のタグを見て、`ja` で始まれば ja、それ以外は en。
29
+ * ヘッダーが空・不正なら null(=呼び出し側の既定に任せる)。
30
+ * @param {string} [header] ヘッダー値
31
+ * @returns {'en'|'ja'|null} 言語
32
+ */
33
+ export function fromAcceptLanguage(header) {
34
+ const raw = String(header ?? '').trim()
35
+ if (!raw) return null
36
+ const entries = raw
37
+ .split(',')
38
+ .map((part, i) => {
39
+ const [tag, ...attrs] = part.trim().split(';')
40
+ let q = 1
41
+ for (const a of attrs) {
42
+ const m = /^\s*q\s*=\s*([0-9.]+)\s*$/i.exec(a)
43
+ if (m) q = Number(m[1])
44
+ }
45
+ return { tag: tag.trim().toLowerCase(), q: Number.isFinite(q) ? q : 1, i }
46
+ })
47
+ .filter((e) => e.tag && e.tag !== '*')
48
+ .sort((x, y) => (y.q - x.q) || (x.i - y.i))
49
+ if (!entries.length) return null
50
+ return entries[0].tag.startsWith('ja') ? 'ja' : 'en'
51
+ }
52
+
53
+ /**
54
+ * リクエストから表示言語を決める。
55
+ * @param {{queryLang?: unknown, acceptLanguage?: string, fallback?: 'en'|'ja'}} [input] 入力
56
+ * @returns {'en'|'ja'} 言語
57
+ */
58
+ export function resolveLang({ queryLang, acceptLanguage, fallback = DEFAULT_LANG } = {}) {
59
+ return normalizeLang(queryLang) ?? fromAcceptLanguage(acceptLanguage) ?? normalizeLang(fallback) ?? DEFAULT_LANG
60
+ }
@@ -0,0 +1,285 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import { DatabaseSync } from 'node:sqlite'
4
+
5
+ /**
6
+ * ライブ進捗(いま何が動いているか)。
7
+ *
8
+ * - 実行中ターン: `state.db` の `session_turn_leases`(本体が張るリース)を読むだけ
9
+ * - 最後のツール: そのセッションの直近 `messages.tool_name`
10
+ * - 実行中タスク: カンバン(既存の kanban モジュール)から status='running'
11
+ *
12
+ * 書き込みはしない。5秒ポーリング前提なので、DB は毎回開いて閉じる(読取のみ・数ms)。
13
+ */
14
+
15
+ /** holder 文字列から platform を取り出す(例: "pid=123:turn=…:platform=discord")。 */
16
+ export function platformOf(holder) {
17
+ const m = /platform=([a-z0-9_-]+)/i.exec(String(holder ?? ''))
18
+ return m ? m[1] : null
19
+ }
20
+
21
+ /** リース期限の猶予(秒)。更新が数秒遅れても「終わった」と誤判定しない。 */
22
+ const LEASE_GRACE_SEC = 60
23
+
24
+ /**
25
+ * Architect(仕様策定)ジョブのうち **LiveSheet の一覧に載せる** 状態。
26
+ *
27
+ * `awaiting_review`(赤ペン待ち)は 🔔 判断待ちピルが受け持つので件数には数えないが、
28
+ * 「いま何が動いているか」を見る場所としては一覧に出す(SPEC-PILOT-V9 §3.2)。
29
+ */
30
+ export const ARCHITECT_LIST_STATUSES = ['running', 'awaiting_spec', 'awaiting_review']
31
+
32
+ /** `counts.architect`(⚡ 実行中)に数える状態。 */
33
+ export const ARCHITECT_RUNNING_STATUSES = ['running', 'awaiting_spec']
34
+
35
+ /**
36
+ * 停滞とみなす経過(3分)。`architect.js` の `STALLED_AFTER_MS` と同値で、
37
+ * あちらが `stalled` を返すようになったらそちらを優先する(この値はその手前の保険)。
38
+ */
39
+ export const ARCHITECT_STALLED_MS = 180_000
40
+
41
+ /**
42
+ * ジョブの状態 → フェーズの控えめな写像。
43
+ *
44
+ * 正規のフェーズ算出は `architect.js#computePhase`(V9-B1)が持ち、`job.phase` があれば
45
+ * そちらをそのまま使う。ここは B1 未適用でも `phase` が空にならないためのフォールバック。
46
+ *
47
+ * @param {string} status ジョブ状態
48
+ * @returns {string} フェーズ名
49
+ */
50
+ export function phaseOfStatus(status) {
51
+ const s = String(status ?? '')
52
+ if (['awaiting_review', 'spec_ready', 'launched', 'failed'].includes(s)) return s
53
+ return 'spawning'
54
+ }
55
+
56
+ /**
57
+ * Architect ジョブを LiveSheet 用に整形する(機密は持たない)。
58
+ *
59
+ * @param {object} job `architect.jobs()` の 1 件(`publicJob` の形)
60
+ * @param {number} [at] 現在時刻
61
+ * @returns {object} LiveSheet 用
62
+ */
63
+ export function shapeArchitectJob(job, at = Date.now()) {
64
+ const status = String(job?.status ?? '')
65
+ const started = Number(job?.startedAt ?? job?.createdAt ?? 0) || 0
66
+ // 停滞判定は architect.js が持つ。無い場合だけ 3 分ルールをここで当てる(SPEC V9 §3.1 と同じ条件)。
67
+ const stalled =
68
+ typeof job?.stalled === 'boolean'
69
+ ? job.stalled
70
+ : ARCHITECT_RUNNING_STATUSES.includes(status) &&
71
+ job?.queueState !== 'queued' &&
72
+ started > 0 &&
73
+ at - started >= ARCHITECT_STALLED_MS
74
+ return {
75
+ id: job?.id ?? null,
76
+ board: job?.board ?? null,
77
+ runner: job?.runner ?? null,
78
+ runnerLabel: job?.runnerLabel ?? job?.runner ?? null,
79
+ status,
80
+ phase: typeof job?.phase === 'string' && job.phase ? job.phase : phaseOfStatus(status),
81
+ stalled,
82
+ taskId: job?.taskId ?? null,
83
+ reviewTaskId: job?.reviewTaskId ?? null,
84
+ reviewBoard: job?.reviewBoard ?? null,
85
+ seed: String(job?.seed ?? '').slice(0, 200),
86
+ startedAt: started || null,
87
+ elapsedSec: started ? Math.max(0, Math.round((at - started) / 1000)) : null,
88
+ }
89
+ }
90
+
91
+ export function createLive(cfg, kanban, deps = {}) {
92
+ const dbPath = cfg.stateDb ?? path.join(cfg.home ?? '', '.hermes', 'state.db')
93
+
94
+ /**
95
+ * 1つの DB から実行中ターンを読む。
96
+ *
97
+ * **期限切れのリースは実行中ではない。** ターンは 5 分のリースを更新しながら走るので、
98
+ * `expires_at` を過ぎた行は「終わったが行が残っている」もの(実測: 前日のリースが
99
+ * `expiresInSec=-79488` で稼働中として並んだ)。更新の遅れを吸収するため 60 秒だけ猶予を置く。
100
+ *
101
+ * @param {{profile: string, path: string}} target DB情報
102
+ * @param {number} at 現在時刻
103
+ * @returns {Array<object>} ターン一覧
104
+ */
105
+ function turnsFrom(target, at) {
106
+ let db
107
+ try {
108
+ db = new DatabaseSync(target.path, { readOnly: true })
109
+ const rows = db
110
+ .prepare(
111
+ `SELECT l.conversation_id, l.holder, l.acquired_at, l.expires_at,
112
+ s.title, s.source, s.chat_type, s.last_activity_description,
113
+ s.last_activity_at
114
+ FROM session_turn_leases l
115
+ LEFT JOIN sessions s ON s.id = l.conversation_id
116
+ WHERE l.expires_at > ?
117
+ ORDER BY l.acquired_at DESC`,
118
+ )
119
+ .all(at / 1000 - LEASE_GRACE_SEC)
120
+ const lastToolStmt = db.prepare(
121
+ `SELECT tool_name, timestamp FROM messages
122
+ WHERE session_id = ? AND tool_name IS NOT NULL
123
+ ORDER BY id DESC LIMIT 1`,
124
+ )
125
+ return rows.map((r) => {
126
+ let lastTool = null
127
+ try {
128
+ const t = lastToolStmt.get(r.conversation_id)
129
+ if (t?.tool_name) lastTool = { name: t.tool_name, at: Math.round(Number(t.timestamp) * 1000) }
130
+ } catch {
131
+ /* noop */
132
+ }
133
+ const acquired = Math.round(Number(r.acquired_at ?? 0) * 1000)
134
+ const expires = Math.round(Number(r.expires_at ?? 0) * 1000)
135
+ return {
136
+ profile: target.profile || 'default',
137
+ sessionId: r.conversation_id,
138
+ title: r.title || r.conversation_id,
139
+ source: r.source ?? '',
140
+ platform: platformOf(r.holder),
141
+ startedAt: acquired || null,
142
+ elapsedSec: acquired ? Math.max(0, Math.round((at - acquired) / 1000)) : null,
143
+ expiresInSec: expires ? Math.round((expires - at) / 1000) : null,
144
+ lastActivity: r.last_activity_description ?? null,
145
+ lastTool,
146
+ }
147
+ })
148
+ } finally {
149
+ try {
150
+ db?.close()
151
+ } catch {
152
+ /* noop */
153
+ }
154
+ }
155
+ }
156
+
157
+ /**
158
+ * いま動いているもの。
159
+ * @param {{dbs?: Array<{profile: string, path: string}>}} [opts] 条件
160
+ * @returns {object} スナップショット
161
+ */
162
+ function baseSnapshot(opts = {}) {
163
+ const at = Date.now()
164
+ const out = { ok: true, at, turns: [], tasks: [], architect: [], counts: { turns: 0, tasks: 0, architect: 0 } }
165
+
166
+ // 実行中タスク(ボード横断)
167
+ try {
168
+ const runs = []
169
+ for (const b of kanban.boards()) {
170
+ for (const t of kanban.tasks(b.slug, { limit: 80 })) {
171
+ if (t.status !== 'running') continue
172
+ runs.push({
173
+ id: t.id,
174
+ title: t.title,
175
+ board: b.slug,
176
+ boardName: b.name,
177
+ elapsedSec: t.elapsedSec,
178
+ workerPid: t.workerPid,
179
+ })
180
+ }
181
+ }
182
+ out.tasks = runs.sort((a, b) => (b.elapsedSec ?? 0) - (a.elapsedSec ?? 0))
183
+ out.counts.tasks = runs.length
184
+ } catch {
185
+ out.tasks = []
186
+ }
187
+
188
+ // 実行中ターン(リース)
189
+ const rawDbs = Array.isArray(opts.dbs) && opts.dbs.length ? opts.dbs : [{ profile: 'default', path: dbPath }]
190
+ const targets = rawDbs.filter((d) => d?.path && fs.existsSync(d.path))
191
+ if (!targets.length) {
192
+ out.ok = false
193
+ out.reason = 'state.db が見つかりません'
194
+ return out
195
+ }
196
+ const turns = []
197
+ let firstErr = null
198
+ let succeeded = 0
199
+ for (const target of targets) {
200
+ try {
201
+ turns.push(...turnsFrom(target, at))
202
+ succeeded++
203
+ } catch (e) {
204
+ if (!firstErr) firstErr = e
205
+ }
206
+ }
207
+ if (!succeeded && firstErr) {
208
+ out.ok = false
209
+ out.reason = `読み取りに失敗しました: ${firstErr.message}`
210
+ return out
211
+ }
212
+ turns.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))
213
+ out.turns = turns
214
+ out.counts.turns = turns.length
215
+ return out
216
+ }
217
+
218
+ /**
219
+ * アクティブな Architect ジョブを一覧と件数へ落とし込む。
220
+ *
221
+ * - 一覧(`out.architect`): `running` / `awaiting_spec` / `awaiting_review` で未破棄のもの
222
+ * - 件数(`out.counts.architect`): そのうち `running` / `awaiting_spec` だけ
223
+ * (`awaiting_review` は 🔔 判断待ちピルが数えるので二重計上しない)
224
+ *
225
+ * @param {object} out スナップショット
226
+ * @param {Array<object>|unknown} raw `architect.jobs()` の `jobs`
227
+ * @returns {object} 同じ `out`
228
+ */
229
+ function withArchitect(out, raw) {
230
+ const at = Number(out.at) || Date.now()
231
+ const list = Array.isArray(raw) ? raw : []
232
+ const jobs = []
233
+ for (const job of list) {
234
+ if (!job || job.dismissed) continue
235
+ if (!ARCHITECT_LIST_STATUSES.includes(String(job.status ?? ''))) continue
236
+ jobs.push(shapeArchitectJob(job, at))
237
+ }
238
+ jobs.sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0))
239
+ out.architect = jobs
240
+ out.counts = {
241
+ ...(out.counts ?? {}),
242
+ architect: jobs.filter((j) => ARCHITECT_RUNNING_STATUSES.includes(j.status)).length,
243
+ }
244
+ return out
245
+ }
246
+
247
+ /**
248
+ * Architect ジョブの供給元を決める(`opts.architect` → `opts.architectJobs` → `deps.architectJobs`)。
249
+ * @param {object} opts snapshot 引数
250
+ * @returns {Array<object>|Promise<Array<object>>|Function|null} 一覧・Promise・関数
251
+ */
252
+ function architectSource(opts) {
253
+ const given = opts.architect !== undefined ? opts.architect : opts.architectJobs
254
+ if (given !== undefined) return given
255
+ return typeof deps.architectJobs === 'function' ? deps.architectJobs : null
256
+ }
257
+
258
+ /**
259
+ * いま動いているもの(ターン・タスク・Architect ジョブ)。
260
+ *
261
+ * Architect の一覧を **配列**で渡せば同期に、**Promise** で渡せば同じ結果を `await` で返す
262
+ * (`server.js` は `await architect.jobs()` の結果を配列で渡す・SPEC V9 §3.2)。
263
+ *
264
+ * @param {{dbs?: Array<{profile: string, path: string}>, architect?: unknown, architectJobs?: unknown}} [opts] 条件
265
+ * @returns {object|Promise<object>} スナップショット(Promise を渡したときだけ Promise)
266
+ */
267
+ function snapshot(opts = {}) {
268
+ let source = null
269
+ try {
270
+ source = architectSource(opts)
271
+ if (typeof source === 'function') source = source()
272
+ } catch {
273
+ source = []
274
+ }
275
+ if (source && typeof source.then === 'function') {
276
+ const base = baseSnapshot(opts)
277
+ return Promise.resolve(source)
278
+ .then((list) => withArchitect(base, list))
279
+ .catch(() => withArchitect(base, []))
280
+ }
281
+ return withArchitect(baseSnapshot(opts), source)
282
+ }
283
+
284
+ return { snapshot }
285
+ }
@@ -0,0 +1,150 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import crypto from 'node:crypto'
4
+ import { ApiError } from './api-errors.js'
5
+
6
+ /**
7
+ * メモ・ひらめき・定期レポート受信箱ストア(`memos.json`)。
8
+ *
9
+ * Google Keep 風にメモ、チェックリスト、チャット切り抜き、定期レポートの保存先を
10
+ * 1 ファイルへ永続化する(最大 500 件)。
11
+ */
12
+
13
+ const MAX_MEMOS = 500
14
+ const MAX_TITLE = 160
15
+ const MAX_BODY = 10_000
16
+ const MAX_TAGS = 12
17
+ const MAX_CHECKLIST = 50
18
+ const COLORS = new Set(['default', 'teal', 'amber', 'violet'])
19
+ const KINDS = new Set(['note', 'report', 'clip'])
20
+
21
+ function normalizeTags(raw) {
22
+ if (!Array.isArray(raw)) return []
23
+ const seen = new Set()
24
+ const out = []
25
+ for (const item of raw) {
26
+ const clean = String(item ?? '')
27
+ .trim()
28
+ .replace(/^#+/, '')
29
+ .slice(0, 32)
30
+ if (!clean || seen.has(clean.toLowerCase())) continue
31
+ seen.add(clean.toLowerCase())
32
+ out.push(clean)
33
+ if (out.length >= MAX_TAGS) break
34
+ }
35
+ return out
36
+ }
37
+
38
+ function normalizeChecklist(raw) {
39
+ if (!Array.isArray(raw)) return []
40
+ const out = []
41
+ for (const item of raw) {
42
+ if (!item || typeof item !== 'object') continue
43
+ const text = String(item.text ?? '').trim().slice(0, 300)
44
+ if (!text) continue
45
+ const id = String(item.id ?? '').trim() || `c_${crypto.randomBytes(4).toString('hex')}`
46
+ out.push({ id, text, done: Boolean(item.done) })
47
+ if (out.length >= MAX_CHECKLIST) break
48
+ }
49
+ return out
50
+ }
51
+
52
+ function normalizeSource(raw) {
53
+ if (!raw || typeof raw !== 'object') return null
54
+ const out = {}
55
+ for (const k of ['chatId', 'chatTitle', 'board', 'repo', 'mid', 'reportKey']) {
56
+ const v = raw[k]
57
+ if (v != null && String(v).trim()) out[k] = String(v).trim().slice(0, 200)
58
+ }
59
+ return Object.keys(out).length ? out : null
60
+ }
61
+
62
+ function sortMemos(list) {
63
+ return [...list].sort((a, b) => {
64
+ if (Boolean(a.pinned) !== Boolean(b.pinned)) return a.pinned ? -1 : 1
65
+ return String(b.updatedAt ?? b.createdAt ?? '').localeCompare(String(a.updatedAt ?? a.createdAt ?? ''))
66
+ })
67
+ }
68
+
69
+ export function createMemosStore(dataDir) {
70
+ const file = path.join(dataDir, 'memos.json')
71
+
72
+ function readAll() {
73
+ try {
74
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'))
75
+ return Array.isArray(raw?.memos) ? raw.memos : []
76
+ } catch {
77
+ return []
78
+ }
79
+ }
80
+
81
+ function writeAll(memos) {
82
+ fs.mkdirSync(dataDir, { recursive: true })
83
+ const tmp = `${file}.tmp-${process.pid}`
84
+ fs.writeFileSync(tmp, JSON.stringify({ memos: memos.slice(0, MAX_MEMOS) }, null, 2))
85
+ fs.renameSync(tmp, file)
86
+ }
87
+
88
+ function list() {
89
+ return sortMemos(readAll())
90
+ }
91
+
92
+ function create(input = {}) {
93
+ const title = String(input.title ?? '').trim().slice(0, MAX_TITLE)
94
+ const body = String(input.body ?? '').trim().slice(0, MAX_BODY)
95
+ const checklist = normalizeChecklist(input.checklist)
96
+ if (!title && !body && !checklist.length) {
97
+ throw new ApiError('MEMO_EMPTY', {}, 400)
98
+ }
99
+ const now = new Date().toISOString()
100
+ const memo = {
101
+ id: `m_${crypto.randomBytes(5).toString('hex')}`,
102
+ title,
103
+ body,
104
+ tags: normalizeTags(input.tags),
105
+ pinned: Boolean(input.pinned),
106
+ color: COLORS.has(input.color) ? input.color : 'default',
107
+ kind: KINDS.has(input.kind) ? input.kind : 'note',
108
+ checklist,
109
+ source: normalizeSource(input.source),
110
+ createdAt: now,
111
+ updatedAt: now,
112
+ }
113
+ const next = sortMemos([memo, ...readAll()]).slice(0, MAX_MEMOS)
114
+ writeAll(next)
115
+ return memo
116
+ }
117
+
118
+ function update(id, patch = {}) {
119
+ const targetId = String(id ?? '').trim()
120
+ const all = readAll()
121
+ const idx = all.findIndex((m) => m.id === targetId)
122
+ if (idx === -1) throw new ApiError('MEMO_NOT_FOUND', {}, 404)
123
+ const cur = all[idx]
124
+ const updated = {
125
+ ...cur,
126
+ ...(patch.title !== undefined ? { title: String(patch.title ?? '').trim().slice(0, MAX_TITLE) } : {}),
127
+ ...(patch.body !== undefined ? { body: String(patch.body ?? '').trim().slice(0, MAX_BODY) } : {}),
128
+ ...(patch.tags !== undefined ? { tags: normalizeTags(patch.tags) } : {}),
129
+ ...(patch.pinned !== undefined ? { pinned: Boolean(patch.pinned) } : {}),
130
+ ...(patch.color !== undefined && COLORS.has(patch.color) ? { color: patch.color } : {}),
131
+ ...(patch.kind !== undefined && KINDS.has(patch.kind) ? { kind: patch.kind } : {}),
132
+ ...(patch.checklist !== undefined ? { checklist: normalizeChecklist(patch.checklist) } : {}),
133
+ updatedAt: new Date().toISOString(),
134
+ }
135
+ all[idx] = updated
136
+ writeAll(sortMemos(all))
137
+ return updated
138
+ }
139
+
140
+ function remove(id) {
141
+ const targetId = String(id ?? '').trim()
142
+ const all = readAll()
143
+ const next = all.filter((m) => m.id !== targetId)
144
+ if (next.length === all.length) throw new ApiError('MEMO_NOT_FOUND', {}, 404)
145
+ writeAll(next)
146
+ return { ok: true, id: targetId }
147
+ }
148
+
149
+ return { list, create, update, remove }
150
+ }
@@ -0,0 +1,201 @@
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
+ * 運用系(状態の俯瞰 + キルスイッチ)。
9
+ *
10
+ * `/api/overview` は **Hermes 標準 API とブリッジ自身のメトリクスだけ**で組み立てる
11
+ * (SPEC §5.2)。外部プラグインのエンドポイントは叩かない。
12
+ *
13
+ * キルスイッチは Hermes 自身の API を叩く(生の launchctl は使わない)。
14
+ * 実測した挙動:
15
+ * - drain … 新規ターンを止め、実行中は完走
16
+ * - restart … SIGUSR1 → 実行中ターンの完了を待って再起動(最大1800秒)
17
+ * - stop … interrupt=true で実行中も停止
18
+ *
19
+ * 緊急停止(pause / resume)だけは CLI を使う(`~/.hermes/ESTOP` センチネルを本体が管理する)。
20
+ *
21
+ * @param {object} cfg 設定
22
+ * @param {object} hermes Hermes クライアント
23
+ * @param {object} auth 認証(監査用)
24
+ * @param {{kanban?: object}} [deps] 差し替え(テスト用)
25
+ * @returns {object} 運用操作
26
+ */
27
+ export function createOps(cfg, hermes, auth, deps = {}) {
28
+ const startedAt = Number(cfg.startedAt ?? Date.now())
29
+ const GATEWAY_ACTIONS = new Map([
30
+ ['drain', '/api/gateway/drain'],
31
+ ['restart', '/api/gateway/restart'],
32
+ ['stop', '/api/gateway/stop?interrupt=true'],
33
+ ['start', '/api/gateway/start'],
34
+ ])
35
+
36
+ /**
37
+ * カンバン集計(自前メトリクス)。板が読めなくても落ちない。
38
+ * @returns {{boards: number, running: number, blocked: number, ready: number, reviewWaiting: number}} 集計
39
+ */
40
+ function kanbanSummary() {
41
+ const empty = { boards: 0, running: 0, blocked: 0, ready: 0, reviewWaiting: 0 }
42
+ let boards = []
43
+ try {
44
+ boards = deps.kanban?.boards?.() ?? []
45
+ } catch {
46
+ boards = []
47
+ }
48
+ if (!Array.isArray(boards) || !boards.length) return empty
49
+ const live = boards.filter((b) => b && !b.archived)
50
+ const sum = (k) => live.reduce((n, b) => n + Number(b.counts?.[k] ?? 0), 0)
51
+ const blocked = sum('blocked')
52
+ return {
53
+ boards: live.length,
54
+ running: sum('running'),
55
+ blocked,
56
+ ready: sum('ready'),
57
+ // 判断待ち(blocked)は人間の回答を待っている件数=Review 待ち
58
+ reviewWaiting: blocked,
59
+ }
60
+ }
61
+
62
+ /** 画面のカード分をまとめて取る(片方が落ちても他は返す)。 */
63
+ async function overview() {
64
+ const [status, stats] = await Promise.allSettled([
65
+ hermes.call('/api/status', { timeoutMs: 8000 }),
66
+ hermes.call('/api/system/stats', { timeoutMs: 8000 }),
67
+ ])
68
+ const s = status.status === 'fulfilled' && status.value.status === 200 ? status.value.data : null
69
+ const sys = stats.status === 'fulfilled' && stats.value.status === 200 ? stats.value.data : null
70
+ return {
71
+ hermes: s
72
+ ? {
73
+ version: s.version,
74
+ model: s.model ?? null,
75
+ gateway: s.gateway ?? null,
76
+ sessions: s.sessions ?? null,
77
+ profiles: s.profiles ?? null,
78
+ }
79
+ : null,
80
+ system: sys
81
+ ? {
82
+ cpuCount: sys.cpu_count ?? null,
83
+ memory: sys.memory ?? null,
84
+ disk: sys.disk ?? null,
85
+ load: sys.loadavg ?? null,
86
+ uptime: sys.uptime ?? null,
87
+ }
88
+ : null,
89
+ /** ブリッジ自身の稼働状態(自前メトリクス) */
90
+ bridge: {
91
+ ok: Boolean(s),
92
+ version: String(cfg.version ?? ''),
93
+ port: Number(cfg.port ?? 0) || null,
94
+ startedAt,
95
+ uptimeSec: Math.max(0, Math.round((Date.now() - startedAt) / 1000)),
96
+ },
97
+ /** カンバン集計(自前メトリクス) */
98
+ kanban: kanbanSummary(),
99
+ checkedAt: Date.now(),
100
+ }
101
+ }
102
+
103
+ /**
104
+ * キルスイッチ。`confirm` が正しくないと実行しない(誤爆防止)。
105
+ * @param {string} action drain|restart|stop|start
106
+ * @param {string} confirm 画面で入力/長押しした確認語
107
+ * @param {string} by 実行者(端末識別)
108
+ * @returns {Promise<object>} 結果
109
+ */
110
+ async function gateway(action, confirm, by = 'mobile') {
111
+ const pathname = GATEWAY_ACTIONS.get(action)
112
+ if (!pathname) {
113
+ throw new ApiError('ACTION_INVALID', { action }, 400)
114
+ }
115
+ const expected = action === 'drain' ? 'DRAIN' : action.toUpperCase()
116
+ if (String(confirm ?? '').toUpperCase() !== expected) {
117
+ throw new ApiError('CONFIRM_MISMATCH', { expected }, 400)
118
+ }
119
+ const res = await hermes.call(pathname, { method: 'POST', body: {}, timeoutMs: 30000 })
120
+ const ok = res.status >= 200 && res.status < 300
121
+ auth.audit({ kind: `gateway.${action}`, ok, status: res.status, by, result: res.data })
122
+ if (!ok) {
123
+ const detail = res.data?.detail ?? res.data?.error?.message ?? `HTTP ${res.status}`
124
+ throw new ApiError('HERMES_REJECTED', { status: res.status }, 502)
125
+ }
126
+ return { ok, action, result: res.data, at: Date.now() }
127
+ }
128
+
129
+ /**
130
+ * 緊急停止(ESTOP)の状態。`~/.hermes/ESTOP` を読むだけ。
131
+ * @returns {{engaged: boolean, reason: string|null, engagedAt: string|null}} 状態
132
+ */
133
+ function paused() {
134
+ const p = path.join(cfg.hermesHome, 'ESTOP')
135
+ try {
136
+ if (!fs.existsSync(p)) return { engaged: false, reason: null, engagedAt: null }
137
+ let raw = {}
138
+ try {
139
+ raw = JSON.parse(fs.readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
140
+ } catch {
141
+ raw = {}
142
+ }
143
+ return {
144
+ engaged: true,
145
+ reason: typeof raw?.reason === 'string' ? raw.reason : null,
146
+ engagedAt: typeof raw?.engaged_at === 'string' ? raw.engaged_at : null,
147
+ }
148
+ } catch {
149
+ return { engaged: false, reason: null, engagedAt: null }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * 緊急停止(新規作業のみ停止。実行中は完走)。
155
+ * CLI `hermes pause` を実行する(センチネルを自前で書かない)。
156
+ * @param {string} reason 理由
157
+ * @param {string} by 実行者
158
+ * @returns {Promise<object>} 結果
159
+ */
160
+ async function pause(reason = 'mobile', by = 'mobile') {
161
+ const res = await runHermes(['pause', '--reason', String(reason).slice(0, 200)])
162
+ const state = paused()
163
+ auth.audit({ kind: 'gateway.pause', ok: res.code === 0, by, reason, state })
164
+ if (res.code !== 0) {
165
+ throw new ApiError('CLI_FAILED', {}, 502)
166
+ }
167
+ return { ok: true, action: 'pause', state, output: res.out.slice(0, 400), at: Date.now() }
168
+ }
169
+
170
+ /**
171
+ * 緊急停止を解除する。
172
+ * @param {string} by 実行者
173
+ * @returns {Promise<object>} 結果
174
+ */
175
+ async function resume(by = 'mobile') {
176
+ const res = await runHermes(['resume'])
177
+ const state = paused()
178
+ auth.audit({ kind: 'gateway.resume', ok: res.code === 0, by, state })
179
+ if (res.code !== 0) {
180
+ throw new ApiError('CLI_FAILED', {}, 502)
181
+ }
182
+ return { ok: true, action: 'resume', state, output: res.out.slice(0, 400), at: Date.now() }
183
+ }
184
+
185
+ /** `hermes <args>` を実行する(シェルを介さない。テストでは runner を差し替え可)。 */
186
+ function runHermes(args) {
187
+ if (cfg.runner) return cfg.runner(args)
188
+ return new Promise((resolve) => {
189
+ execFile(
190
+ cfg.hermesBin ?? resolveHermesBin(),
191
+ args,
192
+ { timeout: 20_000, maxBuffer: 1_000_000, env: { ...process.env, PATH: buildAugmentedPath() } },
193
+ (err, stdout, stderr) => {
194
+ resolve({ code: err ? (err.code ?? 1) : 0, out: `${stdout ?? ''}${stderr ?? ''}`.trim() })
195
+ },
196
+ )
197
+ })
198
+ }
199
+
200
+ return { overview, gateway, paused, pause, resume }
201
+ }