Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4398: fix Hermes bound-skill discovery with per-task overlay (#5308)
Rusty Ravenef9b33440878
diff --git a/apps/docs/content/docs/install-agent-runtime.mdx b/apps/docs/content/docs/install-agent-runtime.mdxindex fe426b5c62..63046c8175 100644--- a/apps/docs/content/docs/install-agent-runtime.mdx+++ b/apps/docs/content/docs/install-agent-runtime.mdx@@ -111,7 +111,7 @@ ACP-protocol agent, primarily aimed at the Chinese market. MCP config is passed### Hermes (Nous Research)-ACP-protocol agent (shares the transport with Kimi). Session resumption works, and MCP config is passed through ACP `mcpServers`. The skill injection path falls back to the generic `.agent_context/skills/` — verify your skills are loading before relying on them.+ACP-protocol agent (shares the transport with Kimi). Session resumption works, and MCP config is passed through ACP `mcpServers`. Hermes discovers skills only from its home (`~/.hermes/skills/`), so when an agent has skills assigned Multica points `HERMES_HOME` at a per-task overlay of your `~/.hermes/` (real home mirrored by symlink; a derived `config.yaml` references your existing skills as external roots) and writes the assigned skills into its `skills/` directory for native discovery. Tasks with no assigned skills run against your real home unchanged.| | ||---|---|diff --git a/apps/docs/content/docs/providers.ja.mdx b/apps/docs/content/docs/providers.ja.mdxindex e55ff22168..09ba3cf6d4 100644--- a/apps/docs/content/docs/providers.ja.mdx+++ b/apps/docs/content/docs/providers.ja.mdx@@ -19,7 +19,7 @@ Multica は **14 個の AI コーディングツール**を標準でサポート| **Codex** | OpenAI | ✅ | ✅ | `$CODEX_HOME/skills/` | 静的 || **Copilot** | GitHub | ✅ | ❌ | `.github/skills/` | 静的(アカウントの権限で決定) || **Cursor** | Anysphere | ✅ | ✅ | `.cursor/skills/` | 動的探索 |-| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/`(フォールバック) | 動的探索 |+| **Hermes** | Nous Research | ✅ | ✅ | `HERMES_HOME/skills/`(タスクごとのホーム) | 動的探索 || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | 動的探索 || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | 動的探索 || **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 動的探索 + variant |@@ -56,7 +56,7 @@ Anysphere が提供し、Cursor エディターに対応する CLI です。**### Hermes-Nous Research が提供します。ACP プロトコルを使用します(Kimi とトランスポート層を共有します)。セッション再開が動作し、MCP 構成は ACP `mcpServers` として渡されます。しかし**スキル注入パスは専用のものではなく汎用のフォールバック**(`.agent_context/skills/`)です — Hermes CLI 自体がこのパスを読み取らない場合、スキルが適用されないことがあります。テストで確認してください。+Nous Research が提供します。ACP プロトコルを使用します(Kimi とトランスポート層を共有します)。セッション再開が動作し、MCP 構成は ACP `mcpServers` として渡されます。Hermes はスキルを自身のホームディレクトリ(`~/.hermes/skills/`)と設定済みの `skills.external_dirs` からのみ探索し、ワークスペース相対の探索は行いません。そのため、**エージェントにスキルが割り当てられている場合のみ**、Multica は `HERMES_HOME` をユーザーの `~/.hermes/` のタスクごとオーバーレイに向けます。実ホームはシンボリックリンクでミラーされ(auth/シークレットも含むためトークン更新が伝播します)、派生した `config.yaml` が既存スキルを読み取り専用の external root として参照し、割り当てられたスキルだけがその `skills/` ディレクトリに書き込まれて優先されます。グローバルスキルはそのまま機能します。Multica は共有の `~/.hermes/` を直接書き換えず、読み取ってリンクするだけですが、Hermes 自身がミラーされたシンボリックリンク経由で書き込む場合(トークン更新など)は伝播します。`custom_args` の `-p`/`--profile` 指定は尊重されます。オーバーレイはその profile のホームからシードされ、フラグは起動コマンドから消費されるため、オーバーレイを迂回できません。タスクの記憶はタスクごとに隔離されます。新しい `memories/` ディレクトリに加え、派生設定で外部 `memory.provider` バックエンドを無効化するので、ディスク上のメモも共有の Supermemory/Hindsight 的バンクもタスク間で共有されません(マネージドで agent スコープの記憶バックエンドは今後の別課題です)。スキルが割り当てられていない Hermes タスクは実ホームのまま変わりません。なお home のプラットフォーム既定はネイティブ Windows では `%LOCALAPPDATA%\hermes` です。**Hermes profile を選択する。** 特定の profile で Hermes を起動するには、エージェントの `custom_args` に profile フラグと profile 名を 2 つの独立したエントリとして設定します。たとえば `research` という profile を使う場合:@@ -126,10 +126,10 @@ ByteDance 公式の TRAE CLI(`traecli`、Trae IDE と組み合わせて使う| Qoder | `.qoder/skills/` | ✅ ネイティブ || Trae CLI | `.traecli/skills/` | ✅ ネイティブ || Antigravity | `.agents/skills/` | ✅ ネイティブ(Gemini CLI のワークスペースレイアウトを継承 — [Antigravity ドキュメント](https://antigravity.google/docs/gcli-migration)を参照) |-| Hermes | `.agent_context/skills/` | ⚠️ 汎用フォールバック |+| Hermes | `HERMES_HOME/skills/`(タスクごとのホーム) | ✅ ネイティブ(タスクごとに `~/.hermes/` からシード) || OpenClaw | `.agent_context/skills/` | ⚠️ 汎用フォールバック |-フォールバックパスを使うツールが実際にこのディレクトリを読み取るかどうかは、そのツール自体のドキュメントによって異なり、保証されません。Hermes / OpenClaw でスキルが適用されない場合は、まずこの点を確認してください。+フォールバックパスを使うツールが実際にこのディレクトリを読み取るかどうかは、そのツール自体のドキュメントによって異なり、保証されません。OpenClaw でスキルが適用されない場合は、まずこの点を確認してください。ネイティブなプロジェクトレベルのパスでは、リポジトリスコープの探索は想定された挙動です。チェックアウトされたリポジトリが対応するディレクトリをすでに含んでいる場合、基盤となるツールはそのコミット済みスキルを自分で検出できます。そのリポジトリで使うためだけに、これらの repo skills を Multica へインポートする必要はありません。Multica はそれらのリポジトリファイルをそのまま保持します。ワークスペーススキルの自然なディレクトリ名が同じ場合、デーモンは `review-helper-multica` のような衝突しない兄弟ディレクトリへワークスペースコピーを書き込みます。diff --git a/apps/docs/content/docs/providers.ko.mdx b/apps/docs/content/docs/providers.ko.mdxindex 70058ee8d2..4623d4022a 100644--- a/apps/docs/content/docs/providers.ko.mdx+++ b/apps/docs/content/docs/providers.ko.mdx@@ -19,7 +19,7 @@ Multica는 **14개의 AI 코딩 도구**를 기본 지원합니다. 이들은| **Codex** | OpenAI | ✅ | ✅ | `$CODEX_HOME/skills/` | 정적 || **Copilot** | GitHub | ✅ | ❌ | `.github/skills/` | 정적 (계정 권한으로 결정) || **Cursor** | Anysphere | ✅ | ✅ | `.cursor/skills/` | 동적 탐색 |-| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/` (fallback) | 동적 탐색 |+| **Hermes** | Nous Research | ✅ | ✅ | `HERMES_HOME/skills/` (작업별 홈) | 동적 탐색 || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | 동적 탐색 || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | 동적 탐색 || **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 동적 탐색 + variant |@@ -56,7 +56,7 @@ Anysphere에서 제공하며, Cursor 에디터에 대응하는 CLI입니다. **### Hermes-Nous Research에서 제공합니다. ACP 프로토콜을 사용합니다(Kimi와 전송 계층을 공유합니다). 세션 재개가 동작하고, MCP 구성은 ACP `mcpServers`로 전달됩니다. 하지만 **스킬 주입 경로는 전용 경로가 아니라 범용 fallback**(`.agent_context/skills/`)입니다 — Hermes CLI 자체가 이 경로를 읽지 않으면 스킬이 적용되지 않을 수 있습니다. 테스트로 확인하세요.+Nous Research에서 제공합니다. ACP 프로토콜을 사용합니다(Kimi와 전송 계층을 공유합니다). 세션 재개가 동작하고, MCP 구성은 ACP `mcpServers`로 전달됩니다. Hermes는 스킬을 자신의 홈 디렉터리(`~/.hermes/skills/`)와 설정된 `skills.external_dirs`에서만 탐색하며, 워크스페이스 상대 탐색은 하지 않습니다. 그래서 **에이전트에 스킬이 할당된 경우에만** Multica는 `HERMES_HOME`을 사용자 `~/.hermes/`의 작업별 오버레이로 향하게 합니다. 실제 홈은 심링크로 미러되고(auth/시크릿 포함, 토큰 갱신이 전파됨), 파생된 `config.yaml`이 기존 스킬을 읽기 전용 external root로 참조하며, 할당된 스킬만 그 `skills/` 디렉터리에 기록되어 우선합니다. 전역 스킬은 그대로 동작합니다. Multica는 공유 `~/.hermes/`를 직접 수정하지 않고 읽어서 링크만 하지만, Hermes가 미러된 심링크를 통해 쓰는 경우(토큰 갱신 등)는 전파됩니다. `custom_args`의 `-p`/`--profile` 선택은 존중됩니다. 오버레이는 그 profile의 홈에서 시드되고, 플래그는 실행 명령에서 소비되어 오버레이를 우회할 수 없습니다. 작업 메모리는 작업별로 격리됩니다. 새 `memories/` 디렉터리에 더해 파생 설정에서 외부 `memory.provider` 백엔드를 비활성화하므로, 디스크상의 메모도 공유 Supermemory/Hindsight 류의 뱅크도 작업 간에 공유되지 않습니다(관리형 agent 범위 메모리 백엔드는 향후 별도 과제입니다). 스킬이 할당되지 않은 Hermes 작업은 실제 홈 그대로 실행됩니다. 참고로 홈의 플랫폼 기본값은 네이티브 Windows에서 `%LOCALAPPDATA%\hermes`입니다.**Hermes profile 선택.** 특정 profile로 Hermes를 실행하려면 에이전트의 `custom_args`에 profile 플래그와 profile 이름을 두 개의 독립된 항목으로 설정하세요. 예를 들어 `research`라는 profile을 사용하려면:@@ -126,10 +126,10 @@ ByteDance의 공식 TRAE CLI(`traecli`, Trae IDE와 함께 쓰는 제품이며| Qoder | `.qoder/skills/` | ✅ 기본 || Trae CLI | `.traecli/skills/` | ✅ 기본 || Antigravity | `.agents/skills/` | ✅ 기본 (Gemini CLI의 워크스페이스 레이아웃을 따름 — [Antigravity 문서](https://antigravity.google/docs/gcli-migration) 참고) |-| Hermes | `.agent_context/skills/` | ⚠️ 범용 fallback |+| Hermes | `HERMES_HOME/skills/` (작업별 홈) | ✅ 기본 (작업별로 `~/.hermes/`에서 시드) || OpenClaw | `.agent_context/skills/` | ⚠️ 범용 fallback |-fallback 경로를 쓰는 도구가 실제로 이 디렉터리를 읽는지는 해당 도구 자체의 문서에 따라 달라지며 — 보장되지 않습니다. Hermes / OpenClaw에서 스킬이 적용되지 않는다면, 먼저 이 점을 확인하세요.+fallback 경로를 쓰는 도구가 실제로 이 디렉터리를 읽는지는 해당 도구 자체의 문서에 따라 달라지며 — 보장되지 않습니다. OpenClaw에서 스킬이 적용되지 않는다면, 먼저 이 점을 확인하세요.기본 프로젝트 수준 경로에서는 저장소 범위 탐색이 의도된 동작입니다. 체크아웃된 저장소가 이미 해당 디렉터리를 포함하고 있으면, 기반 도구가 커밋된 스킬을 자체적으로 탐색할 수 있습니다. 해당 저장소에서 사용하기 위해 이러한 repo skills를 Multica로 먼저 가져올 필요는 없습니다. Multica는 이러한 저장소 파일을 그대로 둡니다. 워크스페이스 스킬의 자연 디렉터리 이름이 같으면 데몬은 `review-helper-multica` 같은 충돌 없는 형제 디렉터리에 워크스페이스 사본을 씁니다.diff --git a/apps/docs/content/docs/providers.mdx b/apps/docs/content/docs/providers.mdxindex 705bc7293a..2410e458b4 100644--- a/apps/docs/content/docs/providers.mdx+++ b/apps/docs/content/docs/providers.mdx@@ -19,7 +19,7 @@ For guidance on picking a tool when creating an agent, see [Creating and configu| **Codex** | OpenAI | ✅ | ✅ | `$CODEX_HOME/skills/` | Static || **Copilot** | GitHub | ✅ | ❌ | `.github/skills/` | Static (determined by account entitlement) || **Cursor** | Anysphere | ✅ | ✅ | `.cursor/skills/` | Dynamic discovery |-| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/` (fallback) | Dynamic discovery |+| **Hermes** | Nous Research | ✅ | ✅ | `HERMES_HOME/skills/` (per-task home) | Dynamic discovery || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | Dynamic discovery || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | Dynamic discovery || **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | Dynamic discovery + variants |@@ -56,7 +56,7 @@ From Anysphere, the CLI counterpart to the Cursor editor. **Session resumption w### Hermes-From Nous Research. Uses the ACP protocol (shares a transport with Kimi). Session resumption works, and MCP config is passed through ACP `mcpServers`. But the **skill injection path is the generic fallback** (`.agent_context/skills/`), not a dedicated one — if the Hermes CLI itself doesn't read this path, skills may not take effect. Verify by testing.+From Nous Research. Uses the ACP protocol (shares a transport with Kimi). Session resumption works, and MCP config is passed through ACP `mcpServers`. Hermes discovers skills only from its home directory (`~/.hermes/skills/`, or `%LOCALAPPDATA%\hermes\skills\` on native Windows) and configured `skills.external_dirs` — it has no workspace-relative discovery. So **when an agent has skills assigned**, Multica points `HERMES_HOME` at a per-task overlay of your Hermes home: your real home is mirrored by symlink (auth/secrets included, so token refreshes propagate), a derived `config.yaml` references your existing skills as read-only external roots, and only the assigned skills are written into its `skills/` directory — where they take precedence, so your global skills keep working. A `-p`/`--profile` selection in `custom_args` is honored: the overlay is seeded from that profile's home, and the flag is consumed from the launch command so it can't slip past the overlay. Multica never writes to your shared home directly (it only reads it and links into it), though writes Hermes itself makes through a mirrored symlink — a token refresh, say — do propagate. Task memory is isolated per task: a fresh `memories/` directory, plus the external `memory.provider` backend is disabled in the derived config, so neither on-disk notes nor a shared Supermemory/Hindsight-style bank crosses between tasks (a managed, agent-scoped memory backend is a separate future decision). A Hermes task with no assigned skills runs against your real home unchanged.**Selecting a Hermes profile.** To launch Hermes under a specific profile, set the agent's `custom_args` to the profile flag and the profile name as two separate entries — for example, for a profile named `research`:@@ -134,10 +134,10 @@ Each tool uses **its own** skill discovery path. Before a task runs, the Multica| Pi | `.pi/skills/` | ✅ Native || Qoder | `.qoder/skills/` | ✅ Native || Antigravity | `.agents/skills/` | ✅ Native (inherits Gemini CLI's workspace layout — see [Antigravity docs](https://antigravity.google/docs/gcli-migration)) |-| Hermes | `.agent_context/skills/` | ⚠️ Generic fallback |+| Hermes | `HERMES_HOME/skills/` (per-task home) | ✅ Native (seeded per task from `~/.hermes/`) || OpenClaw | `.agent_context/skills/` | ⚠️ Generic fallback |-Whether a fallback-path tool actually reads this directory depends on the tool's own documentation — no guarantees. If your skills aren't taking effect for Hermes / OpenClaw, check this first.+Whether a fallback-path tool actually reads this directory depends on the tool's own documentation — no guarantees. If your skills aren't taking effect for OpenClaw, check this first.For native project-level paths, repo-scoped discovery is expected: if the checked-out repository already contains a matching directory, the underlying tool can discover those committed skills on its own. You do not need to import those repo skills into Multica just to use them in that repo. Multica keeps the repo files intact. If a workspace skill has the same natural directory name, the daemon writes the workspace copy to a collision-free sibling such as `review-helper-multica`.diff --git a/apps/docs/content/docs/providers.zh.mdx b/apps/docs/content/docs/providers.zh.mdxindex d2359a57ad..9619d533b3 100644--- a/apps/docs/content/docs/providers.zh.mdx+++ b/apps/docs/content/docs/providers.zh.mdx@@ -19,7 +19,7 @@ Multica 内置支持 **14 款 AI 编程工具**。它们都实现了同一套接| **Codex** | OpenAI | ✅ | ✅ | `$CODEX_HOME/skills/` | 静态 || **Copilot** | GitHub | ✅ | ❌ | `.github/skills/` | 静态(账号权益决定)|| **Cursor** | Anysphere | ✅ | ✅ | `.cursor/skills/` | 动态发现 |-| **Hermes** | Nous Research | ✅ | ✅ | `.agent_context/skills/` (fallback)| 动态发现 |+| **Hermes** | Nous Research | ✅ | ✅ | `HERMES_HOME/skills/` (单次任务 home)| 动态发现 || **Kimi** | Moonshot | ✅ | ✅ | `.kimi/skills/` | 动态发现 || **Kiro CLI** | Amazon | ✅ | ✅ | `.kiro/skills/` | 动态发现 || **OpenCode** | SST | ✅ | ✅ | `.opencode/skills/` | 动态发现 + variant |@@ -56,7 +56,7 @@ Anysphere 出品,Cursor 编辑器的 CLI 对应物。**会话恢复可用**—### Hermes-Nous Research 出品。使用 ACP 协议(和 Kimi 共享传输层)。会话恢复真用,MCP 配置通过 ACP `mcpServers` 传入。但 **skill 注入路径是通用 fallback**(`.agent_context/skills/`),不是专用路径——如果 Hermes CLI 本身不读这路径,skill 对它可能不起作用。需要结合实测再确认。+Nous Research 出品。使用 ACP 协议(和 Kimi 共享传输层)。会话恢复真用,MCP 配置通过 ACP `mcpServers` 传入。Hermes 只从自己的 home 目录(`~/.hermes/skills/`)和配置的 `skills.external_dirs` 发现 skill,没有工作区相对发现。因此,**只有当智能体分配了 skill 时**,Multica 才会把 `HERMES_HOME` 指向你 `~/.hermes/` 的单次任务 overlay:真实 home 用软链镜像(含 auth/密钥,令牌刷新可传播),派生的 `config.yaml` 把你已有的 skill 作为只读 external root 引用,只有被分配的 skill 写入它的 `skills/` 目录并具更高优先级。你的全局 skill 照常可用。Multica 不会直接写你的共享 `~/.hermes/`(只读取并链接进去),但 Hermes 自己通过被镜像的软链写入时(如刷新令牌)会传播。`custom_args` 里的 `-p`/`--profile` 选择会被尊重:overlay 从该 profile 的 home 播种,且该标志会从启动命令里消费掉,无法绕过 overlay。任务记忆按任务隔离:一个全新的 `memories/` 目录,外加在派生配置里禁用外部 `memory.provider` 后端,所以磁盘上的笔记和共享的 Supermemory/Hindsight 之类记忆库都不会在任务间串用(受管、按 agent 隔离的记忆后端是后续单独决策)。没有分配 skill 的 Hermes 任务按真实 home 原样运行。另外,home 的平台默认值在原生 Windows 上是 `%LOCALAPPDATA%\hermes`。**指定 Hermes profile。** 要让 Hermes 使用某个 profile 启动,把智能体的 `custom_args` 设成 profile flag 和 profile 名两个独立条目。例如使用名为 `research` 的 profile:@@ -126,10 +126,10 @@ ByteDance 官方 TRAE CLI(`traecli`,搭配 Trae IDE,**不是**开源的 `b| Qoder | `.qoder/skills/` | ✅ 原生 || Trae CLI | `.traecli/skills/` | ✅ 原生 || Antigravity | `.agents/skills/` | ✅ 原生(沿用 Gemini CLI 的 workspace 布局——见 [Antigravity 文档](https://antigravity.google/docs/gcli-migration))|-| Hermes | `.agent_context/skills/` | ⚠️ 通用 fallback |+| Hermes | `HERMES_HOME/skills/` (单次任务 home)| ✅ 原生(每个任务从 `~/.hermes/` 播种)|| OpenClaw | `.agent_context/skills/` | ⚠️ 通用 fallback |-fallback 路径对应的工具是否真的读取这个目录,取决于工具本身的文档——没保证。如果你的 skill 对 Hermes / OpenClaw 没起效,先查这个问题。+fallback 路径对应的工具是否真的读取这个目录,取决于工具本身的文档——没保证。如果你的 skill 对 OpenClaw 没起效,先查这个问题。对原生项目级路径来说,repo-scoped discovery 是预期行为:如果检出的仓库已经包含对应目录,底层工具可以自己发现这些提交在仓库里的 Skill。你不需要为了在这个仓库里使用这些 repo skills 而先把它们导入 Multica。Multica 会保持这些仓库文件不变。如果某个工作区 Skill 的自然目录名相同,守护进程会把工作区副本写到类似 `review-helper-multica` 的无冲突 sibling 目录。diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 48dee603be..40898edd53 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -3850,33 +3850,73 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif task.Agent != nil && provider == "openclaw" {openclawMode, openclawGateway = decodeOpenclawRuntimeConfig(task.Agent.RuntimeConfig, d.logger)}+ var agentEnvOverrides map[string]string+ var agentCustomArgs []string+ if task.Agent != nil {+ agentEnvOverrides = task.Agent.CustomEnv+ agentCustomArgs = task.Agent.CustomArgs+ }+ // Hermes: resolve the overlay source home through one resolver contract —+ // the selection parsed from custom_args (agent.ParseHermesProfileArgs) plus+ // the agent's custom_env HERMES_HOME feed execenv.ResolveHermesProfile, which+ // reproduces Hermes' own profile semantics (root derivation, explicit vs.+ // sticky selection, reserved/invalid failure). A reserved/invalid selection+ // fails the task closed, matching Hermes' sys.exit(1). The selected source+ // home is exported to hermesEnv["HERMES_HOME"] so ${HERMES_HOME} in a+ // profile's skills.external_dirs expands against the selected profile home,+ // as native Hermes does before loading config.yaml. The parsed occurrence is+ // stripped from the acp argv at launch (only when the overlay is built) so+ // the flag can't re-point HERMES_HOME past the overlay.+ var hermesSourceHome string+ var hermesSourceMustExist bool+ var hermesEnv map[string]string+ if provider == "hermes" {+ sel := agent.ParseHermesProfileArgs(agentCustomArgs)+ res := execenv.ResolveHermesProfile(agentEnvOverrides["HERMES_HOME"], sel.Name, sel.Found, sel.Inline)+ if res.Err != nil {+ return TaskResult{}, fmt.Errorf("resolve hermes profile: %w", res.Err)+ }+ hermesSourceHome = res.SourceHome+ hermesSourceMustExist = res.MustExist+ hermesEnv = sanitizeAgentEnv(agentEnvOverrides)+ if hermesEnv == nil {+ hermesEnv = map[string]string{}+ }+ hermesEnv["HERMES_HOME"] = res.SourceHome+ }if task.PriorWorkDir != "" && localAssignment == nil && !task.IsLeaderTask {env = execenv.Reuse(execenv.ReuseParams{- WorkspacesRoot: d.cfg.WorkspacesRoot,- WorkDir: task.PriorWorkDir,- Provider: provider,- CodexVersion: codexVersion,- OpenclawBin: openclawBin,- McpConfig: effectiveMcpConfig,- CursorMcpAuthSource: cursorMcpAuthSource,- OpenclawGateway: openclawGateway,- Task: taskCtx,+ WorkspacesRoot: d.cfg.WorkspacesRoot,+ WorkDir: task.PriorWorkDir,+ Provider: provider,+ CodexVersion: codexVersion,+ OpenclawBin: openclawBin,+ McpConfig: effectiveMcpConfig,+ CursorMcpAuthSource: cursorMcpAuthSource,+ OpenclawGateway: openclawGateway,+ HermesSourceHome: hermesSourceHome,+ HermesSourceMustExist: hermesSourceMustExist,+ HermesEnv: hermesEnv,+ Task: taskCtx,}, d.logger)}if env == nil {var err errorprepParams := execenv.PrepareParams{- WorkspacesRoot: d.cfg.WorkspacesRoot,- WorkspaceID: task.WorkspaceID,- TaskID: task.ID,- AgentName: agentName,- Provider: provider,- CodexVersion: codexVersion,- OpenclawBin: openclawBin,- McpConfig: effectiveMcpConfig,- CursorMcpAuthSource: cursorMcpAuthSource,- OpenclawGateway: openclawGateway,- Task: taskCtx,+ WorkspacesRoot: d.cfg.WorkspacesRoot,+ WorkspaceID: task.WorkspaceID,+ TaskID: task.ID,+ AgentName: agentName,+ Provider: provider,+ CodexVersion: codexVersion,+ OpenclawBin: openclawBin,+ McpConfig: effectiveMcpConfig,+ CursorMcpAuthSource: cursorMcpAuthSource,+ OpenclawGateway: openclawGateway,+ HermesSourceHome: hermesSourceHome,+ HermesSourceMustExist: hermesSourceMustExist,+ HermesEnv: hermesEnv,+ Task: taskCtx,}if localAssignment != nil {prepParams.LocalWorkDir = localAssignment.AbsPath@@ -4019,6 +4059,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif env.CodexHome != "" {agentEnv["CODEX_HOME"] = env.CodexHome}+ // (Hermes HERMES_HOME is applied after custom_env below so the per-task+ // overlay can win over a user-set HERMES_HOME; see+ // layerCustomEnvAndHermesHome.)// Point Cursor at per-task project state when managed MCP is present.// The workdir .cursor/mcp.json carries the managed server list, while// CURSOR_DATA_DIR isolates the matching project approvals from the user's@@ -4047,15 +4090,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// Bedrock). These are set per-agent via the agent settings UI.// Critical internal variables are blocklisted to prevent accidental or// malicious override of daemon-set values.+ var agentCustomEnv map[string]stringif task.Agent != nil {- for k, v := range task.Agent.CustomEnv {- if isBlockedEnvKey(k) {- d.logger.Warn("custom_env: blocked key skipped", "key", k)- continue- }- agentEnv[k] = v- }+ agentCustomEnv = task.Agent.CustomEnv}+ layerCustomEnvAndHermesHome(agentEnv, agentCustomEnv, env.HermesHome, d.logger)backend, err := agent.New(provider, agent.Config{ExecutablePath: entry.Path,Env: agentEnv,@@ -4087,6 +4126,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot icustomArgs = task.Agent.CustomArgsmcpConfig = effectiveMcpConfig}+ if provider == "hermes" {+ customArgs = hermesLaunchArgs(customArgs, env != nil && env.HermesHome != "")+ }// Two-tier model resolution: an explicit agent.model wins,// then the daemon-wide MULTICA_<PROVIDER>_MODEL env var. If// both are empty we deliberately pass "" through — each@@ -5005,6 +5047,63 @@ func isBlockedEnvKey(key string) bool {return false}+// layerCustomEnvAndHermesHome applies the agent's custom_env onto the child env+// (skipping daemon-internal blocklisted keys), then overrides HERMES_HOME with+// the per-task overlay when one was built. HERMES_HOME is intentionally NOT+// blocklisted: with skills bound the overlay is built FROM the user's+// HERMES_HOME and must win here; with no skills bound (overlayHome empty) the+// user's own HERMES_HOME passes through unchanged, so a skill-less Hermes task+// keeps its original behavior.+// sanitizeAgentEnv returns the agent custom_env with daemon-blocklisted keys+// removed — the effective env the Hermes child actually sees, used to expand+// ${VAR} in external_dirs consistently (blocked keys like HOME resolve to the+// daemon process value, not the dropped custom one). Uses the same+// isBlockedEnvKey rule as layerCustomEnvAndHermesHome so the two agree.+func sanitizeAgentEnv(customEnv map[string]string) map[string]string {+ if len(customEnv) == 0 {+ return nil+ }+ out := make(map[string]string, len(customEnv))+ for k, v := range customEnv {+ if isBlockedEnvKey(k) {+ continue+ }+ out[k] = v+ }+ return out+}++// hermesLaunchArgs decides the final Hermes custom_args: with the per-task+// overlay active, the -p/--profile flags are stripped (the overlay was seeded+// from that profile's home and exports its own HERMES_HOME, so the flag must not+// re-resolve the profile past it); with no overlay, the flags pass through so a+// skill-less task's profile behavior is unchanged.+func hermesLaunchArgs(customArgs []string, overlayActive bool) []string {+ if !overlayActive {+ return customArgs+ }+ // Strip exactly the occurrence the resolver acted on. This re-parses with the+ // same authoritative parser used to resolve the source home, so parsing and+ // stripping never diverge.+ sel := agent.ParseHermesProfileArgs(customArgs)+ return agent.StripHermesProfileArgs(customArgs, sel)+}++func layerCustomEnvAndHermesHome(agentEnv, customEnv map[string]string, overlayHome string, logger *slog.Logger) {+ for k, v := range customEnv {+ if isBlockedEnvKey(k) {+ if logger != nil {+ logger.Warn("custom_env: blocked key skipped", "key", k)+ }+ continue+ }+ agentEnv[k] = v+ }+ if overlayHome != "" {+ agentEnv["HERMES_HOME"] = overlayHome+ }+}+func defaultArgsForProvider(cfg Config, provider string) []string {var args []stringswitch provider {diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex ea9a254fbb..e0e345dee7 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -161,6 +161,11 @@ func TestIsBlockedEnvKey(t *testing.T) {{key: "OPENCLAW_INCLUDE_ROOTS", want: true},{key: "ANTHROPIC_API_KEY", want: false},{key: "CURSOR_AGENT", want: false},+ // HERMES_HOME is intentionally NOT blocked: a skill-less Hermes task+ // must be able to honor a user-set profile/home, and when skills are+ // bound the per-task overlay overrides it after custom_env is layered.+ {key: "HERMES_HOME", want: false},+ {key: "hermes_home", want: false},}for _, tt := range tests {@@ -173,6 +178,68 @@ func TestIsBlockedEnvKey(t *testing.T) {}}+// TestLayerCustomEnvAndHermesHome exercises the daemon-assembled child env for+// HERMES_HOME: no overlay passes the user's value through, an overlay overrides+// it, and blocklisted keys are still dropped.+func TestLayerCustomEnvAndHermesHome(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ customEnv map[string]string+ overlayHome string+ wantHermes string // "" means the key must be absent+ wantAbsent []string+ }{+ {+ name: "no skills: user HERMES_HOME passes through",+ customEnv: map[string]string{"HERMES_HOME": "/home/u/.hermes-research"},+ overlayHome: "",+ wantHermes: "/home/u/.hermes-research",+ },+ {+ name: "skills bound: overlay overrides user HERMES_HOME",+ customEnv: map[string]string{"HERMES_HOME": "/home/u/.hermes-research"},+ overlayHome: "/tmp/task/hermes-home",+ wantHermes: "/tmp/task/hermes-home",+ },+ {+ name: "no custom home, no overlay: key absent",+ customEnv: map[string]string{"ANTHROPIC_API_KEY": "sk"},+ overlayHome: "",+ wantHermes: "",+ },+ {+ name: "blocklisted key dropped, overlay still applied",+ customEnv: map[string]string{"CODEX_HOME": "/evil", "MULTICA_TOKEN": "x"},+ overlayHome: "/tmp/task/hermes-home",+ wantHermes: "/tmp/task/hermes-home",+ wantAbsent: []string{"CODEX_HOME", "MULTICA_TOKEN"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ t.Parallel()+ agentEnv := map[string]string{}+ layerCustomEnvAndHermesHome(agentEnv, tt.customEnv, tt.overlayHome, nil)++ if got, ok := agentEnv["HERMES_HOME"]; tt.wantHermes == "" {+ if ok {+ t.Errorf("HERMES_HOME should be absent, got %q", got)+ }+ } else if got != tt.wantHermes {+ t.Errorf("HERMES_HOME = %q, want %q", got, tt.wantHermes)+ }+ for _, k := range tt.wantAbsent {+ if _, ok := agentEnv[k]; ok {+ t.Errorf("blocklisted key %q should not be applied", k)+ }+ }+ })+ }+}+func TestTaskScopedAuthToken(t *testing.T) {t.Parallel()@@ -3082,3 +3149,67 @@ func TestWatchTaskCancellation_ReconcileRunningKeepsTickerAlive(t *testing.T) {t.Fatalf("ticker did not detect cancellation after broadcast-running path (calls=%d)", calls.Load())}}++// TestSanitizeAgentEnv asserts the effective env handed to the Hermes overlay+// for ${VAR} expansion drops daemon-blocklisted keys (so a blocked HOME in+// custom_env can't repoint external_dirs away from what the child sees) while+// keeping ordinary vars.+func TestSanitizeAgentEnv(t *testing.T) {+ t.Parallel()+ in := map[string]string{+ "HOME": "/evil",+ "PATH": "/evil/bin",+ "MULTICA_X": "1",+ "TEAM_SKILLS": "/srv/team",+ "HERMES_HOME": "/some/home",+ }+ got := sanitizeAgentEnv(in)+ for _, blocked := range []string{"HOME", "PATH", "MULTICA_X"} {+ if _, ok := got[blocked]; ok {+ t.Errorf("blocklisted key %q must be dropped from the effective env", blocked)+ }+ }+ if got["TEAM_SKILLS"] != "/srv/team" {+ t.Errorf("ordinary var dropped: %v", got)+ }+ // HERMES_HOME is not blocklisted (it drives source-home resolution), so it+ // survives here even though the child's value is the overlay.+ if got["HERMES_HOME"] != "/some/home" {+ t.Errorf("HERMES_HOME should survive sanitization, got %v", got)+ }+ if sanitizeAgentEnv(nil) != nil {+ t.Error("nil in should yield nil out")+ }+}++// TestHermesLaunchArgsAndEnvByScenario covers the profile chain end to end at+// the decision level: the final launch args + the final HERMES_HOME the child+// sees, for a skill-less vs. an overlay-active task that both set a profile.+func TestHermesLaunchArgsAndEnvByScenario(t *testing.T) {+ t.Parallel()+ customArgs := []string{"-p", "research", "--yolo"}+ customEnv := map[string]string{"HERMES_HOME": "/home/u/.hermes"}++ // No overlay (skill-less): profile flag passes through, and the user's+ // HERMES_HOME passes through — behavior unchanged.+ noOverlayArgs := hermesLaunchArgs(customArgs, false)+ if len(noOverlayArgs) != 3 || noOverlayArgs[0] != "-p" || noOverlayArgs[1] != "research" {+ t.Errorf("skill-less task must keep its profile flags, got %v", noOverlayArgs)+ }+ noOverlayEnv := map[string]string{}+ layerCustomEnvAndHermesHome(noOverlayEnv, customEnv, "", nil)+ if noOverlayEnv["HERMES_HOME"] != "/home/u/.hermes" {+ t.Errorf("skill-less task must keep the user HERMES_HOME, got %q", noOverlayEnv["HERMES_HOME"])+ }++ // Overlay active: profile flag is stripped, and HERMES_HOME is the overlay.+ overlayArgs := hermesLaunchArgs(customArgs, true)+ if len(overlayArgs) != 1 || overlayArgs[0] != "--yolo" {+ t.Errorf("overlay task must strip profile flags, got %v", overlayArgs)+ }+ overlayEnv := map[string]string{}+ layerCustomEnvAndHermesHome(overlayEnv, customEnv, "/task/hermes-home", nil)+ if overlayEnv["HERMES_HOME"] != "/task/hermes-home" {+ t.Errorf("overlay task must redirect HERMES_HOME to the overlay, got %q", overlayEnv["HERMES_HOME"])+ }+}diff --git a/server/internal/daemon/execenv/context.go b/server/internal/daemon/execenv/context.goindex b4b4e4d5e3..a6f2e4fd2f 100644--- a/server/internal/daemon/execenv/context.go+++ b/server/internal/daemon/execenv/context.go@@ -121,6 +121,7 @@ func writeWorkspacesRootMarkerAtomic(path string, data []byte) error {//// Claude: skills → {workDir}/.claude/skills/{name}/SKILL.md (native discovery)// Codex: skills → handled separately in Prepare via codex-home+// Hermes: skills → handled separately in Prepare via hermes-home (HERMES_HOME/skills; Hermes has no workspace-relative discovery, see hermes_home.go)// Copilot: skills → {workDir}/.github/skills/{name}/SKILL.md (native project-level discovery)// OpenCode: skills → {workDir}/.opencode/skills/{name}/SKILL.md (native discovery)// OpenClaw: skills → {workDir}/skills/{name}/SKILL.md (native discovery — paired with a per-task synthesized openclaw-config.json that pins agents.defaults.workspace to workDir; see openclaw_config.go)@@ -165,14 +166,20 @@ func writeContextFiles(workDir, provider string, ctx TaskContextForEnv, manifest}if len(ctx.AgentSkills) > 0 {- skillsDir, err := resolveSkillsDir(workDir, provider, manifest)- if err != nil {- return fmt.Errorf("resolve skills dir: %w", err)- }- // Codex skills are written to codex-home in Prepare; skip here.- if provider != "codex" {- if err := writeSkillFiles(skillsDir, ctx.AgentSkills, manifest); err != nil {- return fmt.Errorf("write skill files: %w", err)+ // Hermes materializes skills into its per-task HERMES_HOME/skills during+ // Prepare (Hermes has no workspace-relative discovery), so it needs no+ // workdir-local skills dir at all — skip the resolve too, to avoid+ // leaving an empty .agent_context/skills/ behind.+ if provider != "hermes" {+ skillsDir, err := resolveSkillsDir(workDir, provider, manifest)+ if err != nil {+ return fmt.Errorf("resolve skills dir: %w", err)+ }+ // Codex skills are written to codex-home in Prepare; skip here.+ if provider != "codex" {+ if err := writeSkillFiles(skillsDir, ctx.AgentSkills, manifest); err != nil {+ return fmt.Errorf("write skill files: %w", err)+ }}}}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 3857bd5309..6aa2a91c90 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -64,7 +64,20 @@ type PrepareParams struct {// substituted. Used by the local_directory project_resource flow// (MUL-2663). When set, the envRoot/workdir directory is not created.LocalWorkDir string- Task TaskContextForEnv // context data for writing files+ // HermesSourceHome is the shared Hermes home the per-task overlay is seeded+ // from — resolved by the daemon via execenv.ResolveHermesProfile so it honors+ // the agent's custom_env HERMES_HOME and any -p/--profile or sticky selection.+ // Only used for the hermes provider; empty falls back to the platform default.+ HermesSourceHome string+ // HermesSourceMustExist fails the overlay build closed when HermesSourceHome+ // is absent — set when an explicit named profile was requested so a typo+ // doesn't silently seed from an empty home and drop the user's auth/config.+ HermesSourceMustExist bool+ // HermesEnv is the sanitized effective env (agent custom_env minus the daemon+ // blocklisted keys) used to expand ${VAR} in Hermes external_dirs so it+ // matches what the Hermes child process actually sees. Only used for hermes.+ HermesEnv map[string]string+ Task TaskContextForEnv // context data for writing files}// TaskContextForEnv is the subset of task context used for writing context files.@@ -179,6 +192,16 @@ type Environment struct {// exports this as CURSOR_DATA_DIR so project-level MCP approvals are// isolated from the user's persistent ~/.cursor/projects state.CursorDataDir string+ // HermesHome is the path to the per-task HERMES_HOME overlay (set only for+ // the hermes provider, and only when the agent has skills bound — empty+ // otherwise, leaving the user's real home in place). It mirrors ~/.hermes/+ // via symlink, derives a config.yaml that references the user's real skills+ // as an external root, and holds the bound skills in its skills/ subdir. The+ // daemon exports it as HERMES_HOME so the hermes CLI discovers those skills+ // natively — Hermes has no workspace-relative discovery, so the previous+ // .agent_context/skills/ fallback was never read (issue #5242). See+ // hermes_home.go.+ HermesHome stringlogger *slog.Logger // for cleanup logging}@@ -274,6 +297,20 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {env.CodexHome = codexHome}+ // For Hermes, redirect HERMES_HOME to a per-task compatibility overlay ONLY+ // when the agent has skills bound. A skill-less Hermes task keeps the user's+ // real home and its original behavior untouched. The overlay makes the bound+ // skills visible — Hermes discovers skills only from its home, so the old+ // .agent_context/skills/ fallback was never read (issue #5242). See+ // hermes_home.go.+ if params.Provider == "hermes" && len(params.Task.AgentSkills) > 0 {+ hermesHome := filepath.Join(envRoot, "hermes-home")+ if err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, logger); err != nil {+ return nil, fmt.Errorf("execenv: prepare hermes-home: %w", err)+ }+ env.HermesHome = hermesHome+ }+// For Cursor, materialize managed MCP into project-local config and use// an isolated CURSOR_DATA_DIR for the per-workdir approval sidecar. Cursor// still reads ~/.cursor/mcp.json, but only servers with approval entries in@@ -343,7 +380,13 @@ type ReuseParams struct {// loop) keep the "never delete the user's directory" invariant on// reuse paths.LocalDirectory bool- Task TaskContextForEnv // refreshed context files / skills+ // HermesSourceHome and HermesEnv mirror PrepareParams on reuse so the Hermes+ // overlay re-derives against the agent's current source home / profile and+ // external_dirs vars.+ HermesSourceHome string+ HermesSourceMustExist bool+ HermesEnv map[string]string+ Task TaskContextForEnv // refreshed context files / skills}// Reuse wraps an existing workdir into an Environment and refreshes context files.@@ -448,6 +491,32 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {}}+ // Refresh (or tear down) the per-task HERMES_HOME on reuse. With skills+ // bound, rebuild the overlay so an added/removed/edited skill and the+ // mirrored home/config track the user's current ~/.hermes/ before the next+ // hermes process starts. With no skills bound, drop the redirect entirely so+ // the task reverts to the user's real home — matching a fresh Prepare for a+ // skill-less agent.+ if params.Provider == "hermes" && env.RootDir != "" {+ hermesHome := filepath.Join(env.RootDir, "hermes-home")+ if len(params.Task.AgentSkills) > 0 {+ if err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, logger); err != nil {+ // Fail closed: a half-built overlay must not run. Returning nil+ // makes the daemon fall back to a fresh Prepare, whose error+ // then blocks dispatch rather than silently dropping the bound+ // skill.+ logger.Warn("execenv: refresh hermes-home failed; forcing fresh prepare", "error", err)+ return nil+ }+ env.HermesHome = hermesHome+ } else {+ env.HermesHome = ""+ if err := os.RemoveAll(hermesHome); err != nil {+ logger.Warn("execenv: remove stale hermes-home failed", "error", err)+ }+ }+ }+// Refresh Cursor's managed MCP sidecars on reuse. A newly saved agent// mcp_config must replace the prior run's .cursor/mcp.json and isolated// approvals before the next cursor-agent process starts.diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 67e9b11e52..bb59aa6945 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -1863,14 +1863,15 @@ func TestInjectRuntimeConfigHermes(t *testing.T) {if !strings.Contains(s, "Coding") {t.Error("AGENTS.md missing skill name")}- // Hermes has no native skill discovery path wired up, so AGENTS.md must- // point the agent at the .agent_context/skills/ fallback — NOT claim that- // skills are "discovered automatically".- if strings.Contains(s, "discovered automatically") {- t.Error("AGENTS.md for Hermes should not claim native skill discovery")+ // Hermes now discovers skills from the daemon-seeded per-task+ // HERMES_HOME/skills (see hermes_home.go), so AGENTS.md must use the+ // "discovered automatically" framing and must NOT point the agent at the+ // old .agent_context/skills/ fallback it never read (issue #5242).+ if !strings.Contains(s, "discovered automatically") {+ t.Error("AGENTS.md for Hermes should describe skills as discovered automatically")}- if !strings.Contains(s, ".agent_context/skills/") {- t.Error("AGENTS.md for Hermes should reference .agent_context/skills/ fallback path")+ if strings.Contains(s, ".agent_context/skills/") {+ t.Error("AGENTS.md for Hermes should not reference the .agent_context/skills/ fallback path")}// CLAUDE.md should NOT exist.@@ -1879,7 +1880,13 @@ func TestInjectRuntimeConfigHermes(t *testing.T) {}}-func TestWriteContextFilesHermesFallbackSkills(t *testing.T) {+// TestWriteContextFilesHermesSkipsWorkdirSkills asserts that Hermes skills are+// NOT materialized into the workdir. Hermes has no workspace-relative skill+// discovery; the daemon seeds them into a per-task HERMES_HOME/skills instead+// (see prepareHermesHome / TestPrepareHermesHome). Writing the old+// .agent_context/skills/ fallback was pure dead weight the CLI never read+// (issue #5242).+func TestWriteContextFilesHermesSkipsWorkdirSkills(t *testing.T) {t.Parallel()dir := t.TempDir()@@ -1894,14 +1901,15 @@ func TestWriteContextFilesHermesFallbackSkills(t *testing.T) {t.Fatalf("writeContextFiles failed: %v", err)}- // Skills should be in the fallback .agent_context/skills/ path since- // Hermes has no native skills discovery directory.- skillMd, err := os.ReadFile(filepath.Join(dir, ".agent_context", "skills", "go-conventions", "SKILL.md"))- if err != nil {- t.Fatalf("failed to read .agent_context/skills/go-conventions/SKILL.md: %v", err)+ // No skills dir should be created in the workdir for Hermes — not the old+ // fallback, and not an empty leftover directory either.+ if _, err := os.Stat(filepath.Join(dir, ".agent_context", "skills")); !os.IsNotExist(err) {+ t.Errorf("expected no .agent_context/skills/ for Hermes, got err=%v", err)}- if !strings.Contains(string(skillMd), "Follow Go conventions.") {- t.Error("SKILL.md missing content")++ // issue_context.md should still be written under .agent_context/.+ if _, err := os.Stat(filepath.Join(dir, ".agent_context", "issue_context.md")); err != nil {+ t.Errorf("expected .agent_context/issue_context.md to exist: %v", err)}}diff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.gonew file mode 100644index 0000000000..8ad5af02ec--- /dev/null+++ b/server/internal/daemon/execenv/hermes_home.go@@ -0,0 +1,826 @@+package execenv++import (+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "regexp"+ "runtime"+ "strings"++ "gopkg.in/yaml.v3"+)++// Hermes discovers skills from exactly two places (verified against the bundled+// Hermes agent source, agent/skill_utils.py get_all_skills_dirs): its home+// skills dir `<HERMES_HOME>/skills/` first, then the directories listed under+// `skills.external_dirs` in `<HERMES_HOME>/config.yaml`, in config order. It has+// NO workspace-relative discovery, so the generic `.agent_context/skills/`+// fallback the daemon used before was never scanned and workspace-assigned+// skills silently never took effect (issue #5242).+//+// Rather than replace HERMES_HOME with a home rebuilt from a fixed allowlist —+// which would silently change behavior for tasks that don't even use skills and+// would drop any home state not on the list (plugins, OAuth state, hooks, SOUL,+// scripts, and whatever Hermes adds next) — this builds a minimal compatibility+// overlay, and only when the agent actually has skills bound (gated at the call+// site in Prepare/Reuse; a skill-less Hermes task keeps HERMES_HOME untouched).+//+// The overlay:+// - mirrors every top-level entry of the shared ~/.hermes/ into the per-task+// home via symlink, EXCEPT the entries it overrides — so the denylist stays+// tiny and future home state is inherited automatically instead of being+// missed by an allowlist;+// - derives a task-local config.yaml whose `skills.external_dirs` points at+// the shared skills dir plus the user's existing external_dirs, expanded+// against the agent's effective env and normalized to absolute paths (Hermes+// resolves relative external_dirs against HERMES_HOME, so leaving them+// relative after the redirect would silently repoint them) — this exposes+// the user's global/builtin skills read-only without copying them;+// - populates the task-local `skills/` dir with ONLY the Multica-bound skills,+// which take precedence because Hermes lists the home skills dir first;+// - keeps `memories/` overlay-owned (a fresh per-task dir), NOT symlinked to+// the shared home: Hermes loads and writes back MEMORY.md/USER.md there, and+// per-agent memory is a Multica product concern — the host's local Hermes+// memory must not bleed into a task, nor task memory back out to the host;+// - disables the external `memory.provider` in the derived config so a+// host-configured Supermemory/Hindsight/etc. backend isn't shared across+// tasks. This is the on-disk + external-backend memory isolation; a managed,+// agent-scoped memory backend is a separate future product decision.+//+// The shared ~/.hermes/ is never modified by this setup. Note however that+// mirrored entries are writable symlinks, so if Hermes writes through one at+// runtime (e.g. refreshing token state under a mirrored auth/OAuth path) that+// write does reach the shared home — that propagation is intentional.++// hermesOverriddenEntries are the top-level entries of the shared ~/.hermes/+// that the overlay supplies its own task-local version of, so they are NOT+// mirrored from the shared home and are preserved across reuse reconciliation:+// - skills/ task-local, only the bound skills+// - config.yaml derived config with absolutized external_dirs+// - memories/ fresh per-task dir, isolated from the host's memory+//+// Everything else in the shared home is mirrored generically.+//+// active_profile and profiles are also overlay-owned (never mirrored): Hermes+// reads <HERMES_HOME>/active_profile at startup and, if it names a non-default+// profile, redirects HERMES_HOME to that real profile — which would bypass the+// overlay's skills and memory isolation. Keeping active_profile out of the+// overlay means Hermes finds none and stays put. The overlay is already seeded+// from the correct (possibly profile) source home.+//+// .env is overlay-owned too, but unlike the others it is DERIVED, not just+// omitted (see writeDerivedHermesEnv): Hermes runs _apply_profile_override()+// and then load_hermes_dotenv(), which loads <HERMES_HOME>/.env with+// override=True. A source .env carrying an out-of-band HERMES_HOME= would+// overwrite the overlay's HERMES_HOME after the argv/sticky-profile protections+// ran, repointing skill discovery and memory back at the source home. The+// derived overlay .env preserves the source's credentials/settings but pins+// HERMES_HOME to the overlay, and is written even when the source has none so+// Hermes' project-.env fallback (loaded with override=True only when no user+// .env loaded) can't relocate the home either.+var hermesOverriddenEntries = map[string]struct{}{+ "skills": {},+ "config.yaml": {},+ "memories": {},+ "active_profile": {},+ "profiles": {},+ ".env": {},+}++// platformDefaultHermesHome returns Hermes' platform-native default home:+// %LOCALAPPDATA%\hermes on native Windows, ~/.hermes elsewhere — matching+// hermes_constants._get_platform_default_hermes_home. Without the Windows branch+// a Windows user with no explicit HERMES_HOME would seed the overlay from an+// empty ~/.hermes and lose their real config/auth/global skills.+func platformDefaultHermesHome() string {+ la, _ := os.LookupEnv("LOCALAPPDATA")+ home, _ := os.UserHomeDir()+ return platformDefaultHermesHomeFor(runtime.GOOS, la, home)+}++// platformDefaultHermesHomeFor is the pure core of platformDefaultHermesHome,+// split out so the Windows branch is testable off a Windows host. It matches+// hermes_constants._get_platform_default_hermes_home: on Windows the base is+// %LOCALAPPDATA%, or %USERPROFILE%\AppData\Local when LOCALAPPDATA is unset,+// with `hermes` appended; POSIX uses ~/.hermes.+func platformDefaultHermesHomeFor(goos, localAppData, userHome string) string {+ if goos == "windows" {+ base := strings.TrimSpace(localAppData)+ if base == "" && userHome != "" {+ base = filepath.Join(userHome, "AppData", "Local")+ }+ if base != "" {+ return filepath.Join(base, "hermes")+ }+ }+ if userHome != "" {+ return filepath.Join(userHome, ".hermes")+ }+ return filepath.Join(os.TempDir(), ".hermes") // last-resort fallback+}++// hermesProfileNameRe mirrors Hermes' hermes_cli.profiles._PROFILE_ID_RE — the+// shape a profile identifier must have on disk and in argv.+var hermesProfileNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`)++// hermesReservedProfileNames mirrors hermes_cli.profiles._RESERVED_NAMES: names+// Hermes' validate_profile_name rejects (they would collide with the install+// itself or a common system binary). "default" is in Hermes' set too but is a+// special pass-through there — it names the root home — so it is handled before+// this check, not listed here.+var hermesReservedProfileNames = map[string]struct{}{+ "hermes": {}, "test": {}, "tmp": {}, "root": {}, "sudo": {},+}++// HermesProfileResolution is the single authoritative result of resolving a+// Hermes profile selection: the source home to seed the overlay from (and to+// expand ${HERMES_HOME} against), whether that home must already exist, and a+// non-nil Err when the selection is one Hermes would refuse to start under.+type HermesProfileResolution struct {+ // SourceHome is the resolved HERMES_HOME the overlay is built from. It is+ // also the value ${HERMES_HOME} in a profile's skills.external_dirs expands+ // to, matching native Hermes applying the profile override before it loads+ // config.yaml.+ SourceHome string+ // MustExist fails the overlay closed when SourceHome is absent — set for a+ // named/profile-scoped source so a typo doesn't silently seed from an empty+ // dir and drop the user's auth/config, matching Hermes' own FileNotFoundError+ // sys.exit on a missing profile.+ MustExist bool+ // Err is set when the selection names a reserved or otherwise invalid+ // profile (including the empty inline `--profile=` value). Hermes sys.exit(1)s+ // in these cases, so the daemon must fail the task closed rather than start+ // it under the default profile.+ Err error+}++// ResolveHermesProfile is the one resolver contract for Hermes profile+// selection. Given the agent's custom_env HERMES_HOME and the profile selection+// already parsed from custom_args (agent.ParseHermesProfileArgs), it reproduces+// hermes_cli.main._apply_profile_override + hermes_cli.profiles semantics:+//+// - The Hermes root is derived exactly like get_default_hermes_root: an+// explicit custom_env HERMES_HOME, else the process HERMES_HOME, else the+// platform default; if that home is itself <root>/profiles/<name>, the root+// is <root> (profiles are always resolved against the root, never nested).+// - An explicit -p/--profile wins. Otherwise an already-profile-scoped+// HERMES_HOME is trusted as-is (step 1.5), and only failing that is the+// sticky <root>/active_profile consulted (step 2).+// - The chosen name is normalized + validated like normalize_profile_name /+// validate_profile_name: "default" (case-insensitively) means the root home;+// an empty, malformed, or reserved name is a hard error (Err set).+// - A valid named profile resolves to <root>/profiles/<name> and MustExist.+//+// found/inline come from the parsed selection: found means an explicit flag with+// a value matched; inline distinguishes the `--profile=<value>` form, whose empty+// value must hard-fail rather than fall back to the default.+func ResolveHermesProfile(customEnvHome, name string, found, inline bool) HermesProfileResolution {+ base := strings.TrimSpace(customEnvHome)+ if base == "" {+ base = strings.TrimSpace(os.Getenv("HERMES_HOME"))+ }+ if base == "" {+ base = platformDefaultHermesHome()+ }+ if abs, err := filepath.Abs(base); err == nil {+ base = abs+ }+ root := hermesRootFromHome(base)++ profile := name+ if !found {+ // Step 1.5: trust an already-profile-scoped HERMES_HOME (immediate parent+ // dir named "profiles") without consulting active_profile.+ if base != "" && filepath.Base(filepath.Dir(base)) == "profiles" {+ return HermesProfileResolution{SourceHome: base, MustExist: true}+ }+ // Step 2: honor the sticky <root>/active_profile. (The container-only+ // HERMES_S6_SUPERVISED_CHILD exception in Hermes does not apply to a+ // daemon task spawn.) When no sticky applies, the base home (the+ // root/default) is the source.+ profile = readHermesActiveProfile(root)+ if profile == "" {+ return HermesProfileResolution{SourceHome: base}+ }+ }++ // An explicit selection (found) is always validated — an empty inline value+ // (`--profile=`) is a hard error, not a fall-back to the default — as is a+ // sticky name, matching Hermes calling resolve_profile_env on both.+ home, mustExist, err := hermesProfileDir(root, profile)+ if err != nil {+ return HermesProfileResolution{Err: err}+ }+ return HermesProfileResolution{SourceHome: home, MustExist: mustExist}+}++// hermesRootFromHome reproduces hermes_constants.get_default_hermes_root: the+// root for profile-level operations. If base is the platform default or lives+// under it (normal or profile mode) the root is the platform default; otherwise+// (Docker/custom home) a <...>/profiles/<name> layout roots at the grandparent,+// and any other path is its own root.+func hermesRootFromHome(base string) string {+ return hermesRootFromHomeFor(base, platformDefaultHermesHome())+}++// hermesRootFromHomeFor is the pure core of hermesRootFromHome with the native+// home injected for testability. The containment test resolves symlinks on both+// sides (like get_default_hermes_root's env_path.resolve().relative_to(+// native_home.resolve())), so a HERMES_HOME symlinked into <native>/profiles/<x>+// still roots at native. The RETURNED value stays unresolved, matching Hermes,+// which returns native_home / the lexical grandparent of the original env_path.+func hermesRootFromHomeFor(base, native string) string {+ if base == "" {+ return native+ }+ if isPathUnder(resolvePathBestEffort(native), resolvePathBestEffort(base)) {+ return native+ }+ if filepath.Base(filepath.Dir(base)) == "profiles" {+ return filepath.Dir(filepath.Dir(base))+ }+ return base+}++// resolvePathBestEffort resolves symlinks like Python's Path.resolve(strict=False):+// it follows every symlink in the existing prefix of p and appends the remaining+// non-existent tail unchanged, rather than failing (as filepath.EvalSymlinks does)+// when p doesn't fully exist. The result is absolute.+func resolvePathBestEffort(p string) string {+ if p == "" {+ return p+ }+ if abs, err := filepath.Abs(p); err == nil {+ p = abs+ }+ if resolved, err := filepath.EvalSymlinks(p); err == nil {+ return resolved+ }+ dir := p+ var tail []string+ for {+ parent := filepath.Dir(dir)+ if parent == dir {+ return p // reached the root without an existing ancestor+ }+ tail = append([]string{filepath.Base(dir)}, tail...)+ dir = parent+ if resolved, err := filepath.EvalSymlinks(dir); err == nil {+ return filepath.Join(append([]string{resolved}, tail...)...)+ }+ }+}++// isPathUnder reports whether child is parent or nested under it.+func isPathUnder(parent, child string) bool {+ rel, err := filepath.Rel(parent, child)+ if err != nil {+ return false+ }+ return rel == "." || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)))+}++// readHermesActiveProfile returns the sticky profile name from+// <root>/active_profile, or "" when absent, unreadable, empty, or "default"+// (matching _apply_profile_override step 2, which ignores a "default" sticky).+func readHermesActiveProfile(root string) string {+ data, err := os.ReadFile(filepath.Join(root, "active_profile"))+ if err != nil {+ return ""+ }+ name := strings.TrimSpace(string(data))+ if name == "default" {+ return ""+ }+ return name+}++// hermesProfileDir resolves a profile name against root, reproducing+// normalize_profile_name + validate_profile_name + get_profile_dir. It returns+// the home dir, whether that home must already exist (true for a named profile),+// or an error for an empty/malformed/reserved name (which Hermes sys.exit(1)s on).+func hermesProfileDir(root, name string) (home string, mustExist bool, err error) {+ stripped := strings.TrimSpace(name)+ if stripped == "" {+ return "", false, fmt.Errorf("hermes profile name cannot be empty")+ }+ var canon string+ if strings.EqualFold(stripped, "default") {+ canon = "default"+ } else {+ canon = strings.ToLower(stripped)+ }+ if canon == "default" {+ return root, false, nil // the default profile IS the root home+ }+ if !hermesProfileNameRe.MatchString(canon) {+ return "", false, fmt.Errorf("invalid hermes profile name %q", canon)+ }+ if _, reserved := hermesReservedProfileNames[canon]; reserved {+ return "", false, fmt.Errorf("hermes profile name %q is reserved", canon)+ }+ return filepath.Join(root, "profiles", canon), true, nil+}++// prepareHermesHome builds the per-task HERMES_HOME compatibility overlay+// described above. The daemon exports the given path as HERMES_HOME on the+// hermes subprocess so the CLI discovers the bound skills natively.+//+// Callers gate this on the agent having skills bound; it is a full rebuild each+// time (mirror reconciled, config re-derived, bound skills rewritten) so a Reuse+// after a skill/config change lands cleanly. It fails CLOSED: if the mirror, the+// derived config, or the bound skills can't be established the whole overlay is+// unusable, so the error propagates and the caller must not start Hermes against+// a half-built home.+// sourceHome is the shared home to seed from (resolved by the daemon via+// ResolveHermesProfile, honoring the agent's HERMES_HOME/profile); empty+// falls back to the platform default. sourceMustExist fails closed when the+// source home is absent — set for an explicitly named profile so a typo doesn't+// silently seed from an empty dir and drop the user's auth/config. env is the+// sanitized effective env used to expand ${VAR} in external_dirs so it matches+// what the Hermes child sees.+func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, logger *slog.Logger) error {+ sharedHome := strings.TrimSpace(sourceHome)+ if sharedHome == "" {+ sharedHome = platformDefaultHermesHome()+ }+ if sourceMustExist {+ if fi, err := os.Stat(sharedHome); err != nil || !fi.IsDir() {+ return fmt.Errorf("hermes profile home %q not found (create it with `hermes profile create`)", sharedHome)+ }+ }++ if err := os.MkdirAll(hermesHome, 0o700); err != nil {+ return fmt.Errorf("create hermes-home dir: %w", err)+ }+ // Tighten perms on reuse too — MkdirAll leaves an existing dir's mode alone,+ // and the derived config below can hold inline api_key secrets.+ if err := os.Chmod(hermesHome, 0o700); err != nil {+ return fmt.Errorf("chmod hermes-home dir: %w", err)+ }+ // Fresh, isolated per-task memories dir (idempotent — preserved across reuse+ // so the task/issue lifecycle keeps its own memory).+ if err := os.MkdirAll(filepath.Join(hermesHome, "memories"), 0o700); err != nil {+ return fmt.Errorf("create task memories dir: %w", err)+ }++ if err := mirrorSharedHermesHome(sharedHome, hermesHome, logger); err != nil {+ return fmt.Errorf("mirror shared hermes home: %w", err)+ }+ if err := writeDerivedHermesConfig(sharedHome, hermesHome, env, logger); err != nil {+ return fmt.Errorf("derive hermes config: %w", err)+ }+ if err := writeDerivedHermesEnv(sharedHome, hermesHome); err != nil {+ return fmt.Errorf("derive hermes .env: %w", err)+ }+ return writeHermesBoundSkills(hermesHome, workspaceSkills, logger)+}++// writeDerivedHermesEnv writes the task-local .env: the source home's .env+// contents (credentials/settings preserved) with any HERMES_HOME assignment+// removed, then a pinned HERMES_HOME pointing at the overlay appended last so it+// wins. Hermes loads <HERMES_HOME>/.env with override=True right after profile+// resolution, so without this an out-of-band HERMES_HOME= in the source .env+// would relocate the home past the overlay (dropping bound skills and memory+// isolation). We always write the file — even when the source has none — so the+// overlay .env "loads" and Hermes' project-.env fallback (override=True only when+// no user .env loaded) can't relocate the home either. Written 0600 via atomic+// replace since it can hold API-key secrets; reuse also repairs prior perms.+func writeDerivedHermesEnv(sharedHome, hermesHome string) error {+ dst := filepath.Join(hermesHome, ".env")++ var body []byte+ src, err := os.ReadFile(filepath.Join(sharedHome, ".env"))+ if err != nil {+ if !os.IsNotExist(err) {+ return fmt.Errorf("read shared .env: %w", err)+ }+ } else {+ body = stripDotenvAssignment(src, "HERMES_HOME")+ }++ var buf strings.Builder+ if len(body) > 0 {+ buf.Write(body)+ if body[len(body)-1] != '\n' {+ buf.WriteByte('\n')+ }+ }+ // Pin HERMES_HOME to the overlay. Single-quote the value so python-dotenv+ // treats it literally (no escaping / var expansion) — task home paths can+ // contain spaces or other characters under the workspaces root.+ fmt.Fprintf(&buf, "HERMES_HOME='%s'\n", hermesHome)++ return writeFileAtomic(dst, []byte(buf.String()), 0o600)+}++// stripDotenvAssignment drops every line of a .env file that assigns key,+// tolerating a leading `export ` and surrounding whitespace the way python-dotenv+// does. Other lines (including comments and blanks) are preserved verbatim.+func stripDotenvAssignment(content []byte, key string) []byte {+ lines := strings.Split(string(content), "\n")+ out := lines[:0]+ for _, line := range lines {+ if dotenvLineKey(line) == key {+ continue+ }+ out = append(out, line)+ }+ return []byte(strings.Join(out, "\n"))+}++// dotenvLineKey returns the variable name a .env line assigns, or "" for a+// comment/blank/non-assignment line.+func dotenvLineKey(line string) string {+ s := strings.TrimSpace(line)+ if s == "" || strings.HasPrefix(s, "#") {+ return ""+ }+ if rest := strings.TrimPrefix(s, "export"); rest != s && rest != "" &&+ (rest[0] == ' ' || rest[0] == '\t') {+ s = strings.TrimSpace(rest)+ }+ eq := strings.IndexByte(s, '=')+ if eq <= 0 {+ return ""+ }+ return strings.TrimSpace(s[:eq])+}++// mirrorSharedHermesHome symlinks every top-level entry of the shared ~/.hermes/+// into the per-task home except the overlay-owned entries, then reconciles the+// destination so entries removed from the shared home (or left over from a prior+// reuse) don't linger as readable stale state. Symlinks share state with the+// user's real home (auth/OAuth refreshes propagate, no credential copy lingers+// in task scratch). The shared home itself is never written — we only read it+// and create links pointing into it.+func mirrorSharedHermesHome(sharedHome, hermesHome string, logger *slog.Logger) error {+ entries, err := os.ReadDir(sharedHome)+ if err != nil {+ if os.IsNotExist(err) {+ // No shared home to mirror. The derived config + bound skills still+ // give Hermes a working home, so this is not fatal on its own.+ return reconcileMirroredEntries(hermesHome, nil)+ }+ return fmt.Errorf("read shared home: %w", err)+ }+ mirrored := make(map[string]struct{}, len(entries))+ for _, entry := range entries {+ name := entry.Name()+ if _, overridden := hermesOverriddenEntries[name]; overridden {+ continue+ }+ src := filepath.Join(sharedHome, name)+ dst := filepath.Join(hermesHome, name)+ if err := linkSharedHermesEntry(src, dst); err != nil {+ return fmt.Errorf("mirror %s: %w", name, err)+ }+ mirrored[name] = struct{}{}+ }+ return reconcileMirroredEntries(hermesHome, mirrored)+}++// reconcileMirroredEntries removes overlay entries that are neither overlay-owned+// nor currently mirrored from the shared home, so a shared entry deleted between+// runs (or a Windows copy-fallback left behind) doesn't survive as stale state.+func reconcileMirroredEntries(hermesHome string, mirrored map[string]struct{}) error {+ entries, err := os.ReadDir(hermesHome)+ if err != nil {+ return fmt.Errorf("read overlay home: %w", err)+ }+ for _, entry := range entries {+ name := entry.Name()+ if _, owned := hermesOverriddenEntries[name]; owned {+ continue+ }+ if _, keep := mirrored[name]; keep {+ continue+ }+ if err := os.RemoveAll(filepath.Join(hermesHome, name)); err != nil {+ return fmt.Errorf("reconcile stale %s: %w", name, err)+ }+ }+ return nil+}++// linkSharedHermesEntry symlinks dst → src, idempotent across Reuse: an existing+// link already pointing at src is left alone; anything else is removed and+// recreated so the overlay never drifts from the shared home. A dangling source+// (a broken symlink in the user's home) is skipped, not failed. Directories use+// createDirLink and files createFileLink so the Windows copy fallbacks match the+// entry kind.+func linkSharedHermesEntry(src, dst string) error {+ if fi, err := os.Lstat(dst); err == nil {+ if fi.Mode()&os.ModeSymlink != 0 {+ if target, err := os.Readlink(dst); err == nil && target == src {+ return nil+ }+ }+ if err := os.RemoveAll(dst); err != nil {+ return fmt.Errorf("remove stale %s: %w", dst, err)+ }+ }++ info, err := os.Stat(src) // follow the link to decide dir vs file+ if err != nil {+ if os.IsNotExist(err) {+ return nil // dangling source in the user's home — nothing to link+ }+ return fmt.Errorf("stat %s: %w", src, err)+ }+ if info.IsDir() {+ return createDirLink(src, dst)+ }+ return createFileLink(src, dst)+}++// writeDerivedHermesConfig writes the task-local config.yaml: the user's config+// with `skills.external_dirs` set to their existing external dirs plus the shared+// ~/.hermes/skills, all as absolute paths. When the user has no config we still+// write a minimal one so their global skills stay reachable via the external+// root. If the config can't be parsed we copy it verbatim so auth/model settings+// survive — the bound skills still load from the task-local skills/ dir, which is+// the point of the fix; only the user's global skills would be missing. The file+// is written 0600 (it can hold inline api_key secrets) via atomic replace, so+// reuse also repairs a prior file's permissions.+func writeDerivedHermesConfig(sharedHome, hermesHome string, env map[string]string, logger *slog.Logger) error {+ srcConfig := filepath.Join(sharedHome, "config.yaml")+ dstConfig := filepath.Join(hermesHome, "config.yaml")++ data, err := os.ReadFile(srcConfig)+ if err != nil {+ if !os.IsNotExist(err) {+ return fmt.Errorf("read shared config: %w", err)+ }+ doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{{Kind: yaml.MappingNode, Tag: "!!map"}}}+ if err := setHermesExternalDirs(doc, computeHermesExternalDirs(sharedHome, nil, env)); err != nil {+ return err+ }+ return marshalYAMLToFile(doc, dstConfig)+ }++ var doc yaml.Node+ if err := yaml.Unmarshal(data, &doc); err != nil {+ logger.Warn("execenv: hermes-home config parse failed; copying verbatim", "error", err)+ return writeFileAtomic(dstConfig, data, 0o600)+ }+ dirs := computeHermesExternalDirs(sharedHome, existingHermesExternalDirs(&doc), env)+ if err := setHermesExternalDirs(&doc, dirs); err != nil {+ logger.Warn("execenv: hermes-home set external_dirs failed; copying verbatim", "error", err)+ return writeFileAtomic(dstConfig, data, 0o600)+ }+ // Disable any host-configured external memory backend (memory.provider) so a+ // Supermemory/Hindsight/etc. bank isn't shared across managed tasks; the+ // built-in per-task memories/ dir is already isolated above.+ disableHermesMemoryProvider(&doc)+ return marshalYAMLToFile(&doc, dstConfig)+}++// disableHermesMemoryProvider forces skills-adjacent `memory.provider` to empty+// in the derived config. Hermes activates an external memory plugin only when+// memory.provider is a non-blank string (agent/agent_init.py), so "" is the+// explicit off switch. The built-in note/user-profile memory is unaffected — it+// writes to the isolated per-task memories/ dir.+func disableHermesMemoryProvider(doc *yaml.Node) {+ top := yamlDocumentRoot(doc)+ if top == nil {+ return+ }+ memory := yamlMapValue(top, "memory")+ if memory == nil || memory.Kind != yaml.MappingNode {+ memory = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}+ yamlSetMapValue(top, "memory", memory)+ }+ yamlSetMapValue(memory, "provider", &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: ""})+}++// computeHermesExternalDirs normalizes the user's existing external_dirs to+// absolute paths and appends the shared skills dir as a read-only external root.+// Variable/`~` expansion uses the sanitized effective env (the same map layered+// onto the Hermes child), falling back to the daemon process env — so a `${VAR}`+// configured on the agent resolves to what Hermes will actually see, and a var+// the daemon blocklists (e.g. HOME) resolves to the process value rather than+// the dropped custom one. Unknown variables are PRESERVED as `${VAR}` (matching+// Hermes/Python expandvars) rather than collapsed to empty, so a path meant to+// be resolved at runtime isn't silently rewritten. An entry still containing an+// unresolved `${` is left as-is (Hermes expands it later); otherwise relative+// paths resolve against the shared home, matching pre-redirect behavior. Order+// preserved; duplicates dropped.+func computeHermesExternalDirs(sharedHome string, existing []string, env map[string]string) []string {+ expand := func(s string) string {+ return os.Expand(s, func(k string) string {+ if v, ok := env[k]; ok {+ return v+ }+ if v, ok := os.LookupEnv(k); ok {+ return v+ }+ return "${" + k + "}" // preserve unknown vars for runtime expansion+ })+ }++ out := make([]string, 0, len(existing)+1)+ seen := make(map[string]struct{}, len(existing)+1)+ add := func(p string) {+ if p == "" {+ return+ }+ if _, ok := seen[p]; ok {+ return+ }+ seen[p] = struct{}{}+ out = append(out, p)+ }+ for _, raw := range existing {+ entry := strings.TrimSpace(raw)+ if entry == "" {+ continue+ }+ entry = strings.TrimSpace(expand(entry))+ if entry == "" {+ continue+ }+ // An unresolved ${VAR} remains (unknown var preserved above) — leave the+ // entry untouched so Hermes expands and resolves it at runtime; we can't+ // safely decide abs-vs-relative here.+ if strings.Contains(entry, "${") {+ add(entry)+ continue+ }+ if entry == "~" || strings.HasPrefix(entry, "~/") {+ if home, err := os.UserHomeDir(); err == nil {+ entry = filepath.Join(home, strings.TrimPrefix(entry, "~"))+ }+ }+ if !filepath.IsAbs(entry) {+ entry = filepath.Join(sharedHome, entry)+ }+ add(filepath.Clean(entry))+ }+ // The shared skills dir, referenced (not copied) so the user's global and+ // builtin skills stay visible. It differs from the task-local skills dir,+ // so Hermes won't fold it into the local root, and being last it yields to+ // the bound skills on a name collision.+ add(filepath.Join(sharedHome, "skills"))+ return out+}++// writeHermesBoundSkills rebuilds the task-local skills/ dir from scratch so a+// skill removed since the last run can't linger, then writes only the+// Multica-bound skills. They keep their natural slug (no user skills share this+// dir) and therefore take precedence over any same-named external skill.+func writeHermesBoundSkills(hermesHome string, workspaceSkills []SkillContextForEnv, logger *slog.Logger) error {+ skillsDir := filepath.Join(hermesHome, "skills")+ if err := os.RemoveAll(skillsDir); err != nil {+ return fmt.Errorf("clear hermes skills dir: %w", err)+ }+ if len(workspaceSkills) == 0 {+ // Defensive: callers gate on a non-empty set, but stay correct if that+ // ever changes — an empty local dir just means the external root is the+ // only source, matching un-redirected behavior.+ return os.MkdirAll(skillsDir, 0o700)+ }+ // Skills live under env.RootDir/hermes-home, which the GC loop (cloud) or+ // env teardown (local_directory) wipes wholesale — no sidecar manifest.+ return writeSkillFiles(skillsDir, workspaceSkills, nil)+}++// existingHermesExternalDirs reads the raw skills.external_dirs entries from a+// parsed config document, accepting either a single string or a list (both of+// which Hermes accepts). Returns nil when absent.+func existingHermesExternalDirs(doc *yaml.Node) []string {+ top := yamlDocumentRoot(doc)+ if top == nil {+ return nil+ }+ skills := yamlMapValue(top, "skills")+ ed := yamlMapValue(skills, "external_dirs")+ if ed == nil {+ return nil+ }+ if ed.Kind == yaml.ScalarNode {+ return []string{ed.Value}+ }+ if ed.Kind != yaml.SequenceNode {+ return nil+ }+ out := make([]string, 0, len(ed.Content))+ for _, c := range ed.Content {+ if c.Kind == yaml.ScalarNode {+ out = append(out, c.Value)+ }+ }+ return out+}++// setHermesExternalDirs sets skills.external_dirs on the config document,+// creating the skills mapping if needed and preserving every other setting.+func setHermesExternalDirs(doc *yaml.Node, dirs []string) error {+ top := yamlDocumentRoot(doc)+ if top == nil {+ return fmt.Errorf("hermes config: unexpected root node")+ }+ skills := yamlMapValue(top, "skills")+ if skills == nil || skills.Kind != yaml.MappingNode {+ skills = &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}+ yamlSetMapValue(top, "skills", skills)+ }+ yamlSetMapValue(skills, "external_dirs", yamlStringSeq(dirs))+ return nil+}++// yamlDocumentRoot returns the top-level mapping node of a parsed document, or+// nil if the shape isn't a mapping.+func yamlDocumentRoot(doc *yaml.Node) *yaml.Node {+ if doc == nil {+ return nil+ }+ node := doc+ if node.Kind == yaml.DocumentNode {+ if len(node.Content) == 0 {+ return nil+ }+ node = node.Content[0]+ }+ if node.Kind != yaml.MappingNode {+ return nil+ }+ return node+}++// yamlMapValue returns the value node for key in a mapping node, or nil.+func yamlMapValue(m *yaml.Node, key string) *yaml.Node {+ if m == nil || m.Kind != yaml.MappingNode {+ return nil+ }+ for i := 0; i+1 < len(m.Content); i += 2 {+ if m.Content[i].Value == key {+ return m.Content[i+1]+ }+ }+ return nil+}++// yamlSetMapValue sets key to val in a mapping node, replacing in place if the+// key exists or appending otherwise.+func yamlSetMapValue(m *yaml.Node, key string, val *yaml.Node) {+ for i := 0; i+1 < len(m.Content); i += 2 {+ if m.Content[i].Value == key {+ m.Content[i+1] = val+ return+ }+ }+ m.Content = append(m.Content,+ &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: key},+ val,+ )+}++// yamlStringSeq builds a YAML sequence node of string scalars.+func yamlStringSeq(vals []string) *yaml.Node {+ seq := &yaml.Node{Kind: yaml.SequenceNode, Tag: "!!seq"}+ for _, v := range vals {+ seq.Content = append(seq.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: v})+ }+ return seq+}++// marshalYAMLToFile renders a YAML node to dst as a 0600 file (it can hold+// inline secrets) via atomic replace.+func marshalYAMLToFile(doc *yaml.Node, dst string) error {+ out, err := yaml.Marshal(doc)+ if err != nil {+ return fmt.Errorf("marshal hermes config: %w", err)+ }+ return writeFileAtomic(dst, out, 0o600)+}++// writeFileAtomic writes data to a temp file in the destination directory with+// the given perms, then renames it over dst — so readers never see a partial+// file and a prior file's looser permissions are replaced.+func writeFileAtomic(dst string, data []byte, perm os.FileMode) error {+ dir := filepath.Dir(dst)+ tmp, err := os.CreateTemp(dir, ".hermes-tmp-*")+ if err != nil {+ return fmt.Errorf("create temp for %s: %w", dst, err)+ }+ tmpName := tmp.Name()+ defer os.Remove(tmpName) // no-op once renamed+ if _, err := tmp.Write(data); err != nil {+ tmp.Close()+ return fmt.Errorf("write temp for %s: %w", dst, err)+ }+ if err := tmp.Chmod(perm); err != nil {+ tmp.Close()+ return fmt.Errorf("chmod temp for %s: %w", dst, err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("close temp for %s: %w", dst, err)+ }+ if err := os.Rename(tmpName, dst); err != nil {+ return fmt.Errorf("rename temp to %s: %w", dst, err)+ }+ return nil+}diff --git a/server/internal/daemon/execenv/hermes_home_test.go b/server/internal/daemon/execenv/hermes_home_test.gonew file mode 100644index 0000000000..53c36145b2--- /dev/null+++ b/server/internal/daemon/execenv/hermes_home_test.go@@ -0,0 +1,733 @@+package execenv++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "gopkg.in/yaml.v3"+)++// hermesExternalDirs parses skills.external_dirs out of a derived config.yaml.+func hermesExternalDirs(t *testing.T, configPath string) []string {+ t.Helper()+ data, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatalf("read derived config: %v", err)+ }+ var parsed struct {+ Skills struct {+ ExternalDirs []string `yaml:"external_dirs"`+ } `yaml:"skills"`+ }+ if err := yaml.Unmarshal(data, &parsed); err != nil {+ t.Fatalf("parse derived config: %v\n%s", err, data)+ }+ return parsed.Skills.ExternalDirs+}++// hermesMemoryProvider returns the memory.provider value in a derived config,+// and whether the key is present.+func hermesMemoryProvider(t *testing.T, configPath string) (string, bool) {+ t.Helper()+ data, err := os.ReadFile(configPath)+ if err != nil {+ t.Fatalf("read derived config: %v", err)+ }+ var parsed struct {+ Memory struct {+ Provider *string `yaml:"provider"`+ } `yaml:"memory"`+ }+ if err := yaml.Unmarshal(data, &parsed); err != nil {+ t.Fatalf("parse derived config: %v", err)+ }+ if parsed.Memory.Provider == nil {+ return "", false+ }+ return *parsed.Memory.Provider, true+}++// TestPrepareHermesHomeOverlay verifies the compatibility overlay: shared state+// is mirrored via symlink, the derived config references the user's real skills+// as an external root, and only the bound skill lands in the task-local skills/+// dir (the user's global skills are referenced, not copied).+func TestPrepareHermesHomeOverlay(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "auth.json"), `{"token":"secret"}`)+ mustWrite(t, filepath.Join(sharedHome, ".env"), "API_KEY=abc")+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"), "model: hermes-4\n")+ mustWrite(t, filepath.Join(sharedHome, "plugins", "custom-provider", "plugin.py"), "# provider plugin")+ mustWrite(t, filepath.Join(sharedHome, "oauth_state.json"), `{"nous":"tok"}`)+ mustWrite(t, filepath.Join(sharedHome, "skills", "personal-notes", "SKILL.md"), "My personal notes skill.")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "Help review code."}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ for _, name := range []string{"auth.json", "plugins", "oauth_state.json"} {+ fi, err := os.Lstat(filepath.Join(hermesHome, name))+ if err != nil {+ t.Fatalf("%s not mirrored into overlay: %v", name, err)+ }+ if fi.Mode()&os.ModeSymlink == 0 {+ t.Errorf("%s should be a symlink into the shared home", name)+ }+ }++ // .env is overlay-owned/derived (not symlinked): it preserves the source's+ // credentials but pins HERMES_HOME to the overlay so Hermes' override=True+ // dotenv load can't relocate the home past it.+ envPath := filepath.Join(hermesHome, ".env")+ if fi, err := os.Lstat(envPath); err != nil {+ t.Fatalf(".env missing from overlay: %v", err)+ } else if fi.Mode()&os.ModeSymlink != 0 {+ t.Error(".env should be a derived copy, not a symlink into the shared home")+ }+ if data, _ := os.ReadFile(envPath); !strings.Contains(string(data), "API_KEY=abc") {+ t.Error("derived .env dropped the source credentials")+ } else if !strings.Contains(string(data), "HERMES_HOME='"+hermesHome+"'") {+ t.Errorf("derived .env must pin HERMES_HOME to the overlay, got:\n%s", data)+ }++ cfgPath := filepath.Join(hermesHome, "config.yaml")+ if fi, err := os.Lstat(cfgPath); err != nil {+ t.Fatalf("config.yaml missing: %v", err)+ } else if fi.Mode()&os.ModeSymlink != 0 {+ t.Error("config.yaml should be a derived copy, not a symlink")+ }+ if data, _ := os.ReadFile(cfgPath); !strings.Contains(string(data), "hermes-4") {+ t.Error("derived config dropped the user's model setting")+ }+ wantExternal := filepath.Join(sharedHome, "skills")+ if got := hermesExternalDirs(t, cfgPath); len(got) != 1 || got[0] != wantExternal {+ t.Errorf("external_dirs = %v, want [%s]", got, wantExternal)+ }++ if body, err := os.ReadFile(filepath.Join(hermesHome, "skills", "review-helper", "SKILL.md")); err != nil {+ t.Fatalf("bound skill not written: %v", err)+ } else if !strings.Contains(string(body), "Help review code.") {+ t.Error("bound SKILL.md missing content")+ }+ if _, err := os.Stat(filepath.Join(hermesHome, "skills", "personal-notes")); !os.IsNotExist(err) {+ t.Error("user global skill should be referenced via external_dirs, not copied into the task-local skills/")+ }+}++// TestHermesDisablesExternalMemoryProvider is the regression for the shared+// memory-backend blocker: a host-configured memory.provider must be neutralized+// in the derived config so managed tasks don't share an external memory bank.+func TestHermesDisablesExternalMemoryProvider(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"),+ "memory:\n provider: supermemory\n memory_enabled: true\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ got, ok := hermesMemoryProvider(t, filepath.Join(hermesHome, "config.yaml"))+ if !ok {+ t.Fatal("memory.provider should be present and explicitly disabled")+ }+ if got != "" {+ t.Errorf("memory.provider = %q, want \"\" (external backend disabled)", got)+ }+ if data, _ := os.ReadFile(filepath.Join(hermesHome, "config.yaml")); !strings.Contains(string(data), "memory_enabled: true") {+ t.Error("built-in memory settings should be preserved")+ }+}++// TestHermesDerivedConfigRebasesRelativeExternalDirs is the regression for the+// silent-repoint bug: relative external_dirs must be rewritten to absolute paths+// anchored at the shared home, absolute entries left intact, and the real skills+// dir appended.+func TestHermesDerivedConfigRebasesRelativeExternalDirs(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"),+ "model: hermes-4\nskills:\n external_dirs:\n - team-skills\n - /opt/shared/skills\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ got := hermesExternalDirs(t, filepath.Join(hermesHome, "config.yaml"))+ want := []string{+ filepath.Join(sharedHome, "team-skills"),+ "/opt/shared/skills",+ filepath.Join(sharedHome, "skills"),+ }+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Errorf("external_dirs =\n%v\nwant\n%v", got, want)+ }+}++// TestHermesExternalDirsExpandsSanitizedEnv verifies a ${VAR} present in the+// sanitized effective env expands, while an UNKNOWN var is preserved verbatim+// (Hermes/Python expandvars semantics) instead of collapsing to empty and being+// silently rewritten to an absolute path.+func TestHermesExternalDirsExpandsSanitizedEnv(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"),+ "skills:\n external_dirs:\n - ${TEAM_SKILLS}/reviews\n - ${MYSTERY_VAR}/x\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ env := map[string]string{"TEAM_SKILLS": "/srv/team"} // MYSTERY_VAR set nowhere+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, env, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ got := hermesExternalDirs(t, filepath.Join(hermesHome, "config.yaml"))+ want := []string{+ "/srv/team/reviews", // known var expanded+ "${MYSTERY_VAR}/x", // unknown var preserved verbatim, NOT absolutized+ filepath.Join(sharedHome, "skills"),+ }+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Errorf("external_dirs =\n%v\nwant\n%v", got, want)+ }+}++// TestHermesBoundSkillKeepsNaturalSlug asserts a bound skill sharing a name with+// a user global skill keeps its natural slug (so Hermes resolves the bound+// version, home skills first) and leaves the user's shared copy untouched.+func TestHermesBoundSkillKeepsNaturalSlug(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ userSkill := filepath.Join(sharedHome, "skills", "review-helper", "SKILL.md")+ mustWrite(t, userSkill, "USER VERSION")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "WORKSPACE VERSION"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ body, err := os.ReadFile(filepath.Join(hermesHome, "skills", "review-helper", "SKILL.md"))+ if err != nil {+ t.Fatalf("read bound skill: %v", err)+ }+ if strings.Contains(string(body), "USER VERSION") || !strings.Contains(string(body), "WORKSPACE VERSION") {+ t.Errorf("bound skill should keep natural slug with its own content, got: %q", body)+ }+ if data, _ := os.ReadFile(userSkill); string(data) != "USER VERSION" {+ t.Errorf("user's shared skill was modified: %q", data)+ }+}++// TestHermesOverlayIsolatesMemories asserts the host memory dir isn't reachable+// from the task, task writes don't touch the host, and the task-local dir+// survives reuse.+func TestHermesOverlayIsolatesMemories(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"), "model: hermes-4\n")+ mustWrite(t, filepath.Join(sharedHome, "memories", "MEMORY.md"), "HOST MEMORY — must not leak")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ memDir := filepath.Join(hermesHome, "memories")+ if fi, err := os.Lstat(memDir); err != nil {+ t.Fatalf("task memories dir missing: %v", err)+ } else if fi.Mode()&os.ModeSymlink != 0 {+ t.Fatal("task memories/ must be a real dir, not a symlink into the host home")+ }+ if _, err := os.Stat(filepath.Join(memDir, "MEMORY.md")); !os.IsNotExist(err) {+ t.Error("host MEMORY.md must not be visible in the task")+ }++ mustWrite(t, filepath.Join(memDir, "MEMORY.md"), "TASK MEMORY")+ if data, _ := os.ReadFile(filepath.Join(sharedHome, "memories", "MEMORY.md")); string(data) != "HOST MEMORY — must not leak" {+ t.Errorf("host memory was modified through the overlay: %q", data)+ }+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome (reuse) failed: %v", err)+ }+ if data, _ := os.ReadFile(filepath.Join(memDir, "MEMORY.md")); string(data) != "TASK MEMORY" {+ t.Errorf("reuse should preserve task-local memory, got: %q", data)+ }+}++// TestHermesOverlayPermissions asserts the task home is 0700 and the derived+// config (which can hold inline api_key secrets) is 0600.+func TestHermesOverlayPermissions(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"), "model: hermes-4\napi_key: sk-secret\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ if fi, err := os.Stat(hermesHome); err != nil {+ t.Fatalf("stat home: %v", err)+ } else if fi.Mode().Perm() != 0o700 {+ t.Errorf("task home perms = %o, want 0700", fi.Mode().Perm())+ }+ if fi, err := os.Stat(filepath.Join(hermesHome, "config.yaml")); err != nil {+ t.Fatalf("stat config: %v", err)+ } else if fi.Mode().Perm() != 0o600 {+ t.Errorf("derived config perms = %o, want 0600", fi.Mode().Perm())+ }+}++// TestHermesOverlayReconcilesDeletedSharedEntry asserts a top-level entry+// removed from the shared home is dropped from the overlay on rebuild.+func TestHermesOverlayReconcilesDeletedSharedEntry(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"), "model: hermes-4\n")+ mustWrite(t, filepath.Join(sharedHome, "plugins", "p", "plugin.py"), "# plugin")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }+ if _, err := os.Lstat(filepath.Join(hermesHome, "plugins")); err != nil {+ t.Fatalf("plugins not mirrored: %v", err)+ }+ if err := os.RemoveAll(filepath.Join(sharedHome, "plugins")); err != nil {+ t.Fatalf("remove shared plugins: %v", err)+ }+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome (rebuild) failed: %v", err)+ }+ if _, err := os.Lstat(filepath.Join(hermesHome, "plugins")); !os.IsNotExist(err) {+ t.Error("stale mirrored plugins should be reconciled away after deletion in the shared home")+ }+}++// TestPrepareHermesHomeFailsClosed asserts prepareHermesHome returns an error+// when required overlay state can't be built (here an unreadable shared config).+func TestPrepareHermesHomeFailsClosed(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ if err := os.MkdirAll(filepath.Join(sharedHome, "config.yaml"), 0o755); err != nil {+ t.Fatalf("mkdir config.yaml dir: %v", err)+ }+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err == nil {+ t.Fatal("expected prepareHermesHome to fail closed on an unreadable shared config")+ }+}++// TestResolveHermesProfile exercises the one resolver contract against the+// behaviors the review requires it to match Hermes on: sticky selection, an+// already-profile-scoped home, `-p default`/`-p <sibling>` re-rooting, and native+// failure on reserved/invalid/empty names. Temp dirs stand in for custom Hermes+// roots (they are never under the host's platform-default home, so root+// derivation takes the deterministic custom/profile branch).+func TestResolveHermesProfile(t *testing.T) {+ t.Parallel()++ t.Run("no profile resolves to the base home", func(t *testing.T) {+ t.Parallel()+ base := t.TempDir()+ res := ResolveHermesProfile(base, "", false, false)+ if res.Err != nil || res.SourceHome != base || res.MustExist {+ t.Fatalf("got %+v, want SourceHome=%q MustExist=false Err=nil", res, base)+ }+ })++ // The review's blocker 1: a sticky active_profile must be SELECTED as the+ // overlay source, not merely blocked from bypassing.+ t.Run("root + sticky named profile selects the profile as source", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ mustWrite(t, filepath.Join(root, "active_profile"), "coder\n")+ res := ResolveHermesProfile(root, "", false, false)+ want := filepath.Join(root, "profiles", "coder")+ if res.Err != nil || res.SourceHome != want || !res.MustExist {+ t.Fatalf("sticky: got %+v, want SourceHome=%q MustExist=true", res, want)+ }+ })++ t.Run("sticky default is ignored", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ mustWrite(t, filepath.Join(root, "active_profile"), "default\n")+ res := ResolveHermesProfile(root, "", false, false)+ if res.Err != nil || res.SourceHome != root || res.MustExist {+ t.Fatalf("sticky default: got %+v, want SourceHome=%q MustExist=false", res, root)+ }+ })++ t.Run("already-profile-scoped home with no flag is trusted", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ scoped := filepath.Join(root, "profiles", "coder")+ // A sticky at the root must NOT override an explicit profile-scoped home.+ mustWrite(t, filepath.Join(root, "active_profile"), "research\n")+ res := ResolveHermesProfile(scoped, "", false, false)+ if res.Err != nil || res.SourceHome != scoped || !res.MustExist {+ t.Fatalf("profile-scoped: got %+v, want SourceHome=%q MustExist=true", res, scoped)+ }+ })++ t.Run("-p default from a profile-scoped home re-roots to the root", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ scoped := filepath.Join(root, "profiles", "coder")+ res := ResolveHermesProfile(scoped, "default", true, false)+ if res.Err != nil || res.SourceHome != root || res.MustExist {+ t.Fatalf("-p default: got %+v, want SourceHome=%q MustExist=false", res, root)+ }+ })++ t.Run("-p sibling from a profile-scoped home is a sibling, not nested", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ scoped := filepath.Join(root, "profiles", "coder")+ res := ResolveHermesProfile(scoped, "research", true, false)+ want := filepath.Join(root, "profiles", "research")+ if res.Err != nil || res.SourceHome != want || !res.MustExist {+ t.Fatalf("-p sibling: got %+v, want SourceHome=%q MustExist=true", res, want)+ }+ })++ t.Run("explicit named profile resolves under the root", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ res := ResolveHermesProfile(root, "research", true, false)+ want := filepath.Join(root, "profiles", "research")+ if res.Err != nil || res.SourceHome != want || !res.MustExist {+ t.Fatalf("named: got %+v, want SourceHome=%q MustExist=true", res, want)+ }+ })++ t.Run("reserved names fail closed", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ for _, name := range []string{"hermes", "test", "tmp", "root", "sudo"} {+ if res := ResolveHermesProfile(root, name, true, false); res.Err == nil {+ t.Errorf("reserved %q: expected Err, got SourceHome=%q", name, res.SourceHome)+ }+ }+ })++ t.Run("empty inline value fails closed", func(t *testing.T) {+ t.Parallel()+ root := t.TempDir()+ if res := ResolveHermesProfile(root, "", true, true); res.Err == nil {+ t.Error("empty inline --profile= must fail closed, not fall back to default")+ }+ })++ t.Run("empty inputs resolve to a platform default", func(t *testing.T) {+ t.Parallel()+ if res := ResolveHermesProfile("", "", false, false); res.SourceHome == "" {+ t.Error("empty inputs should resolve to a platform default, not empty")+ }+ })+}++// TestHermesExternalDirsExpandsAgainstSelectedProfileHome is the review's blocker+// 3: a ${HERMES_HOME} in a selected profile's skills.external_dirs must expand+// against the SELECTED profile home (what native Hermes sees after applying the+// profile override before loading config.yaml), not the pre-resolution/root home+// or the task overlay. The daemon sets the effective env's HERMES_HOME to the+// resolved source home for exactly this reason.+func TestHermesExternalDirsExpandsAgainstSelectedProfileHome(t *testing.T) {+ t.Parallel()+ profileHome := t.TempDir() // stands in for <root>/profiles/coder+ mustWrite(t, filepath.Join(profileHome, "config.yaml"),+ "skills:\n external_dirs:\n - ${HERMES_HOME}/profile-skills\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ env := map[string]string{"HERMES_HOME": profileHome} // as the daemon sets it+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, profileHome, true, skills, env, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ got := hermesExternalDirs(t, filepath.Join(hermesHome, "config.yaml"))+ want := []string{+ filepath.Join(profileHome, "profile-skills"),+ filepath.Join(profileHome, "skills"),+ }+ if strings.Join(got, "\n") != strings.Join(want, "\n") {+ t.Errorf("external_dirs =\n%v\nwant\n%v", got, want)+ }+}++// TestHermesOverlayEnvPinsHomeAfterDotenvOverride is the review's blocker 1: a+// source .env that sets HERMES_HOME must not relocate the home past the overlay.+// Hermes loads <HERMES_HOME>/.env with override=True right after profile+// resolution; we replay that last-wins/override order over the derived overlay+// .env and prove the effective HERMES_HOME stays the overlay — so bound-skill+// discovery and task-local memory keep using it — while source creds survive.+func TestHermesOverlayEnvPinsHomeAfterDotenvOverride(t *testing.T) {+ t.Parallel()+ sourceHome := t.TempDir()+ mustWrite(t, filepath.Join(sourceHome, ".env"),+ "ANTHROPIC_API_KEY=sk-source\nexport HERMES_HOME=/home/u/.hermes/profiles/coder\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sourceHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }++ envPath := filepath.Join(hermesHome, ".env")+ if fi, err := os.Stat(envPath); err != nil {+ t.Fatalf(".env missing: %v", err)+ } else if perm := fi.Mode().Perm(); perm != 0o600 {+ t.Errorf(".env perms = %o, want 600 (holds credentials)", perm)+ }++ env := applyDotenvOverride(t, envPath)+ if env["HERMES_HOME"] != hermesHome {+ t.Errorf("after override=True dotenv load HERMES_HOME = %q, want the overlay %q", env["HERMES_HOME"], hermesHome)+ }+ if env["ANTHROPIC_API_KEY"] != "sk-source" {+ t.Errorf("source credential dropped: ANTHROPIC_API_KEY = %q", env["ANTHROPIC_API_KEY"])+ }+ // HERMES_HOME pinned to the overlay ⇒ skill discovery and memory use the+ // overlay's own dirs.+ if _, err := os.Stat(filepath.Join(hermesHome, "skills", "review-helper", "SKILL.md")); err != nil {+ t.Errorf("bound skill not in overlay skills dir: %v", err)+ }+ if fi, err := os.Stat(filepath.Join(hermesHome, "memories")); err != nil || !fi.IsDir() {+ t.Errorf("overlay memories dir missing: %v", err)+ }+}++// TestHermesOverlayEnvCreatedWhenSourceHasNone ensures a minimal overlay .env is+// written even when the source has none, so Hermes' project-.env fallback (loaded+// with override=True only when no user .env loaded) can't relocate the home.+func TestHermesOverlayEnvCreatedWhenSourceHasNone(t *testing.T) {+ t.Parallel()+ sourceHome := t.TempDir() // no .env present+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sourceHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }+ env := applyDotenvOverride(t, filepath.Join(hermesHome, ".env"))+ if env["HERMES_HOME"] != hermesHome {+ t.Errorf("overlay .env must exist and pin HERMES_HOME even with no source .env; got %q", env["HERMES_HOME"])+ }+}++// applyDotenvOverride replays python-dotenv's single-file override=True load over+// a .env: KEY=VALUE lines in order, last assignment wins, surrounding quotes and+// a leading `export` stripped. It mirrors how Hermes loads <HERMES_HOME>/.env.+func applyDotenvOverride(t *testing.T, path string) map[string]string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read overlay .env: %v", err)+ }+ env := map[string]string{}+ for _, line := range strings.Split(string(data), "\n") {+ s := strings.TrimSpace(line)+ if s == "" || strings.HasPrefix(s, "#") {+ continue+ }+ if rest := strings.TrimPrefix(s, "export"); rest != s && rest != "" && (rest[0] == ' ' || rest[0] == '\t') {+ s = strings.TrimSpace(rest)+ }+ eq := strings.IndexByte(s, '=')+ if eq <= 0 {+ continue+ }+ key := strings.TrimSpace(s[:eq])+ val := strings.TrimSpace(s[eq+1:])+ if len(val) >= 2 && (val[0] == '\'' || val[0] == '"') && val[len(val)-1] == val[0] {+ val = val[1 : len(val)-1]+ }+ env[key] = val // last wins (override=True)+ }+ return env+}++// TestHermesRootFromHomeResolvesSymlinks is the review's blocker 2: a HERMES_HOME+// symlinked into <native>/profiles/<x> must root at native (so -p default+// re-roots to native and -p <sibling> is a native sibling), which requires+// resolving symlinks for the containment decision — lexical containment alone+// would treat the symlink path as its own root.+func TestHermesRootFromHomeResolvesSymlinks(t *testing.T) {+ t.Parallel()+ native := t.TempDir()+ coder := filepath.Join(native, "profiles", "coder")+ if err := os.MkdirAll(coder, 0o755); err != nil {+ t.Fatal(err)+ }+ link := filepath.Join(t.TempDir(), "coder-home")+ if err := os.Symlink(coder, link); err != nil {+ t.Skipf("symlink unsupported here: %v", err)+ }++ root := hermesRootFromHomeFor(link, native)+ if root != native {+ t.Fatalf("symlinked profile home: root = %q, want native %q", root, native)+ }+ if home, _, err := hermesProfileDir(root, "default"); err != nil || home != native {+ t.Fatalf("-p default: home=%q err=%v, want %q", home, err, native)+ }+ sibling := filepath.Join(native, "profiles", "research")+ if home, _, err := hermesProfileDir(root, "research"); err != nil || home != sibling {+ t.Fatalf("-p sibling: home=%q err=%v, want %q", home, err, sibling)+ }+}++// TestPlatformDefaultHermesHome covers the Windows branch off a Windows host,+// including the LOCALAPPDATA-missing fallback to %USERPROFILE%\AppData\Local.+func TestPlatformDefaultHermesHome(t *testing.T) {+ t.Parallel()+ la := filepath.Join(string(filepath.Separator)+"Users", "me", "AppData", "Local")+ home := filepath.Join(string(filepath.Separator)+"home", "me")++ if got, want := platformDefaultHermesHomeFor("windows", la, home), filepath.Join(la, "hermes"); got != want {+ t.Errorf("windows: got %q, want %q", got, want)+ }+ // No LOCALAPPDATA → %USERPROFILE%\AppData\Local\hermes, matching Hermes.+ if got, want := platformDefaultHermesHomeFor("windows", "", home), filepath.Join(home, "AppData", "Local", "hermes"); got != want {+ t.Errorf("windows no LOCALAPPDATA: got %q, want %q", got, want)+ }+ if got, want := platformDefaultHermesHomeFor("linux", la, home), filepath.Join(home, ".hermes"); got != want {+ t.Errorf("linux: got %q, want %q", got, want)+ }+}++// TestHermesOverlayDoesNotMirrorStickyProfile is the regression for the sticky+// active_profile bypass: active_profile and profiles/ from the shared home must+// NOT be mirrored into the overlay, or Hermes would follow the sticky profile at+// startup and redirect HERMES_HOME past the overlay.+func TestHermesOverlayDoesNotMirrorStickyProfile(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"), "model: hermes-4\n")+ mustWrite(t, filepath.Join(sharedHome, "active_profile"), "coder")+ mustWrite(t, filepath.Join(sharedHome, "profiles", "coder", "config.yaml"), "model: coder\n")++ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, testLogger()); err != nil {+ t.Fatalf("prepareHermesHome failed: %v", err)+ }+ for _, name := range []string{"active_profile", "profiles"} {+ if _, err := os.Lstat(filepath.Join(hermesHome, name)); !os.IsNotExist(err) {+ t.Errorf("%s must not be mirrored into the overlay (sticky-profile bypass)", name)+ }+ }+}++// TestPrepareHermesHomeFailsOnMissingNamedProfile asserts an explicitly named+// profile whose home doesn't exist fails closed rather than silently seeding+// from an empty dir (which would drop the user's auth/config), matching Hermes'+// own sys.exit(1).+func TestPrepareHermesHomeFailsOnMissingNamedProfile(t *testing.T) {+ t.Parallel()+ base := t.TempDir()+ missingProfileHome := filepath.Join(base, "profiles", "does-not-exist")+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}+ if err := prepareHermesHome(hermesHome, missingProfileHome, true, skills, nil, testLogger()); err == nil {+ t.Fatal("expected a missing named profile home to fail closed")+ }+}++// TestPrepareHermesNoSkillsLeavesHomeUnset is the regression for the review's+// top blocker: a Hermes task with no bound skills must NOT get a redirected+// HERMES_HOME.+func TestPrepareHermesNoSkillsLeavesHomeUnset(t *testing.T) {+ t.Parallel()+ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-hermes-noskill",+ TaskID: "aaaa1111-2222-3333-4444-555566667777",+ Provider: "hermes",+ Task: TaskContextForEnv{IssueID: "no-skill"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ if env.HermesHome != "" {+ t.Errorf("skill-less Hermes task must not redirect HERMES_HOME, got %q", env.HermesHome)+ }+ if _, err := os.Stat(filepath.Join(env.RootDir, "hermes-home")); !os.IsNotExist(err) {+ t.Error("no hermes-home overlay should be created for a skill-less task")+ }+}++// TestReuseHermesTearsDownWhenSkillsRemoved covers the resume path: a task that+// had a skill and lost its last one must drop the redirect and remove the+// overlay.+func TestReuseHermesTearsDownWhenSkillsRemoved(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ mustWrite(t, filepath.Join(sharedHome, "config.yaml"), "model: hermes-4\n")++ withSkill := TaskContextForEnv{+ IssueID: "hermes-resume",+ AgentSkills: []SkillContextForEnv{{Name: "Review Helper", Content: "Help review."}},+ }+ env, err := Prepare(PrepareParams{+ WorkspacesRoot: t.TempDir(),+ WorkspaceID: "ws-hermes-resume",+ TaskID: "bbbb1111-2222-3333-4444-555566667777",+ Provider: "hermes",+ HermesSourceHome: sharedHome,+ Task: withSkill,+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ if env.HermesHome == "" {+ t.Fatal("expected HERMES_HOME redirect for a task with a bound skill")+ }+ overlayDir := filepath.Join(env.RootDir, "hermes-home")++ if reused := Reuse(ReuseParams{WorkDir: env.WorkDir, Provider: "hermes", HermesSourceHome: sharedHome, Task: withSkill}, testLogger()); reused == nil {+ t.Fatal("Reuse with skill returned nil")+ } else if reused.HermesHome == "" {+ t.Error("resume with a bound skill should keep the redirect")+ }++ noSkill := TaskContextForEnv{IssueID: "hermes-resume"}+ reused := Reuse(ReuseParams{WorkDir: env.WorkDir, Provider: "hermes", HermesSourceHome: sharedHome, Task: noSkill}, testLogger())+ if reused == nil {+ t.Fatal("Reuse without skill returned nil")+ }+ if reused.HermesHome != "" {+ t.Errorf("removing the last skill should clear HERMES_HOME, got %q", reused.HermesHome)+ }+ if _, err := os.Stat(overlayDir); !os.IsNotExist(err) {+ t.Error("stale hermes-home overlay should be removed on teardown")+ }+}++func mustWrite(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ t.Fatalf("mkdir for %s: %v", path, err)+ }+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}diff --git a/server/internal/daemon/execenv/runtime_config.go b/server/internal/daemon/execenv/runtime_config.goindex 294542c32b..1416d2d8da 100644--- a/server/internal/daemon/execenv/runtime_config.go+++ b/server/internal/daemon/execenv/runtime_config.go@@ -161,7 +161,7 @@ func formatProjectResource(r ProjectResourceForEnv) string {// For Copilot: writes {workDir}/AGENTS.md (skills discovered natively from .github/skills/)// For OpenCode: writes {workDir}/AGENTS.md (skills discovered natively from .opencode/skills/)// For OpenClaw: writes {workDir}/AGENTS.md (skills discovered natively from {workDir}/skills/ via per-task openclaw-config.json that pins agents.defaults.workspace)-// For Hermes: writes {workDir}/AGENTS.md (skills fall back to .agent_context/skills/; AGENTS.md points there)+// For Hermes: writes {workDir}/AGENTS.md (skills discovered natively from a per-task HERMES_HOME/skills seeded by the daemon; see hermes_home.go)// For Pi: writes {workDir}/AGENTS.md (skills discovered natively from .pi/skills/)// For Cursor: writes {workDir}/AGENTS.md (skills discovered natively from .cursor/skills/)// For Kimi: writes {workDir}/AGENTS.md (Kimi Code CLI reads AGENTS.md natively; skills auto-discovered from project skills dirs)diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.goindex ce9dddc171..5a27099717 100644--- a/server/internal/daemon/execenv/runtime_config_sections.go+++ b/server/internal/daemon/execenv/runtime_config_sections.go@@ -429,10 +429,11 @@ func writeSkills(b *strings.Builder, provider string, ctx TaskContextForEnv) {switch provider {case "claude", "codebuddy":b.WriteString("You have the following skills installed (discovered automatically):\n\n")- case "codex", "copilot", "opencode", "openclaw", "pi", "cursor", "kimi", "kiro", "qoder", "antigravity":+ case "codex", "copilot", "opencode", "openclaw", "pi", "cursor", "kimi", "kiro", "qoder", "antigravity", "hermes":+ // Hermes discovers these from its per-task HERMES_HOME/skills (seeded by+ // the daemon), so it needs the same "discovered automatically" framing+ // as the other native-discovery runtimes rather than a path pointer.b.WriteString("You have the following skills installed (discovered automatically):\n\n")- case "hermes":- b.WriteString("Detailed skill instructions are in `.agent_context/skills/`. Each subdirectory contains a `SKILL.md`.\n\n")default:b.WriteString("Detailed skill instructions are in `.agent_context/skills/`. Each subdirectory contains a `SKILL.md`.\n\n")}diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex f28b44713c..1d4970fad0 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -25,10 +25,134 @@ import (// overridden by user-configured custom_args. `acp` is the protocol// subcommand that drives the ACP JSON-RPC transport; overriding it// would break the daemon↔Hermes communication contract.+//+// `-p`/`--profile` are NOT stripped unconditionally: a skill-less Hermes task+// has no overlay, so its profile selection must pass through to Hermes+// unchanged. The daemon strips the selected occurrence via StripHermesProfileArgs+// only when it actually built the per-task overlay (see the daemon's launch-arg+// handling), so the flag can't re-point HERMES_HOME past the overlay while+// leaving no-overlay tasks' behavior untouched.var hermesBlockedArgs = map[string]blockedArgMode{"acp": blockedStandalone,}+// hermesArgProfileRe mirrors the space-form guard in Hermes'+// hermes_cli.main._apply_profile_override step 1b: a `-p <value>` whose value+// doesn't match the profile-id shape is not a profile selection at all (e.g.+// pytest's `-p no:xdist`), so it is ignored rather than consumed. The inline+// `--profile=<value>` form is NOT guarded here — Hermes forwards it verbatim to+// resolve_profile_env, which validates and hard-fails on an invalid value; that+// validation lives in the daemon-side resolver (execenv.ResolveHermesProfile).+var hermesArgProfileRe = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,63}$`)++// hermesValueFlags and hermesOptionalValueFlags mirror the value-taking flags+// Hermes skips while scanning argv for -p/--profile, so a value like the `coder`+// in `-m coder -p research` is never misread as the profile. Kept in sync with+// _apply_profile_override.value_flags / optional_value_flags.+var hermesValueFlags = map[string]struct{}{+ "-z": {}, "--oneshot": {}, "-m": {}, "--model": {}, "--provider": {},+ "-t": {}, "--toolsets": {}, "-r": {}, "--resume": {}, "-s": {},+ "--skills": {}, "--usage-file": {},+}+var hermesOptionalValueFlags = map[string]struct{}{"-c": {}, "--continue": {}}++// HermesProfileSelection is the profile selection parsed out of custom_args by+// ParseHermesProfileArgs. It carries the exact argv occurrence to consume so the+// daemon-side resolver and the launch-arg stripping act on one authoritative+// parse instead of each re-approximating Hermes' argv handling.+type HermesProfileSelection struct {+ Name string // the selected value; "" for the empty inline `--profile=` value+ Found bool // a -p/--profile selection with a value was matched+ Inline bool // matched the `--profile=<value>` form (value validated downstream)+ ArgFrom int // index of the first token to strip, or -1 when nothing matched+ ArgLen int // tokens to strip: 2 for `-p <value>`, 1 for `--profile=<value>`+}++// ParseHermesProfileArgs finds the first Hermes profile selection in custom_args,+// mirroring hermes_cli.main._apply_profile_override step 1/1b: it scans for the+// first `-p`/`--profile <value>` or `--profile=<value>`, skipping value-taking+// flags and stopping at a `--` sentinel or an `mcp add --args` command-argv+// passthrough region. A space-form value that fails the profile-id shape is+// ignored (matches Hermes discarding it). Args are unquoted with the same helper+// as filterCustomArgs so quoting is handled consistently.+func ParseHermesProfileArgs(args []string) HermesProfileSelection {+ none := HermesProfileSelection{ArgFrom: -1}+ i := 0+ for i < len(args) {+ arg := unshellQuoteArg(args[i])+ if arg == "--" {+ break+ }+ if arg == "--args" && hermesInsideMcpAdd(args, i) {+ break+ }+ if arg == "-p" || arg == "--profile" {+ if i+1 < len(args) {+ val := unshellQuoteArg(args[i+1])+ if !hermesArgProfileRe.MatchString(val) {+ return none // step 1b: not a valid profile value, ignore+ }+ return HermesProfileSelection{Name: val, Found: true, ArgFrom: i, ArgLen: 2}+ }+ return none // trailing flag with no value+ }+ if v, ok := strings.CutPrefix(arg, "--profile="); ok {+ return HermesProfileSelection{Name: v, Found: true, Inline: true, ArgFrom: i, ArgLen: 1}+ }+ if _, ok := hermesValueFlags[arg]; ok && i+1 < len(args) {+ i += 2+ continue+ }+ if _, ok := hermesOptionalValueFlags[arg]; ok && i+1 < len(args) &&+ !strings.HasPrefix(unshellQuoteArg(args[i+1]), "-") {+ i += 2+ continue+ }+ i+++ }+ return none+}++// hermesInsideMcpAdd reports whether argv position index sits inside an+// `mcp add ... --args <child argv>` passthrough region, where flags belong to+// the child MCP command and must not be read as Hermes' own profile selector.+func hermesInsideMcpAdd(args []string, index int) bool {+ mcp := -1+ for j := 0; j < index; j++ {+ if unshellQuoteArg(args[j]) == "mcp" {+ mcp = j+ break+ }+ }+ if mcp < 0 {+ return false+ }+ for j := mcp + 1; j < index; j++ {+ if unshellQuoteArg(args[j]) == "add" {+ return true+ }+ }+ return false+}++// StripHermesProfileArgs removes exactly the argv occurrence ParseHermesProfileArgs+// selected. The daemon calls this only when it built the per-task overlay, so+// Hermes uses the overlay's HERMES_HOME instead of re-resolving the profile —+// while a skill-less task keeps its flags untouched.+func StripHermesProfileArgs(args []string, sel HermesProfileSelection) []string {+ if !sel.Found || sel.ArgFrom < 0 || sel.ArgLen <= 0 {+ return args+ }+ end := sel.ArgFrom + sel.ArgLen+ if end > len(args) {+ end = len(args)+ }+ out := make([]string, 0, len(args)-(end-sel.ArgFrom))+ out = append(out, args[:sel.ArgFrom]...)+ out = append(out, args[end:]...)+ return out+}+// hermesBackend implements Backend by spawning `hermes acp` and communicating// via the ACP (Agent Communication Protocol) JSON-RPC 2.0 over stdin/stdout.// This is the same pattern as Codex but with the ACP protocol instead ofdiff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.goindex 6d4041fb92..7a531bb795 100644--- a/server/pkg/agent/hermes_test.go+++ b/server/pkg/agent/hermes_test.go@@ -2375,3 +2375,72 @@ func TestHermesKeepsRemoteMcpWhenCapabilityAdvertised(t *testing.T) {t.Fatalf("session/new.mcpServers: got %d entries, want 3", len(servers))}}++// TestParseHermesProfileArgs covers the parser's fidelity to Hermes'+// _apply_profile_override step 1/1b: first occurrence, both spellings, the inline+// empty value, the space-form profile-id guard, value-flag skipping, and the+// `--` / `mcp add --args` boundaries.+func TestParseHermesProfileArgs(t *testing.T) {+ t.Parallel()+ cases := []struct {+ name string+ args []string+ wantName string+ found bool+ inline bool+ from int+ length int+ }{+ {"none", []string{"--yolo"}, "", false, false, -1, 0},+ {"short flag", []string{"-p", "research"}, "research", true, false, 0, 2},+ {"long flag", []string{"--profile", "research"}, "research", true, false, 0, 2},+ {"inline", []string{"--profile=research"}, "research", true, true, 0, 1},+ {"inline empty value", []string{"--profile="}, "", true, true, 0, 1},+ {"trailing short flag with no value", []string{"--yolo", "-p"}, "", false, false, -1, 0},+ {"amid other args", []string{"--yolo", "--profile", "coder", "-x"}, "coder", true, false, 1, 2},+ {"space-form invalid value ignored", []string{"-p", "no:xdist"}, "", false, false, -1, 0},+ {"value-flag hides a following -p", []string{"-m", "-p", "research"}, "", false, false, -1, 0},+ {"double-dash sentinel stops scan", []string{"--", "-p", "research"}, "", false, false, -1, 0},+ {"mcp add --args passthrough stops scan", []string{"mcp", "add", "srv", "--args", "-p", "research"}, "", false, false, -1, 0},+ {"only the first occurrence is selected", []string{"-p", "research", "--profile", "coder"}, "research", true, false, 0, 2},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ sel := ParseHermesProfileArgs(tc.args)+ if sel.Name != tc.wantName || sel.Found != tc.found || sel.Inline != tc.inline ||+ sel.ArgFrom != tc.from || sel.ArgLen != tc.length {+ t.Errorf("ParseHermesProfileArgs(%v) = %+v, want name=%q found=%v inline=%v from=%d len=%d",+ tc.args, sel, tc.wantName, tc.found, tc.inline, tc.from, tc.length)+ }+ })+ }+}++// TestStripHermesProfileArgs asserts only the parsed occurrence is removed (not+// every -p/--profile spelling), and that the base blocked set does NOT strip the+// profile flags, so a skill-less task's profile passes through unchanged.+func TestStripHermesProfileArgs(t *testing.T) {+ t.Parallel()+ args := []string{"-p", "research", "--yolo", "--profile", "coder"}+ sel := ParseHermesProfileArgs(args)+ got := StripHermesProfileArgs(args, sel)+ want := []string{"--yolo", "--profile", "coder"}+ if len(got) != len(want) {+ t.Fatalf("StripHermesProfileArgs = %v, want %v", got, want)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("StripHermesProfileArgs = %v, want %v", got, want)+ }+ }+ if none := StripHermesProfileArgs([]string{"--yolo"}, ParseHermesProfileArgs([]string{"--yolo"})); len(none) != 1 || none[0] != "--yolo" {+ t.Fatalf("no selection should leave args unchanged, got %v", none)+ }+ if _, ok := hermesBlockedArgs["-p"]; ok {+ t.Error("hermesBlockedArgs must not unconditionally strip -p")+ }+ if _, ok := hermesBlockedArgs["--profile"]; ok {+ t.Error("hermesBlockedArgs must not unconditionally strip --profile")+ }+}