hermes-pilot 0.2.0 → 0.2.3

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/README.ja.md CHANGED
@@ -33,7 +33,8 @@ English README: [`README.md`](README.md)
33
33
  - **全タブ状態保持**: タスク・レビュー・チャット・メモ・ターミナル・設定のすべてのタブを裏で保持し、タブ往復時の再読み込みタイムラグや入力ロスを防止
34
34
  - **英語・日本語**(既定フォールバックは `en`、`ja` 同梱)、**Dark / Light / System** テーマ、そして 2 段階の
35
35
  2 ペイン: **680px から狭幅マスター・ディテール**(左 280px。iPad mini 縦などの 744/768px 用)と
36
- **820px から広幅 2 ペイン**(レビュー左 380px / タスク左 360px)。680px 未満は詳細が全画面シートで開きます
36
+ **820px から広幅 2 ペイン**(タスク・レビューとも左 380px、1180px 以上は 450px。詳細は全幅で本文だけ 1040px 上限)。
37
+ 680px 未満は詳細が全画面シートで開きます
37
38
  - **外部プラグイン不要** — リポジトリはプロジェクトフォルダの 1 階層スキャンで見つけ、システム状態は
38
39
  Hermes 標準 API だけで組み立てます
39
40
 
@@ -97,6 +98,33 @@ curl -s -H "x-client: mobile" \
97
98
  "http://127.0.0.1:4097/api/telemetry/receipt?board=<board>&hours=24&t=$(cat ~/.hermes/plugin-data/hermes-pilot/token)"
98
99
  ```
99
100
 
101
+ ## 抽象ロールとネイティブ委譲
102
+
103
+ バッチを振り分けるのは**モデル名ではなくロール**です。パイプライン全体を 4 つの抽象ロールで覆い、
104
+ リポジトリと同梱 3 スキルが使う語彙はこの 4 つだけです。
105
+
106
+ - `role:planner` — 設計・仕様策定・影響分析・難所の原因究明。
107
+ - `role:builder` — 実装・テスト修復・ビルド・定型のカンバン作業(既定)。
108
+ - `role:visual-reviewer` — スクショ/赤入れ画像の読解と `390×844` / `820×1180` の視覚検収。
109
+ - `role:decision-framer` — クイックレビューの設問設計とトレードオフ整理。
110
+
111
+ バッチに `- **Recommended Role**: \`role:planner\`` と書けば、ブリッジがそれを抽出して起票タスク本文の
112
+ `[Hermes Pilot Execution Contract]` にロール指針を注入します。書かない SPEC は従来どおりに動きます。
113
+
114
+ 委譲は**ネイティブ**(Hermes 自身の `delegate_task`)だけで、外部 AI CLI の子プロセス(`gemini -p` /
115
+ `agy -p` など)は起動しません(`npm run check:oauth` がランタイム側の起動を検出すると失敗します)。
116
+ しかも**止まりません**: 委譲先がエラー・レート制限・タイムアウト・未設定のいずれでも、親はプロファイルが
117
+ 宣言したフォールバック順で自分のモデルのまま続行し、バッチは最後まで完走します。委譲の失敗でタスクが
118
+ 止まったままになることはありません。
119
+
120
+ **モデル名を書かない場所。** リポジトリと同梱 3 スキルは抽象ロールしか語りません。「どのロールをどの
121
+ モデルに割り当て、失敗時にどこへ落とすか」の対応表は運用者のもので、Hermes プロファイル側(毎ターン読む
122
+ 短い契約は `~/.hermes/SOUL.md`、具体的な割当表はプロファイル自身の `SOUL.md` とメモリ)に置きます。この
123
+ 分離が、誰の環境にも入るプラグインでいるための条件です。`POST /api/pipeline/optimize` はマーカーブロックを
124
+ `~/.hermes/SOUL.md` と、見つかった各 `~/.hermes/profiles/<name>/SOUL.md` へ冪等に書き込み(実行前に
125
+ `.bak-<stamp>` を退避)、`GET /api/pipeline/status` はファイルの中身を返さずにプロファイルごとの適用状況
126
+ だけを返します。
127
+
100
128
  ## 意思決定コックピット(v2)
101
129
 
102
130
  「エージェントが判断を待っている」から「また走り出した」までを最短にする 5 つ。スマホからも標準
@@ -145,8 +173,10 @@ curl -s -H "x-client: mobile" \
145
173
  - **スニペット帯トグル** — チャット入力欄の上、注釈ツールバー、端末キーのチップ帯はそれぞれ折りたためます。
146
174
  選択は帯ごとに記憶され、390px の画面で入力欄とキーボードが場所を取り合いません。
147
175
  - **1 タップ環境最適化** — *設定 → この Hermes を最適化*(`POST /api/pipeline/optimize`)が
