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,544 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import os from 'node:os'
4
+ import { execFile } from 'node:child_process'
5
+ import { DatabaseSync } from 'node:sqlite'
6
+
7
+ /**
8
+ * リポジトリ(作業ディレクトリ)の自動検出と、カンバンボードとの対応。
9
+ *
10
+ * 旧来の個人プラグインの設定ファイルには**依存しない**。一覧は次の 4 ソースを
11
+ * `normalizePath` で重複排除して統合する(SPEC §5.1 / D4):
12
+ * 1. ユーザー設定 `repos.json`(`custom`)+ `scanDirs` 直下 1 階層の `.git` 自動スキャン
13
+ * 2. カンバン各ボードの `default_workdir`
14
+ * 3. `state.db` の直近セッション `cwd`
15
+ * 4. 手動追加(`custom`)・非表示(`hidden`)・ピン留め(`pinned`)
16
+ *
17
+ * macOS は大文字小文字を区別しないので比較は小文字で行う(実測: `~/projects/...` と
18
+ * `~/Projects/...` が混在している)。パスは**表示用に元の表記**を残す。
19
+ */
20
+
21
+ /** 自動スキャンのキャッシュ TTL(SPEC §5.1: 30 秒)。 */
22
+ export const SCAN_TTL_MS = 30_000
23
+
24
+ /** `state.db` の cwd から拾う候補の上限。 */
25
+ const SESSION_LIMIT = 8
26
+
27
+ /** ホーム直下の探索候補(実在するものだけ使う)。 */
28
+ const DEFAULT_SCAN_DIRS = ['~/Projects', '~/projects']
29
+
30
+ /**
31
+ * パス比較用の正規化(~ 展開・絶対化・小文字化・末尾スラッシュ落とし)。
32
+ * @param {string} p パス
33
+ * @param {string} [home] ホーム(テスト用)
34
+ * @returns {string} 正規化済みパス
35
+ */
36
+ export function normalizePath(p, home = os.homedir()) {
37
+ const raw = String(p ?? '').trim()
38
+ if (!raw) return ''
39
+ const abs = path.resolve(expandHome(raw, home))
40
+ const lower = abs.toLowerCase()
41
+ return lower.length > 1 ? lower.replace(/[/\\]+$/, '') : lower
42
+ }
43
+
44
+ /**
45
+ * `~` を展開して絶対パスにする(表記はそのまま)。
46
+ * @param {string} p パス
47
+ * @param {string} [home] ホーム
48
+ * @returns {string} 絶対パス
49
+ */
50
+ export function expandHome(p, home = os.homedir()) {
51
+ const raw = String(p ?? '').trim()
52
+ if (!raw) return ''
53
+ if (raw === '~') return home
54
+ if (raw.startsWith('~/')) return path.join(home, raw.slice(2))
55
+ return path.isAbsolute(raw) ? raw : path.resolve(home, raw)
56
+ }
57
+
58
+ /**
59
+ * そのディレクトリが Git リポジトリか(`.git` はディレクトリでも worktree のファイルでもよい)。
60
+ * @param {string} dir ディレクトリ
61
+ * @returns {boolean} Git 管理下なら true
62
+ */
63
+ export function isGitRepo(dir) {
64
+ const abs = String(dir ?? '').trim()
65
+ if (!abs) return false
66
+ try {
67
+ return fs.existsSync(path.join(abs, '.git'))
68
+ } catch {
69
+ return false
70
+ }
71
+ }
72
+
73
+ /**
74
+ * パスからボード名に使える id を作る(`[a-z0-9._-]` 以外は `-`)。
75
+ * @param {string} dir パス
76
+ * @returns {string} id
77
+ */
78
+ export function repoIdFromPath(dir) {
79
+ const base = path.basename(String(dir ?? '').trim()) || 'repo'
80
+ const id = base
81
+ .toLowerCase()
82
+ .replace(/[^a-z0-9._-]+/g, '-')
83
+ .replace(/^-+|-+$/g, '')
84
+ .slice(0, 64)
85
+ return id || 'repo'
86
+ }
87
+
88
+ /**
89
+ * 空の設定(初回起動時の既定)。`scanDirs` は実在する既定候補だけ。
90
+ * @param {string} [home] ホーム
91
+ * @returns {{scanDirs: string[], pinned: string[], hidden: string[], custom: Array<object>}} 設定
92
+ */
93
+ export function defaultReposConfig(home = os.homedir()) {
94
+ return {
95
+ scanDirs: DEFAULT_SCAN_DIRS.filter((d) => {
96
+ try {
97
+ return fs.statSync(expandHome(d, home)).isDirectory()
98
+ } catch {
99
+ return false
100
+ }
101
+ }),
102
+ pinned: [],
103
+ hidden: [],
104
+ custom: [],
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 設定ファイルの内容を安全な形に整える(壊れた値は捨てる)。
110
+ * @param {unknown} raw 読み込んだ値
111
+ * @param {string} [home] ホーム
112
+ * @returns {{scanDirs: string[], pinned: string[], hidden: string[], custom: Array<{id: string, label: string, path: string}>}} 設定
113
+ */
114
+ export function normalizeReposConfig(raw, home = os.homedir()) {
115
+ const base = defaultReposConfig(home)
116
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base
117
+ const strList = (v, map) =>
118
+ Array.isArray(v)
119
+ ? [...new Set(v.map((x) => (typeof x === 'string' ? x.trim() : '')).filter(Boolean).map(map ?? ((x) => x)))]
120
+ : []
121
+ const custom = []
122
+ if (Array.isArray(raw.custom)) {
123
+ for (const c of raw.custom) {
124
+ const abs = expandHome(String(c?.path ?? '').trim(), home)
125
+ if (!abs || !path.isAbsolute(abs)) continue
126
+ const id = repoIdFromPath(String(c?.id ?? '').trim() || abs)
127
+ const label = String(c?.label ?? '').trim() || path.basename(abs)
128
+ custom.push({ id, label, path: abs })
129
+ }
130
+ }
131
+ return {
132
+ scanDirs: Array.isArray(raw.scanDirs) ? strList(raw.scanDirs) : base.scanDirs,
133
+ pinned: strList(raw.pinned),
134
+ hidden: strList(raw.hidden, (x) => normalizePath(x, home)),
135
+ custom,
136
+ }
137
+ }
138
+
139
+ /**
140
+ * `repos.json` を読む(無ければ既定・書かない)。
141
+ * @param {string} file 設定ファイル
142
+ * @param {string} [home] ホーム
143
+ * @returns {object} 設定
144
+ */
145
+ export function readReposConfig(file, home = os.homedir()) {
146
+ try {
147
+ return normalizeReposConfig(JSON.parse(fs.readFileSync(file, 'utf8')), home)
148
+ } catch {
149
+ return defaultReposConfig(home)
150
+ }
151
+ }
152
+
153
+ /**
154
+ * `repos.json` をアトミックに書く(0600・tmp → rename)。
155
+ * @param {string} file 設定ファイル
156
+ * @param {object} data 設定
157
+ * @returns {object} 正規化後の設定
158
+ */
159
+ export function writeReposConfig(file, data) {
160
+ const normalized = normalizeReposConfig(data)
161
+ fs.mkdirSync(path.dirname(file), { recursive: true })
162
+ const tmp = `${file}.tmp`
163
+ fs.writeFileSync(tmp, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 })
164
+ fs.renameSync(tmp, file)
165
+ return normalized
166
+ }
167
+
168
+ /**
169
+ * `scanDirs` の直下 **1 階層のみ** を走査して Git リポジトリを探す(深追いしない)。
170
+ * @param {string[]} scanDirs 親ディレクトリ
171
+ * @param {string} [home] ホーム
172
+ * @returns {Array<{id: string, label: string, path: string, source: string}>} 見つかったリポジトリ
173
+ */
174
+ export function scanGitDirs(scanDirs = [], home = os.homedir()) {
175
+ const out = []
176
+ const seen = new Set()
177
+ for (const rawDir of scanDirs) {
178
+ const dir = expandHome(String(rawDir ?? '').trim(), home)
179
+ if (!dir || !path.isAbsolute(dir)) continue
180
+ let entries = []
181
+ try {
182
+ entries = fs.readdirSync(dir, { withFileTypes: true })
183
+ } catch {
184
+ continue
185
+ }
186
+ for (const ent of entries) {
187
+ if (!ent.isDirectory() || ent.name.startsWith('.')) continue
188
+ const abs = path.join(dir, ent.name)
189
+ if (!isGitRepo(abs)) continue
190
+ const key = normalizePath(abs, home)
191
+ if (seen.has(key)) continue
192
+ seen.add(key)
193
+ out.push({ id: repoIdFromPath(abs), label: ent.name, path: abs, source: 'scan' })
194
+ }
195
+ }
196
+ out.sort((a, b) => a.label.localeCompare(b.label))
197
+ return out
198
+ }
199
+
200
+ /**
201
+ * 4 ソースを統合する(重複パスは最初の 1 件・`hidden` は除外・`pinned` が先頭)。
202
+ * @param {object} input 材料
203
+ * @param {object} input.config 設定
204
+ * @param {Array<object>} [input.scanned] 自動スキャン結果
205
+ * @param {Array<object>} [input.boards] `kanban.boards()` の結果
206
+ * @param {Array<string>} [input.cwds] 直近セッションの cwd
207
+ * @param {string} [input.home] ホーム
208
+ * @returns {Array<{id: string, label: string, path: string, source: string, pinned: boolean}>} 統合結果
209
+ */
210
+ export function mergeRepos({ config = {}, scanned = [], boards = [], cwds = [], home = os.homedir() } = {}) {
211
+ const hidden = new Set((config.hidden ?? []).map((p) => normalizePath(p, home)))
212
+ const rows = []
213
+ const seenPath = new Set()
214
+ const seenId = new Set()
215
+ const homeKey = normalizePath(home, home)
216
+
217
+ const push = (raw, label, source) => {
218
+ const abs = expandHome(String(raw ?? '').trim(), home)
219
+ if (!abs || !path.isAbsolute(abs)) return
220
+ const key = normalizePath(abs, home)
221
+ if (!key || key === homeKey || key === '/' || seenPath.has(key) || hidden.has(key)) return
222
+ if (!isGitRepo(abs)) return
223
+ let id = repoIdFromPath(abs)
224
+ if (seenId.has(id)) {
225
+ let n = 2
226
+ while (seenId.has(`${id}-${n}`)) n += 1
227
+ id = `${id}-${n}`
228
+ }
229
+ seenId.add(id)
230
+ seenPath.add(key)
231
+ rows.push({ id, label: String(label ?? '').trim() || path.basename(abs), path: abs, source })
232
+ }
233
+
234
+ for (const c of config.custom ?? []) push(c.path, c.label || c.id, 'custom')
235
+ for (const s of scanned) push(s.path, s.label || s.id, 'scan')
236
+ for (const b of boards) {
237
+ if (!b || b.archived) continue
238
+ push(b.workdir, b.name || b.slug, 'board')
239
+ }
240
+ for (const cwd of cwds.slice(0, SESSION_LIMIT)) push(cwd, path.basename(String(cwd ?? '')), 'session')
241
+
242
+ // ピン留めは id でもパスでも受ける(設定画面は id を書く)
243
+ const pinnedRank = new Map()
244
+ for (const [i, p] of (config.pinned ?? []).entries()) {
245
+ const raw = String(p ?? '').trim()
246
+ if (!raw) continue
247
+ if (!pinnedRank.has(raw)) pinnedRank.set(raw, i)
248
+ const key = normalizePath(raw, home)
249
+ if (key && !pinnedRank.has(key)) pinnedRank.set(key, i)
250
+ }
251
+ for (const r of rows) {
252
+ const rank = pinnedRank.has(r.id) ? pinnedRank.get(r.id) : pinnedRank.get(normalizePath(r.path, home))
253
+ r.pinned = rank !== undefined
254
+ r.rank = rank ?? Number.MAX_SAFE_INTEGER
255
+ }
256
+ rows.sort((a, b) => a.rank - b.rank || a.label.localeCompare(b.label))
257
+ for (const r of rows) delete r.rank
258
+ return rows
259
+ }
260
+
261
+ /**
262
+ * repo の path と workdir が一致するボード(アーカイブ済みは除く)。
263
+ * @param {string} repoPath リポジトリの絶対パス
264
+ * @param {Array<object>} boards `kanban.boards()` の結果
265
+ * @returns {Array<{slug: string, name: string, current: boolean}>} ボード(複数ありうる)
266
+ */
267
+ export function boardsForRepo(repoPath, boards = []) {
268
+ const want = normalizePath(repoPath)
269
+ if (!want) return []
270
+ return boards
271
+ .filter((b) => b && !b.archived && normalizePath(b.workdir) === want)
272
+ .map((b) => ({ slug: String(b.slug), name: String(b.name ?? b.slug), current: Boolean(b.current) }))
273
+ }
274
+
275
+ /**
276
+ * repos × boards を合成する。
277
+ * @param {Array<{id: string, label: string, path: string}>} repos 統合済みリポジトリ
278
+ * @param {Array<object>} boards
279
+ * @returns {Array<{id: string, label: string, path: string, source: string, pinned: boolean, boards: Array<object>}>} 合成結果
280
+ */
281
+ export function joinRepos(repos = [], boards = []) {
282
+ const out = []
283
+ const seen = new Set()
284
+ for (const r of repos) {
285
+ const id = String(r?.id ?? '').trim()
286
+ const abs = String(r?.path ?? '').trim()
287
+ if (!id || !abs || seen.has(id)) continue
288
+ seen.add(id)
289
+ out.push({
290
+ id,
291
+ label: String(r.label ?? id),
292
+ path: abs,
293
+ source: String(r.source ?? 'custom'),
294
+ pinned: Boolean(r.pinned),
295
+ boards: boardsForRepo(abs, boards),
296
+ })
297
+ }
298
+ return out
299
+ }
300
+
301
+ /**
302
+ * ボード名(slug)として安全か。CLI と同じ規則に寄せる。
303
+ * @param {unknown} slug 候補
304
+ * @returns {boolean} 安全なら true
305
+ */
306
+ export function isSafeBoardSlug(slug) {
307
+ return typeof slug === 'string' && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(slug)
308
+ }
309
+
310
+ /**
311
+ * `state.db` の直近セッション `cwd` を読む(読取専用・失敗しても空)。
312
+ * @param {object} cfg 設定(`stateDb` / `kanbanRoot`)
313
+ * @returns {string[]} cwd の新しい順
314
+ */
315
+ export function readSessionCwds(cfg = {}) {
316
+ const dbPath = String(cfg.stateDb ?? '')
317
+ if (!dbPath) return []
318
+ try {
319
+ if (!fs.existsSync(dbPath)) return []
320
+ } catch {
321
+ return []
322
+ }
323
+ let db
324
+ try {
325
+ db = new DatabaseSync(dbPath, { readOnly: true })
326
+ const rows = db
327
+ .prepare(
328
+ `SELECT cwd, MAX(last_activity_at) AS t
329
+ FROM sessions
330
+ WHERE cwd IS NOT NULL AND cwd <> ''
331
+ GROUP BY cwd
332
+ ORDER BY t DESC
333
+ LIMIT 64`,
334
+ )
335
+ .all()
336
+ const kanbanRoot = String(cfg.kanbanRoot ?? '')
337
+ const out = []
338
+ for (const r of rows) {
339
+ const cwd = String(r.cwd ?? '').trim()
340
+ if (!cwd || !path.isAbsolute(cwd)) continue
341
+ // ワーカーの workspace(worktree)は同じリポジトリの重複なので候補にしない
342
+ if (kanbanRoot && cwd.startsWith(kanbanRoot)) continue
343
+ if (!isGitRepo(cwd)) continue
344
+ out.push(cwd)
345
+ if (out.length >= SESSION_LIMIT) break
346
+ }
347
+ return out
348
+ } catch {
349
+ return []
350
+ } finally {
351
+ try {
352
+ db?.close()
353
+ } catch {
354
+ /* noop */
355
+ }
356
+ }
357
+ }
358
+
359
+ /**
360
+ * リポジトリ一覧の読み取り・自動スキャン・追加・非表示、板が無いリポジトリのボード作成。
361
+ *
362
+ * @param {object} cfg 設定(`reposPath` / `stateDb` / `kanbanRoot` / `hermesBin`)
363
+ * @param {{boards?: Function, cwds?: Function, runner?: Function, configPath?: string, now?: Function}} [deps] 差し替え(テスト用)
364
+ * @returns {object} 操作
365
+ */
366
+ export function createRepos(cfg = {}, deps = {}) {
367
+ const listBoards = deps.boards ?? (() => [])
368
+ const readCwds = deps.cwds ?? (() => readSessionCwds(cfg))
369
+ const now = deps.now ?? (() => Date.now())
370
+ const configPath = deps.configPath ?? cfg.reposPath ?? ''
371
+ const run =
372
+ deps.runner ??
373
+ ((args) =>
374
+ new Promise((resolve) => {
375
+ execFile(
376
+ cfg.hermesBin ?? 'hermes',
377
+ args,
378
+ { timeout: 30_000, maxBuffer: 1_000_000, env: { ...process.env } },
379
+ (err, stdout, stderr) => {
380
+ resolve({ code: err ? (err.code ?? 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
381
+ },
382
+ )
383
+ }))
384
+
385
+ let cache = null
386
+
387
+ /** 設定を読む(ファイルが無ければ既定)。 */
388
+ function readConfig() {
389
+ return configPath ? readReposConfig(configPath) : defaultReposConfig()
390
+ }
391
+
392
+ /** 設定を書く(`configPath` 未設定ならメモリのみ=テスト用)。 */
393
+ function writeConfig(data) {
394
+ const normalized = configPath ? writeReposConfig(configPath, data) : normalizeReposConfig(data)
395
+ cache = null
396
+ return normalized
397
+ }
398
+
399
+ /** キャッシュを捨てる(`POST /api/repos/scan`)。 */
400
+ function invalidate() {
401
+ cache = null
402
+ }
403
+
404
+ /** 統合済みの候補(キャッシュ TTL 30 秒)。 */
405
+ function candidates({ force = false } = {}) {
406
+ if (!force && cache && now() - cache.at < SCAN_TTL_MS) return cache
407
+ const config = readConfig()
408
+ const scanned = scanGitDirs(config.scanDirs)
409
+ const boards = listBoards()
410
+ let cwds = []
411
+ try {
412
+ cwds = readCwds() ?? []
413
+ } catch {
414
+ cwds = []
415
+ }
416
+ const rows = mergeRepos({ config, scanned, boards, cwds })
417
+ cache = { at: now(), rows, config }
418
+ return cache
419
+ }
420
+
421
+ /** 一覧(ボード付き)。 */
422
+ function list({ force = false } = {}) {
423
+ const { rows } = candidates({ force })
424
+ return joinRepos(rows, listBoards())
425
+ }
426
+
427
+ /** 現在の `scanDirs`。 */
428
+ function scanDirs() {
429
+ return candidates().config.scanDirs ?? []
430
+ }
431
+
432
+ /** `review` など他モジュール向けの最小形(`id` / `label` / `path`)。 */
433
+ function targets() {
434
+ return list().map(({ id, label, path }) => ({ id, label, path }))
435
+ }
436
+
437
+ /**
438
+ * リポジトリを手動追加する(実在 + `.git` + ホーム直下でないことを確認)。
439
+ * @param {{path: string, label?: string}} input 追加内容
440
+ * @returns {{ok: boolean, repo?: object, error?: string}} 結果
441
+ */
442
+ function add(input = {}) {
443
+ const raw = String(input?.path ?? '').trim()
444
+ if (!raw) return { ok: false, code: 'REPO_PATH_REQUIRED' }
445
+ if (raw === '~' || normalizePath(raw) === normalizePath(os.homedir())) {
446
+ return { ok: false, code: 'REPO_PATH_FORBIDDEN' }
447
+ }
448
+ const abs = expandHome(raw)
449
+ if (!path.isAbsolute(abs)) return { ok: false, code: 'REPO_PATH_INVALID' }
450
+ if (!isGitRepo(abs)) return { ok: false, code: 'REPO_NOT_GIT' }
451
+ const config = readConfig()
452
+ const key = normalizePath(abs)
453
+ const custom = config.custom.filter((c) => normalizePath(c.path) !== key)
454
+ const id = String(input.id ?? '').trim() || repoIdFromPath(abs)
455
+ custom.push({ id, label: String(input.label ?? '').trim() || path.basename(abs), path: abs })
456
+ const next = writeConfig({
457
+ ...config,
458
+ custom,
459
+ hidden: config.hidden.filter((p) => p !== key),
460
+ pinned: config.pinned.filter((p) => p !== key),
461
+ })
462
+ const repo = list({ force: true }).find((r) => normalizePath(r.path) === key)
463
+ return { ok: true, repo: repo ?? null, config: next }
464
+ }
465
+
466
+ /**
467
+ * リポジトリを消す。手動追加は `custom` から、自動検出は `hidden` へ入れる。
468
+ * @param {string} id リポジトリ id
469
+ * @returns {{ok: boolean, hidden?: boolean, error?: string}} 結果
470
+ */
471
+ function remove(id) {
472
+ const want = String(id ?? '').trim()
473
+ if (!want) return { ok: false, code: 'REPO_ID_REQUIRED' }
474
+ const repo = list().find((r) => r.id === want)
475
+ if (!repo) return { ok: false, code: 'REPO_NOT_FOUND' }
476
+ const config = readConfig()
477
+ const key = normalizePath(repo.path)
478
+ const wasCustom = config.custom.some((c) => normalizePath(c.path) === key)
479
+ const next = wasCustom
480
+ ? { ...config, custom: config.custom.filter((c) => normalizePath(c.path) !== key) }
481
+ : { ...config, hidden: [...new Set([...(config.hidden ?? []), key])] }
482
+ writeConfig({ ...next, pinned: (config.pinned ?? []).filter((p) => p !== want && p !== key) })
483
+ return { ok: true, hidden: !wasCustom }
484
+ }
485
+
486
+ /**
487
+ * `scanDirs` を更新する(実在するディレクトリのみ・ホーム直下と `/` は拒否)。
488
+ * @param {string[]} dirs 親ディレクトリ
489
+ * @returns {{ok: boolean, scanDirs?: string[], error?: string}} 結果
490
+ */
491
+ function setScanDirs(dirs) {
492
+ if (!Array.isArray(dirs)) return { ok: false, code: 'SCAN_DIRS_INVALID' }
493
+ const clean = []
494
+ for (const raw of dirs) {
495
+ const s = String(raw ?? '').trim()
496
+ if (!s) continue
497
+ const abs = expandHome(s)
498
+ if (!path.isAbsolute(abs)) return { ok: false, code: 'SCAN_DIR_NOT_ABSOLUTE', params: { path: s } }
499
+ if (normalizePath(abs) === normalizePath(os.homedir())) {
500
+ return { ok: false, code: 'SCAN_DIR_FORBIDDEN' }
501
+ }
502
+ try {
503
+ if (!fs.statSync(abs).isDirectory()) return { ok: false, code: 'SCAN_DIR_NOT_DIRECTORY', params: { path: s } }
504
+ } catch {
505
+ return { ok: false, code: 'SCAN_DIR_MISSING', params: { path: s } }
506
+ }
507
+ if (!clean.includes(s)) clean.push(s)
508
+ }
509
+ const config = readConfig()
510
+ writeConfig({ ...config, scanDirs: clean })
511
+ return { ok: true, scanDirs: clean }
512
+ }
513
+
514
+ /** 即時再スキャン(キャッシュを捨てて返す)。 */
515
+ function scan() {
516
+ const snap = candidates({ force: true })
517
+ return { ok: true, repos: joinRepos(snap.rows, listBoards()), scanDirs: snap.config.scanDirs ?? [] }
518
+ }
519
+
520
+ /**
521
+ * 板が無いリポジトリにボードを 1 つ作る(既に同じ workdir の板があればそれを返す)。
522
+ * @param {string} repoId リポジトリ id(=ボードの slug に使う)
523
+ * @returns {Promise<{ok: boolean, board?: object, error?: string, created?: boolean}>} 結果
524
+ */
525
+ async function createBoard(repoId) {
526
+ const repo = list().find((r) => r.id === String(repoId ?? ''))
527
+ if (!repo) return { ok: false, code: 'REPO_NOT_FOUND' }
528
+ if (repo.boards.length) {
529
+ const hit = repo.boards.find((b) => b.current) ?? repo.boards[0]
530
+ return { ok: true, created: false, board: hit }
531
+ }
532
+ if (!isSafeBoardSlug(repo.id)) return { ok: false, code: 'BOARD_NAME_INVALID' }
533
+ const args = ['kanban', 'boards', 'create', repo.id, '--name', repo.label, '--default-workdir', repo.path]
534
+ const res = await run(args)
535
+ if (res.code !== 0) {
536
+ const msg = (res.stderr || res.stdout || '').trim().slice(0, 400)
537
+ return { ok: false, code: 'CREATE_FAILED', error: msg }
538
+ }
539
+ invalidate()
540
+ return { ok: true, created: true, board: { slug: repo.id, name: repo.label, current: false } }
541
+ }
542
+
543
+ return { list, scanDirs, targets, add, remove, setScanDirs, scan, createBoard, invalidate }
544
+ }