148
- `~/.hermes/SOUL.md` へ A2B の規律節を**冪等に**追記し、同梱 3 スキルを `~/.hermes/skills/` へ配置します。
149
- `GET /api/pipeline/status` は適用済みかだけを返し、`SOUL.md` の中身は返しません。
176
+ `~/.hermes/SOUL.md` と各プロファイルの `~/.hermes/profiles/<name>/SOUL.md` へ A2B の規律節を**冪等に**
177
+ 追記し(既存節は重複させず、実行前に `.bak-<stamp>` を退避)、同梱 3 スキルを `~/.hermes/skills/` へ
178
+ 配置します。`GET /api/pipeline/status` はプロファイルごとの適用済み状況だけを返し、`SOUL.md` の中身は
179
+ 返しません。
150
180
  - **旧 cron の自動片付け** — `migrate`(と `init`)は旧 `mobile-akapen-watch` / `mobile-review-watch` の
151
181
  cron を削除します。完了フィードはブリッジ内蔵の監視が書くようになり、2 者が書くと報告が二重になるためです。
152
182
  他の cron とストアのトップレベル構造は変更しません。
@@ -202,20 +232,36 @@ data URL として組み立てるため、デモは外部ネットワークに
202
232
 
203
233
  ## インストール
204
234
 
205
- ルートは 2 つ。最初の 1 手が違うだけで、そのあとは同じ **コードを取る → `npm ci` → `init`** の 3 手です。
206
- まだ npm へ公開していないため、以下のコマンドはすべて `npx` ではなくリポジトリ(またはプラグイン
207
- ディレクトリ)の CLI を直接叩く `node bin/hermes-pilot.mjs …` で書いています。
235
+ ルートは 3 つ。**A が最短**(clone 不要・コマンド 1 本)。**B / C** は Hermes のプラグインとして
236
+ 入れるので、ダッシュボードのタブと同梱スキルまで一緒に設定されます。
237
+
238
+ **A. npm から(公開パッケージ)**
239
+
240
+ ```bash
241
+ npx hermes-pilot@0.2.3 init # データ・トークン・同梱スキル・ペアリング QR(冪等)
242
+ npx hermes-pilot@0.2.3 start # ブリッジ起動(http://127.0.0.1:4097)
243
+ ```
244
+
245
+ ログインをまたいで常駐させるなら、一度だけ入れて `service` を使います。
246
+
247
+ ```bash
248
+ npm i -g hermes-pilot@0.2.3
249
+ hermes-pilot service install # macOS は launchd、Linux は systemd --user
250
+ ```
208
251
 
209
- **A. Hermes のプラグインカタログから(推奨)**
252
+ npm のパッケージ: <https://www.npmjs.com/package/hermes-pilot>(版は固定を推奨。`@latest` は最新)。
253
+ `postinstall` が npm の tarball 展開で落ちる `spawn-helper` の実行ビットを戻すので、端末タブもそのまま動きます。
254
+
255
+ **B. Hermes のプラグインカタログから**
210
256
 
211
257
  ```bash
212
- hermes plugins install hajimemanila/hermes-pilot --ref <sha> # sha で固定。--ref を省くと既定ブランチ
258
+ hermes plugins install hajimemanila/hermes-pilot --ref v0.2.3 # タグ/sha で固定。--ref を省くと既定ブランチ
213
259
  cd ~/.hermes/plugins/hermes-pilot
214
260
  npm ci
215
261
  node bin/hermes-pilot.mjs init
216
262
  ```
217
263
 
218
- **B. このリポジトリを clone して**
264
+ **C. このリポジトリを clone して**
219
265
 
220
266
  ```bash
221
267
  git clone https://github.com/hajimemanila/hermes-pilot.git
@@ -224,12 +270,10 @@ npm ci
224
270
  node bin/hermes-pilot.mjs init
225
271
  ```
226
272
 
227
- `npm ci` は省略できません。ブリッジは `ws` と**ネイティブアドオン**の `node-pty` を使い、
228
- `postinstall` が npm の tarball 展開で落ちる `spawn-helper` の実行ビットを戻しています
229
- (これが無いと端末タブが `posix_spawnp failed` で落ちます)。
230
-
231
- 以下の `node bin/hermes-pilot.mjs …` はすべて、カレントディレクトリがそのリポジトリ/プラグイン
232
- ディレクトリである前提です。短く打ちたければ一度 `npm link` してから `hermes-pilot …` を使ってください。
273
+ **B / C** では `npm ci` は省略できません。ブリッジは `ws` と**ネイティブアドオン**の `node-pty` を使い、
274
+ `postinstall` が `spawn-helper` の実行ビットを戻しています(無いと端末タブが `posix_spawnp failed` で落ちます)。
275
+ 以下の `node bin/hermes-pilot.mjs …` はカレントディレクトリがそのリポジトリ/プラグインである前提です。
276
+ **A** の場合は同じコマンドを `hermes-pilot …` で打てます。
233
277
 
234
278
  `init` は何度実行しても安全で、次の 5 つを行います。
235
279
 
@@ -349,7 +393,7 @@ review/ sheets/, shots/, library/, feed.jsonl, chat-reports.jsonl, task-c
349
393
  ```bash
350
394
  npm install # postinstall が node-pty の権限を直す
351
395
  npm run dev # Vite :4098(/api・/ws は 4097 へプロキシ)
352
- npm test # 単体テスト(808 件)
396
+ npm test # 単体テスト(933 件)
353
397
  npm run verify # test + check:pwa(34 項目)+ check:oauth + 本番ビルド + audit:responsive
354
398
  npm run build:demo # バックエンド不要の静的デモ → apps/web/dist-demo(+ google-sites-embed.html)
355
399
  npm run deploy # 検証付きで dist を原子的に切替(無停止)
@@ -361,7 +405,7 @@ node bin/hermes-pilot.mjs --help
361
405
 
362
406
  | 手順 | 何を保証するか |
363
407
  |---|---|
364
- | `npm test` | **808 件**の単体・結合テストが 0 fail(node:test、フレームワーク無し) |
408
+ | `npm test` | **933 件**の単体・結合テストが 0 fail(node:test、フレームワーク無し) |
365
409
  | `check:pwa` | `apps/web/public` に対する **34/34** 項目(マニフェスト・アイコン・マスカブル・Service Worker・viewport) |
366
410
  | `check:oauth` | **0 違反**: 端末の資格情報や OAuth トークンがブラウザ側バンドルから読めないこと |
367
411
  | `build` | Vite 本番ビルドが通り、`demo/` のコードが混入していないこと |
package/README.md CHANGED
@@ -34,7 +34,8 @@ kanban, chat, terminal and usage into a single installable PWA.
34
34
  - **Persistent tab state** — all six tabs (Tasks, Review, Chat, Memos, Terminal, Settings) stay mounted in the background so switching tabs preserves scroll position, drafts, and loaded state without reload lag.
35
35
  - **English and Japanese** (`en` is the fallback, `ja` is bundled), **Dark / Light / System** themes and two
36
36
  two-pane layouts: a **narrow master-detail from 680 px** (280 px master, for portrait tablets such as the
37
- iPad mini) and the **wide two-pane from 820 px** (380 px review master / 360 px tasks master). Below 680 px
37
+ iPad mini) and the **wide two-pane from 820 px** (380 px master for both Tasks and Review, 450 px
38
+ from 1180 px, with the detail column full-bleed and its text capped at 1040 px). Below 680 px
38
39
  every detail opens as a full-height sheet.
39
40
  - **No external plugins required** — repositories are found by scanning your project folders, and system
40
41
  status uses only the standard Hermes APIs.
@@ -98,6 +99,34 @@ curl -s -H "x-client: mobile" \
98
99
  "http://127.0.0.1:4097/api/telemetry/receipt?board=<board>&hours=24&t=$(cat ~/.hermes/plugin-data/hermes-pilot/token)"
99
100
  ```
100
101
 
102
+ ## Abstract roles and native delegation
103
+
104
+ A batch is routed by **role**, not by model name. Four abstract roles cover the whole pipeline, and they are
105
+ the only vocabulary the repo and the bundled skills use:
106
+
107
+ - `role:planner` — design, spec authoring, impact analysis, hard root-cause work.
108
+ - `role:builder` — implementation, test repair, builds, routine kanban work (the default).
109
+ - `role:visual-reviewer` — screenshot / annotation reading and `390×844` / `820×1180` visual acceptance.
110
+ - `role:decision-framer` — quick-review question design and trade-off framing.
111
+
112
+ A batch may declare `- **Recommended Role**: \`role:planner\``; the bridge extracts it and adds the role
113
+ guidance to the `[Hermes Pilot Execution Contract]` appended to the filed task. Specs without the line behave
114
+ exactly as before.
115
+
116
+ Delegation is **native** — Hermes's own `delegate_task` — and never an external AI CLI subprocess
117
+ (`gemini -p`, `agy -p`, …); `npm run check:oauth` fails if a runtime file tries to spawn one. It is also
118
+ **non-blocking**: if the delegated model errors, is rate-limited, times out or is not configured, the parent
119
+ continues on its own model in the fallback order its profile declares, and the batch still finishes. A failed
120
+ delegation never leaves a task stopped.
121
+
122
+ **Where the models are named: not here.** The repository and the three bundled skills speak only abstract
123
+ roles. The mapping (which role uses which model, in what fallback order) belongs to the operator and lives in
124
+ the Hermes profile — `~/.hermes/SOUL.md` for the short always-read contract, the profile's own `SOUL.md` and
125
+ memory for the concrete assignment table. That split is what keeps the plugin installable for anyone.
126
+ `POST /api/pipeline/optimize` writes the marker block into `~/.hermes/SOUL.md` **and** every
127
+ `~/.hermes/profiles/<name>/SOUL.md` it finds, idempotently and after a `.bak-<stamp>` backup;
128
+ `GET /api/pipeline/status` reports which profiles are applied without returning any file content.
129
+
101
130
  ## Decision cockpit (v2)
102
131
 
103
132
  Five additions that shorten the loop from "the agent needs a decision" to "it is running again".
@@ -150,9 +179,11 @@ Every one of them is reachable from the phone and from the standard dashboard.
150
179
  keys can each be collapsed. The choice is per band and remembered, so a small phone keeps the composer and
151
180
  the keyboard from fighting for the same 390 px.
152
181
  - **1-tap environment optimisation** — *Settings → Optimise this Hermes* (`POST /api/pipeline/optimize`)
153
- appends the A2B discipline section to `~/.hermes/SOUL.md` (idempotent — an existing section is never
154
- duplicated) and places the three bundled skills into `~/.hermes/skills/`. `GET /api/pipeline/status` reports
155
- what is already applied without returning any `SOUL.md` content.
182
+ appends the A2B discipline section to `~/.hermes/SOUL.md` and to each profile's
183
+ `~/.hermes/profiles/<name>/SOUL.md` (idempotent — an existing section is never duplicated, and a
184
+ `.bak-<stamp>` backup is taken first), then places the three bundled skills into `~/.hermes/skills/`.
185
+ `GET /api/pipeline/status` reports what is already applied, per profile, without returning any `SOUL.md`
186
+ content.
156
187
  - **Legacy cron cleanup** — `migrate` (and `init`) removes the old `mobile-akapen-watch` /
157
188
  `mobile-review-watch` cron entries, because the bridge's own watcher writes the completion feed now and two
158
189
  writers produced duplicate reports. Other cron entries and the store's top-level shape are untouched.
@@ -210,20 +241,37 @@ check, so a broken file cannot reach the site.
210
241
 
211
242
  ## Install
212
243
 
213
- Two routes, same three steps after the first one: **get the code → `npm ci` → `init`**.
214
- There is no published npm release yet, so every command below runs the checked-in CLI
215
- (`node bin/hermes-pilot.mjs …`) from the repository or plugin directory instead of `npx`.
244
+ Three routes. **A** is the shortest (one command, no clone); **B/C** install it as a Hermes plugin
245
+ so the dashboard tab and the bundled skills are wired up for you.
246
+
247
+ **A. From npm (published package)**
248
+
249
+ ```bash
250
+ npx hermes-pilot@0.2.3 init # data dirs, token, bundled skills, pairing QR (idempotent)
251
+ npx hermes-pilot@0.2.3 start # bridge on http://127.0.0.1:4097
252
+ ```
253
+
254
+ To keep it running across logins instead, install it once and use the `service` subcommand:
255
+
256
+ ```bash
257
+ npm i -g hermes-pilot@0.2.3
258
+ hermes-pilot service install # launchd on macOS, systemd --user on Linux
259
+ ```
216
260
 
217
- **A. From the Hermes plugin catalog (recommended)**
261
+ `hermes-pilot` on npm: <https://www.npmjs.com/package/hermes-pilot> (pin the version; `@latest`
262
+ tracks the newest release). The package `postinstall` restores the `spawn-helper` exec bit that
263
+ npm's tarball extraction drops, so the terminal tab works without extra steps.
264
+
265
+ **B. From the Hermes plugin catalog**
218
266
 
219
267
  ```bash
220
- hermes plugins install hajimemanila/hermes-pilot --ref <sha> # pin a commit; omit --ref to track the default branch
268
+ hermes plugins install hajimemanila/hermes-pilot --ref v0.2.3 # pin a tag/commit; omit --ref to track the default branch
221
269
  cd ~/.hermes/plugins/hermes-pilot
222
270
  npm ci
223
271
  node bin/hermes-pilot.mjs init
224
272
  ```
225
273
 
226
- **B. From a clone of this repository**
274
+ **C. From a clone of this repository**
227
275
 
228
276
  ```bash
229
277
  git clone https://github.com/hajimemanila/hermes-pilot.git
@@ -232,12 +280,10 @@ npm ci
232
280
  node bin/hermes-pilot.mjs init
233
281
  ```
234
282
 
235
- `npm ci` is not optional: the bridge needs `ws` and the **native** addon `node-pty`, and the
236
- `postinstall` step restores the `spawn-helper` exec bit that npm's tarball extraction drops
237
- (without it the terminal tab fails with `posix_spawnp failed`).
238
-
239
- Every `node bin/hermes-pilot.mjs …` below assumes the current directory is that repository /
240
- plugin directory. If you prefer the short form, run `npm link` once and use `hermes-pilot …`.
283
+ For **B/C**, `npm ci` is not optional: the bridge needs `ws` and the **native** addon `node-pty`,
284
+ and the `postinstall` step restores the `spawn-helper` exec bit (without it the terminal tab fails
285
+ with `posix_spawnp failed`). Every `node bin/hermes-pilot.mjs …` below assumes the current
286
+ directory is that repository / plugin directory; with route **A** use `hermes-pilot …` instead.
241
287
 
242
288
  `init` is idempotent and does five things:
243
289
 
@@ -358,7 +404,7 @@ review/ sheets/, shots/, library/, feed.jsonl, chat-reports.jsonl, task-c
358
404
  ```bash
359
405
  npm install # postinstall fixes node-pty permissions
360
406
  npm run dev # Vite on :4098, proxies /api and /ws to :4097
361
- npm test # unit tests (808)
407
+ npm test # unit tests (933)
362
408
  npm run verify # test + check:pwa (34 checks) + check:oauth + production build + audit:responsive
363
409
  npm run build:demo # static interactive demo -> apps/web/dist-demo (+ google-sites-embed.html)
364
410
  npm run deploy # atomic, verified swap of apps/web/dist
@@ -370,7 +416,7 @@ node bin/hermes-pilot.mjs --help
370
416
 
371
417
  | Step | What it proves |
372
418
  |---|---|
373
- | `npm test` | **808** unit / integration tests, 0 fail (node:test, no framework). |
419
+ | `npm test` | **933** unit / integration tests, 0 fail (node:test, no framework). |
374
420
  | `check:pwa` | **34/34** PWA checks against `apps/web/public` (manifest, icons, maskable, service worker, viewport). |
375
421
  | `check:oauth` | **0** violations: no device credential or OAuth token is readable from the browser bundle. |
376
422
  | `build` | Vite production build succeeds and contains no `demo/` code. |
@@ -40,6 +40,10 @@ export const A2B_RULES = [
40
40
  '- 判断が必要になったら**長文の質問をチャットへ並べない**。`quick-review` シートを作り、',
41
41
  ' `[review] label=... round=...` 行付きのタスクを起票して `needs_input` で止める。',
42
42
  '- 見た目の検収は `annotation`(スクリーンショット+赤)で受ける。文章で聞き返さない。',
43
+ // D60 / D61 / D63: 抽象ロール・ネイティブ委譲・外部 CLI 禁止(SOUL を太らせないため 3 行に抑える)
44
+ '- 抽象ロール(`role:planner` / `role:builder` / `role:visual-reviewer` / `role:decision-framer`)で捉え、',
45
+ ' ロールごとの実モデル割当とフォールバック順はプロファイルメモリの表に従い `delegate_task` で委譲する。',
46
+ ' 委譲の失敗・レート制限・タイムアウト・未対応では止めずフォールバックへ回し、外部 AI CLI のサブプロセス起動はしない。',
43
47
  '- タスク本文に `Mode: zero-stop` / `fast-track-review` / `visual-gate` があればその契約に従う。',
44
48
  ' `zero-stop` は `npm run verify` が通るまで自律修復し、通過後に `done` にする。',
45
49
  '- 完了報告は「何をしたか / 検証コマンドと exit code / 未検証 / 次の一手」の 4 点に絞る。',
@@ -115,29 +119,42 @@ export function nextBackupPath(soulPath, stamp, exists = (p) => fs.existsSync(p)
115
119
  }
116
120
 
117
121
  /**
118
- * `<hermesHome>/SOUL.md` へ A2B 行動規範を冪等に適用する。
122
+ * `SOUL.md` 1 枚へ A2B 行動規範を冪等に適用する(本体。`optimizeHermesSoul` とプロファイル同期の共通処理)。
119
123
  *
120
124
  * 2 回目以降はブロックが同一なので**書き込みもバックアップもしない**(1 タップボタンの連打で
121
125
  * `SOUL.md.bak-*` が増えない)。内容が変わるときだけバックアップを 1 枚作ってから書く。
122
126
  *
123
- * @param {{hermesHome?: string, now?: number, block?: string}} [opts] 入力
124
- * @returns {{ok: boolean, path: string, mode: string, changed: boolean, backupPath: string|null, error?: string}} 結果
127
+ * @param {string} soulPath 対象ファイルの絶対パス
128
+ * @param {{now?: number, block?: string, create?: boolean}} [opts] 入力(`create:false` はファイルが無ければ作らない)
129
+ * @returns {{ok: boolean, path: string, mode: string, changed: boolean, backupPath: string|null, exists: boolean, applied: boolean, error?: string}} 結果
125
130
  */
126
- export function optimizeHermesSoul({ hermesHome, now = Date.now(), block = A2B_RULE_BLOCK } = {}) {
127
- const home = String(hermesHome ?? process.env.HERMES_HOME ?? path.join(os.homedir(), '.hermes'))
128
- const soulPath = path.join(home, 'SOUL.md')
131
+ function applySoulFile(soulPath, { now = Date.now(), block = A2B_RULE_BLOCK, create = true } = {}) {
129
132
  let current = ''
133
+ let exists = false
130
134
  try {
131
135
  current = fs.readFileSync(soulPath, 'utf8')
136
+ exists = true
132
137
  } catch (err) {
133
138
  if (err?.code !== 'ENOENT') {
134
- return { ok: false, path: soulPath, mode: 'error', changed: false, backupPath: null, error: String(err?.message ?? err) }
139
+ return {
140
+ ok: false,
141
+ path: soulPath,
142
+ mode: 'error',
143
+ changed: false,
144
+ backupPath: null,
145
+ exists: false,
146
+ applied: false,
147
+ error: String(err?.message ?? err),
148
+ }
135
149
  }
150
+ // `create:false` は既存 SOUL.md だけを対象にする(人の環境に勝手に作らない)。
151
+ if (!create) return { ok: true, path: soulPath, mode: 'skipped', changed: false, backupPath: null, exists: false, applied: false }
136
152
  }
137
153
 
138
154
  const merged = mergeSoul(current, block)
155
+ const applied = merged.text.includes(A2B_START) && merged.text.includes(A2B_END)
139
156
  if (!merged.changed) {
140
- return { ok: true, path: soulPath, mode: 'unchanged', changed: false, backupPath: null }
157
+ return { ok: true, path: soulPath, mode: 'unchanged', changed: false, backupPath: null, exists, applied }
141
158
  }
142
159
 
143
160
  let backupPath = null
@@ -152,9 +169,145 @@ export function optimizeHermesSoul({ hermesHome, now = Date.now(), block = A2B_R
152
169
  fs.writeFileSync(tmp, merged.text, { encoding: 'utf8', mode: 0o600 })
153
170
  fs.renameSync(tmp, soulPath)
154
171
  } catch (err) {
155
- return { ok: false, path: soulPath, mode: 'error', changed: false, backupPath, error: String(err?.message ?? err) }
172
+ return { ok: false, path: soulPath, mode: 'error', changed: false, backupPath, exists, applied, error: String(err?.message ?? err) }
173
+ }
174
+ return { ok: true, path: soulPath, mode: merged.mode, changed: true, backupPath, exists: true, applied: true }
175
+ }
176
+
177
+ /**
178
+ * `<hermesHome>/SOUL.md` へ A2B 行動規範を冪等に適用する。
179
+ *
180
+ * 引数・戻り値は従来どおり(`{ ok, path, mode, changed, backupPath }`)。プロファイル配下の同期は
181
+ * `optimizeProfileSouls` が担う(D64)。
182
+ *
183
+ * @param {{hermesHome?: string, now?: number, block?: string}} [opts] 入力
184
+ * @returns {{ok: boolean, path: string, mode: string, changed: boolean, backupPath: string|null, error?: string}} 結果
185
+ */
186
+ export function optimizeHermesSoul({ hermesHome, now = Date.now(), block = A2B_RULE_BLOCK } = {}) {
187
+ const home = String(hermesHome ?? process.env.HERMES_HOME ?? path.join(os.homedir(), '.hermes'))
188
+ const soulPath = path.join(home, 'SOUL.md')
189
+ const applied = applySoulFile(soulPath, { now, block, create: true })
190
+ // `exists` / `applied` は内部用の追加情報。従来の戻り値の形は変えない。
191
+ const { exists: _exists, applied: _applied, ...result } = applied
192
+ return result
193
+ }
194
+
195
+ /**
196
+ * プロファイル配下で `SOUL.md` を**新規作成してよい**名前(D64)。
197
+ *
198
+ * ディレクトリが既にある場合だけ、そして `mobile` だけ(実運用で毎ターン読ませたいプロファイル)。
199
+ * それ以外のプロファイルは既存 `SOUL.md` があるときだけ更新する=人の環境を勝手に増やさない。
200
+ */
201
+ export const PROFILE_SOUL_CREATE_IF_MISSING = ['mobile']
202
+
203
+ /**
204
+ * `<hermesHome>/profiles` 配下のプロファイル名(ディレクトリのみ・隠しディレクトリ除外)。
205
+ *
206
+ * @param {string} hermesHome Hermes のホーム
207
+ * @returns {string[]} 昇順のプロファイル名
208
+ */
209
+ export function listProfileNames(hermesHome) {
210
+ let entries = []
211
+ try {
212
+ entries = fs.readdirSync(path.join(String(hermesHome), 'profiles'), { withFileTypes: true })
213
+ } catch {
214
+ return []
215
+ }
216
+ return entries
217
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
218
+ .map((e) => e.name)
219
+ .sort()
220
+ }
221
+
222
+ /**
223
+ * プロファイル 1 つ分の `SOUL.md` 適用状況(**中身は返さない**)。
224
+ *
225
+ * @param {string} hermesHome Hermes のホーム
226
+ * @param {string} name プロファイル名
227
+ * @returns {{name: string, path: string, exists: boolean, applied: boolean, backups: number}} 状態
228
+ */
229
+ function profileSoulState(hermesHome, name) {
230
+ const soulPath = path.join(String(hermesHome), 'profiles', name, 'SOUL.md')
231
+ let exists = false
232
+ let applied = false
233
+ try {
234
+ const text = fs.readFileSync(soulPath, 'utf8')
235
+ exists = true
236
+ applied = text.includes(A2B_START) && text.includes(A2B_END)
237
+ } catch {
238
+ exists = false
239
+ }
240
+ let backups = 0
241
+ try {
242
+ backups = fs.readdirSync(path.dirname(soulPath)).filter((n) => n.startsWith('SOUL.md.bak-')).length
243
+ } catch {
244
+ backups = 0
245
+ }
246
+ return { name, path: soulPath, exists, applied, backups }
247
+ }
248
+
249
+ /**
250
+ * `~/.hermes/profiles/<name>/SOUL.md` へ A2B 行動規範を**非破壊・冪等**に同期する(D64)。
251
+ *
252
+ * - 対象は `profiles` を渡せばその名前だけ、省略時は `<hermesHome>/profiles/*` を自動検出。
253
+ * - `SOUL.md` が既にある → マーカー間だけ置換し、内容が変わるときだけ `.bak-<stamp>` を 1 枚作る。
254
+ * - `SOUL.md` が無い → `PROFILE_SOUL_CREATE_IF_MISSING`(`mobile`)だけ最小構成で新規作成、
255
+ * それ以外は `mode: 'skipped'`(ディレクトリを勝手に作らない)。
256
+ * - 内容(テキスト)は戻り値に載せない。`changed` / `mode` / `backupPath` / 件数だけ。
257
+ *
258
+ * @param {{hermesHome?: string, now?: number, block?: string, profiles?: string[]}} [opts] 入力
259
+ * @returns {{ok: boolean, profiles: Array<{name: string, path: string, exists: boolean, applied: boolean, changed: boolean, mode: string, backupPath: string|null, backups: number, error?: string}>}} 結果
260
+ */
261
+ export function optimizeProfileSouls({ hermesHome, now = Date.now(), block = A2B_RULE_BLOCK, profiles } = {}) {
262
+ const home = String(hermesHome ?? process.env.HERMES_HOME ?? path.join(os.homedir(), '.hermes'))
263
+ const names = Array.isArray(profiles) && profiles.length
264
+ ? profiles.map((n) => String(n ?? '').trim()).filter(Boolean)
265
+ : listProfileNames(home)
266
+
267
+ const out = []
268
+ for (const name of names) {
269
+ // パス連結に使う名前だけを受け付ける(`../` 等の脱出を許さない)。
270
+ if (!/^[A-Za-z0-9._-]+$/.test(name) || name === '.' || name === '..') continue
271
+ const dir = path.join(home, 'profiles', name)
272
+ let dirExists = false
273
+ try {
274
+ dirExists = fs.statSync(dir).isDirectory()
275
+ } catch {
276
+ dirExists = false
277
+ }
278
+ if (!dirExists) {
279
+ out.push({
280
+ name,
281
+ path: path.join(dir, 'SOUL.md'),
282
+ exists: false,
283
+ applied: false,
284
+ changed: false,
285
+ mode: 'skipped',
286
+ backupPath: null,
287
+ backups: 0,
288
+ })
289
+ continue
290
+ }
291
+
292
+ const r = applySoulFile(path.join(dir, 'SOUL.md'), {
293
+ now,
294
+ block,
295
+ create: PROFILE_SOUL_CREATE_IF_MISSING.includes(name),
296
+ })
297
+ const state = profileSoulState(home, name)
298
+ out.push({
299
+ name,
300
+ path: r.path,
301
+ exists: r.exists,
302
+ applied: Boolean(r.applied),
303
+ changed: Boolean(r.changed),
304
+ mode: r.mode,
305
+ backupPath: r.backupPath ?? null,
306
+ backups: state.backups,
307
+ ...(r.error ? { error: r.error } : {}),
308
+ })
156
309
  }
157
- return { ok: true, path: soulPath, mode: merged.mode, changed: true, backupPath }
310
+ return { ok: out.every((p) => p.mode !== 'error'), profiles: out }
158
311
  }
159
312
 
160
313
  /**
@@ -351,6 +504,8 @@ export function getOptimizeStatus({
351
504
  backups: backups.length,
352
505
  latestBackup: backups.length ? backups[backups.length - 1] : null,
353
506
  },
507
+ // プロファイル配下(`profiles/<name>/SOUL.md`)も「適用済みか」だけを返す(中身は返さない)。
508
+ profiles: listProfileNames(hh).map((name) => profileSoulState(hh, name)),
354
509
  hermes: skillState(path.join(hh, 'skills')),
355
510
  bundled: { source: skillsSrcDir, names: BUNDLED_SKILLS },
356
511
  antigravity,
@@ -638,7 +638,7 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
638
638
  return out
639
639
  }
640
640
 
641
- /** `state.db` から cwd 一致の最新通常セッションを 1 件返す。 */
641
+ /** `state.db` から cwd 一致の最新通常セッション `{ id, at }` を 1 件返す。 */
642
642
  function latestSessionForCwd(dbPath, workdir) {
643
643
  let db
644
644
  try {
@@ -649,7 +649,7 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
649
649
  const want = normalizePath(workdir)
650
650
  try {
651
651
  const sql = (order) =>
652
- `SELECT id, cwd FROM sessions
652
+ `SELECT id, cwd, ${order} AS ts FROM sessions
653
653
  WHERE cwd IS NOT NULL AND id NOT LIKE 'local-%'
654
654
  ORDER BY ${order} DESC LIMIT 300`
655
655
  let rows = []
@@ -659,7 +659,9 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
659
659
  rows = db.prepare(sql('started_at')).all()
660
660
  }
661
661
  for (const r of rows) {
662
- if (normalizePath(r.cwd) === want) return String(r.id)
662
+ if (normalizePath(r.cwd) === want) {
663
+ return { id: String(r.id), at: Number(r.ts) || 0 }
664
+ }
663
665
  }
664
666
  return null
665
667
  } catch {
@@ -734,10 +736,12 @@ export function createPipelineWatcher(cfg = {}, opts = {}) {
734
736
  if (CHAT_ID_RE.test(origin)) return origin
735
737
  const workdir = boardWorkdir(group.board)
736
738
  if (workdir) {
739
+ let best = null
737
740
  for (const dbPath of stateDbs()) {
738
- const id = latestSessionForCwd(dbPath, workdir)
739
- if (id) return id
741
+ const hit = latestSessionForCwd(dbPath, workdir)
742
+ if (hit && (!best || hit.at > best.at)) best = hit
740
743
  }
744
+ if (best) return best.id
741
745
  }
742
746
  return '__latest__'
743
747
  }
@@ -38,6 +38,7 @@ import {
38
38
  getOptimizeStatus,
39
39
  optimizeAgentSkills,
40
40
  optimizeHermesSoul,
41
+ optimizeProfileSouls,
41
42
  } from './pipeline-optimizer.js'
42
43
  import { createPairCodes } from './pair-codes.js'
43
44
  import { createMemosStore } from './memos.js'
@@ -695,19 +696,25 @@ async function handleApi(req, res, url) {
695
696
  // 既定は SOUL とスキル配置の両方。片方だけ試したいときは明示的に false を渡す。
696
697
  const doSoul = body?.soul !== false
697
698
  const doSkills = body?.skills !== false
699
+ // プロファイル別 `SOUL.md`(`profiles/<name>/SOUL.md`)も同じ 1 タップで冪等同期する(D64)。
700
+ const doProfiles = doSoul && body?.profiles !== false
698
701
  const soul = doSoul ? optimizeHermesSoul({ hermesHome: cfg.hermesHome }) : null
702
+ const profiles = doProfiles ? optimizeProfileSouls({ hermesHome: cfg.hermesHome }) : null
699
703
  const skills = doSkills ? optimizeAgentSkills({ home: cfg.home, skillsSrcDir: DEFAULT_SKILLS_SRC }) : null
700
- const ok = (soul?.ok ?? true) && (skills?.ok ?? true)
704
+ const ok = (soul?.ok ?? true) && (profiles?.ok ?? true) && (skills?.ok ?? true)
701
705
  auth.audit({
702
706
  kind: 'pipeline.optimize',
703
707
  soul: soul?.mode ?? null,
704
708
  soulChanged: Boolean(soul?.changed),
709
+ profileTargets: profiles?.profiles?.length ?? 0,
710
+ profileChanged: profiles?.profiles?.filter((p) => p.changed).length ?? 0,
705
711
  skillTargets: skills?.targets?.length ?? 0,
706
712
  ok,
707
713
  })
708
714
  return sendJson(res, ok ? 200 : 500, {
709
715
  ok,
710
716
  soul,
717
+ profiles,
711
718
  skills,
712
719
  status: getOptimizeStatus({ hermesHome: cfg.hermesHome, home: cfg.home, skillsSrcDir: DEFAULT_SKILLS_SRC }),
713
720
  })