Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8347: fix Hermes compatibility with gateway-backed and older ACP (#9666)
Bohan Jiang46d4e267129e
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex f985b91fab..eb932bef2b 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -164,6 +164,10 @@ Un cache n'est supprimé que si les trois conditions sont réunies : aucun espac| Mémoire Hermes (une par agent) | `hermes-state/` dans le même répertoire | Supprimée après 90 jours sans usage || Répertoire temporaire privé de chaque exécution (`TMPDIR`) | `multica-task-*` dans le répertoire temporaire du système | Supprimé à la fin de l'exécution ; si le daemon a été tué, un nettoyage ultérieur s'en charge |+Les exécutions Hermes liées à une tâche ou à un chat utilisent le répertoire persistant de leur conversation comme `HERMES_HOME` isolé, avec un fichier `state.db` ordinaire et ses journaux SQLite à l’intérieur. Cette disposition fonctionne aussi bien avec l’ACP exécuté dans le processus qu’avec l’ACP passant par la Gateway. Les historiques existants sont réutilisés et les historiques locaux sont migrés avant l’exécution suivante.++Multica actualise les skills et la configuration dérivée à chaque exécution. L’authentification du fournisseur de modèles est conservée ; les adaptateurs de messagerie et les points d’entrée HTTP sont désactivés pour les exécutions gérées. L’état de la Gateway, les journaux, les sessions et les tâches cron de l’hôte sont isolés. Toute Gateway propre à une exécution est arrêtée à la fin de celle-ci afin que les exécutions suivantes utilisent leur propre environnement.+### Mémoire native et sous-agents de Codex [#codex-memory]Dans les exécutions Codex gérées par le daemon, la mémoire native de Codex est désactivée par défaut, pour que les souvenirs de cette machine ou d'une exécution précédente ne passent pas dans un autre espace de travail. Le réglage est écrit uniquement dans le `CODEX_HOME/config.toml` propre à l'exécution (`features.memories`, `memories.generate_memories` et `memories.use_memories` à `false`) ; votre `~/.codex/config.toml` n'est pas modifié. Pour garder la mémoire native, définissez `MULTICA_CODEX_MEMORY=1` dans l'environnement du daemon.diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex eb8b75f1ad..8efa81f4ee 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -164,6 +164,10 @@ CodeBuddy、Kimi CLI、Pi は起動時に自分でユーザーレベルの設定| Hermes のメモリ(エージェントごとに 1 つ) | 同じディレクトリの `hermes-state/` | 90 日間使われないと削除 || 実行ごとの専用一時ディレクトリ(`TMPDIR`) | システムの一時ディレクトリの `multica-task-*` | 実行終了時に削除。デーモンが強制終了された場合は後のクリーンアップで削除 |+Hermes のタスクとチャットの実行では、会話の永続ディレクトリを隔離された `HERMES_HOME` として使用し、通常ファイルの `state.db` と SQLite のジャーナルをその中に置きます。この構成は、従来のプロセス内 ACP と Gateway 経由の ACP の両方に対応します。既存のセッション記録はそのまま再利用し、実行ローカルの履歴は次の実行前に移行します。++Multica は実行ごとにホーム内のスキルと派生設定を更新します。モデルプロバイダーの認証は保持し、管理下の実行ではメッセージングアダプターと HTTP の受信口を無効にします。ホストの Gateway 状態、ログ、セッション、cron ジョブは隔離されます。実行終了時にはその実行の Gateway を停止し、次の実行が専用の実行環境を使えるようにします。+### Codex のネイティブメモリとサブエージェント [#codex-memory]デーモンが管理する Codex の実行では、Codex のネイティブメモリが既定でオフになります。このマシンや以前の実行のメモリが別のワークスペースに持ち込まれないようにするためです。設定はその実行専用の `CODEX_HOME/config.toml` にだけ書かれ(`features.memories`、`memories.generate_memories`、`memories.use_memories` をすべて `false`)、`~/.codex/config.toml` は変更されません。ネイティブメモリを残したい場合は、デーモンの環境で `MULTICA_CODEX_MEMORY=1` を設定します。diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex 7da5d34f62..146c0a5b28 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -164,6 +164,10 @@ CodeBuddy, Kimi CLI, Pi는 시작할 때 사용자 수준 설정을 직접 읽| Hermes 메모리(에이전트마다 하나) | 같은 디렉터리의 `hermes-state/` | 90일 동안 쓰지 않으면 삭제 || 실행마다 쓰는 전용 임시 디렉터리(`TMPDIR`) | 시스템 임시 디렉터리의 `multica-task-*` | 실행이 끝나면 삭제. 데몬이 강제 종료된 경우 이후 정리에서 삭제 |+Hermes의 태스크 및 채팅 실행은 대화의 영구 디렉터리를 격리된 `HERMES_HOME`으로 사용하며, 일반 파일인 `state.db`와 SQLite 저널을 그 안에 둡니다. 이 구조는 기존의 프로세스 내 ACP와 Gateway 기반 ACP를 모두 지원합니다. 기존 세션 기록은 그대로 재사용하고, 실행 로컬 디렉터리의 기록은 다음 실행 전에 이전합니다.++Multica는 실행마다 홈의 스킬과 파생 설정을 갱신합니다. 모델 제공업체의 인증은 유지하고, 관리되는 실행의 메시징 어댑터와 HTTP 수신 기능은 비활성화합니다. 호스트의 Gateway 상태, 로그, 세션, cron 작업은 격리됩니다. 실행이 끝나면 해당 실행의 Gateway를 중지하여 다음 실행이 자체 실행 환경을 사용하도록 합니다.+### Codex 기본 메모리와 하위 에이전트 [#codex-memory]데몬이 관리하는 Codex 실행에서는 Codex 기본 메모리가 기본적으로 꺼집니다. 이 컴퓨터나 이전 실행의 메모리가 다른 워크스페이스로 넘어가지 않게 하기 위해서입니다. 설정은 해당 실행 전용 `CODEX_HOME/config.toml`에만 기록되고(`features.memories`, `memories.generate_memories`, `memories.use_memories` 모두 `false`), `~/.codex/config.toml`은 바뀌지 않습니다. 기본 메모리를 유지하려면 데몬 환경에 `MULTICA_CODEX_MEMORY=1`을 설정하세요.diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex 8f940bed12..e5602b167d 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -164,6 +164,10 @@ A cache is removed only when all three hold: no workspace or project references| Hermes memory (one per agent) | `hermes-state/` in the same directory | Removed after 90 days unused || Each run's private temporary directory (`TMPDIR`) | `multica-task-*` in the system temp directory | Removed when the run ends; if the daemon was killed, a later cleanup removes it |+Hermes issue and chat tasks use their conversation's session directory as an isolated `HERMES_HOME`, with a regular `state.db` and its SQLite journals inside it. This works with both in-process ACP and gateway-backed Hermes. Existing session stores are reused, and task-local history is migrated before the next run starts.++Multica refreshes the home's skills and derived configuration for each run. Provider authentication is preserved; messaging adapters and HTTP ingress are disabled for managed tasks. Host gateway state, logs, sessions, and cron jobs are isolated. Any task-owned gateway is stopped at task completion so later tasks receive their own execution environment.+### Codex native memory and subagents [#codex-memory]Daemon-managed Codex runs have Codex native memory turned off by default, so memories from this machine or an earlier run do not carry into another workspace. The setting is written only to that run's own `CODEX_HOME/config.toml` (`features.memories`, `memories.generate_memories`, and `memories.use_memories` all `false`); your `~/.codex/config.toml` is not changed. To keep native memory, set `MULTICA_CODEX_MEMORY=1` in the daemon's environment.diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 6c2003a9be..97faadb150 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -165,6 +165,10 @@ CodeBuddy、Kimi CLI 和 Pi 启动时会自己加载用户级配置,并与 Mul| Hermes 记忆(每个智能体一份) | 同一目录下的 `hermes-state/` | 90 天未使用后删除 || 每次运行的私有临时目录(`TMPDIR`) | 系统临时目录下的 `multica-task-*` | 运行结束后删除,守护进程被强制结束时由之后的清理补删 |+Hermes 在任务和聊天中的运行会将会话持久目录作为隔离的 `HERMES_HOME`,`state.db` 及其 SQLite 日志文件均为目录内的普通文件。这个布局同时支持旧版进程内 ACP 和新版由 Gateway 执行的 ACP。已有会话记录会直接复用,旧运行目录中的会话历史会在下次运行前迁移。++Multica 每次运行都会刷新其中的 skill 和派生配置。模型服务认证会保留,托管运行的消息平台适配器和 HTTP 入口会关闭。宿主的 Gateway 状态、日志、会话和定时任务各自隔离。运行结束时会停止本次运行的 Gateway,确保后续运行使用自己的执行环境。+### Codex 原生记忆与子智能体 [#codex-memory]守护进程管理的 Codex 运行默认关闭 Codex 原生记忆,避免本机或前一次运行留下的记忆带进别的工作区。设置只写入这次运行专用的 `CODEX_HOME/config.toml`(`features.memories` 和 `memories.generate_memories`、`memories.use_memories` 均为 `false`),不改你的 `~/.codex/config.toml`。需要保留原生记忆时,在守护进程的环境中设置 `MULTICA_CODEX_MEMORY=1`。diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 74652248a7..a0ab6ea01c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -8124,7 +8124,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot id.markActiveStore(store)defer d.unmarkActiveStore(store)}- // The overlay links state.db here so the conversation transcript+ // The conversation store is the isolated home, so its ordinary state.db// survives the task and a follow-up turn can actually resume it// (GH #6806). Keyed on (agent, resolved source home, conversation):// tasks of one conversation are serial, so the shard has a single@@ -8695,6 +8695,18 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iCodexVersion: codexVersion,BuiltinRuntime: !usesCustomProfileCommand,}+ if hermesOverlayActive {+ // Retire an owner left by a crashed/interrupted daemon before it can+ // execute tools with the preceding task's frozen environment.+ if err := agent.StopHermesTaskGateway(backendConfig, env.HermesHome); err != nil {+ return TaskResult{}, err+ }+ defer func() {+ if err := agent.StopHermesTaskGateway(backendConfig, env.HermesHome); err != nil {+ d.logger.Warn("failed to stop task Hermes gateway", "home", env.HermesHome, "error", err)+ }+ }()+ }// Register retirement before any fresh-session launch can fail. The check// uses the backend's final binary, environment, working directory and MCP// configuration, rather than the daemon's ambient OpenCode store.diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 50154136e3..5510ede236 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -103,7 +103,7 @@ type PrepareParams struct {// Multica profile dir could not be resolved.HermesMemoryStore string// HermesSessionStore is the conversation's persistent Hermes session store- // (HermesSessionStorePath) the overlay links state.db to, so the transcript+ // (HermesSessionStorePath) used as HERMES_HOME, so the transcript// outlives the task and a follow-up turn can actually resume it. Empty keeps// state.db task-local — no agent or conversation to key on, or the Multica// profile dir could not be resolved.@@ -317,9 +317,10 @@ 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+ // HermesHome is the effective 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/+ // otherwise, leaving the user's real home in place). With a conversation+ // store it lives there; otherwise it lives under the task root. 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@@ -327,10 +328,8 @@ type Environment struct {// .agent_context/skills/ fallback was never read (issue #5242). See// hermes_home.go.HermesHome string- // HermesSessionStore is the conversation's session store this task's- // state.db is actually linked to, or "" when the session database stayed- // task-local (no store to key on, or a host that could not create the- // link).+ // HermesSessionStore is the conversation's durable home, or "" when+ // there is no conversation store and the home stays task-local.HermesSessionStore string// HermesSessionHistoryPresent reports that the mounted store actually holds// a session database — a prior turn's transcript this task can resume.@@ -670,7 +669,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {if err != nil {return nil, fmt.Errorf("execenv: prepare hermes-home: %w", err)}- env.HermesHome = hermesHome+ env.HermesHome = sessions.Homeif sessions.Mounted {env.HermesSessionStore = params.HermesSessionStoreenv.HermesSessionHistoryPresent = sessions.HistoryPresent@@ -982,7 +981,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {logger.Warn("execenv: refresh hermes-home failed; forcing fresh prepare", "error", err)return nil}- env.HermesHome = hermesHome+ env.HermesHome = sessions.Homeenv.HermesSessionStore = ""env.HermesSessionHistoryPresent = falseif sessions.Mounted {diff --git a/server/internal/daemon/execenv/hermes_acp_integration_test.go b/server/internal/daemon/execenv/hermes_acp_integration_test.gonew file mode 100644index 0000000000..7d9f630a75--- /dev/null+++ b/server/internal/daemon/execenv/hermes_acp_integration_test.go@@ -0,0 +1,277 @@+//go:build agentintegration++package execenv++import (+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "net"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/pkg/agent"+)++// Run against each installed Hermes release. Inference stays on a local fixture;+// the test never loads the user's config, provider credentials or messaging accounts.+func TestHermesManagedHomeRealACP(t *testing.T) {+ if os.Getenv("MULTICA_RUN_REAL_AGENT_SMOKE") != "1" {+ t.Skip("set MULTICA_RUN_REAL_AGENT_SMOKE=1 to run a real Hermes binary")+ }+ cli, err := exec.LookPath("hermes")+ if err != nil {+ t.Fatal(err)+ }+ version, err := exec.Command(cli, "--version").CombinedOutput()+ if err != nil {+ t.Fatal(err)+ }+ t.Logf("%s", version)+ const liveTurnPrompt = "Hold this cancelled turn until interrupted. Return alpha without tools."+ var holdRequests atomic.Bool+ activeRequest := make(chan struct{}, 1)+ releaseRequests := make(chan struct{})+ model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if r.Method == http.MethodGet {+ fmt.Fprint(w, `{"object":"list","data":[{"id":"fixture-model","object":"model"}]}`)+ return+ }+ var request struct {+ Stream bool+ Messages json.RawMessage+ }+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {+ t.Error(err)+ return+ }+ if holdRequests.Load() && strings.Contains(string(request.Messages), liveTurnPrompt) {+ select {+ case activeRequest <- struct{}{}:+ default:+ }+ select {+ case <-releaseRequests:+ case <-r.Context().Done():+ }+ return+ }+ if request.Stream {+ w.Header().Set("Content-Type", "text/event-stream")+ fmt.Fprint(w, "data: {\"id\":\"fixture\",\"object\":\"chat.completion.chunk\",\"created\":1,\"model\":\"fixture-model\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"alpha\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")+ return+ }+ fmt.Fprint(w, `{"id":"fixture","object":"chat.completion","created":1,"model":"fixture-model","choices":[{"index":0,"message":{"role":"assistant","content":"alpha"},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":1,"total_tokens":11}}`)+ }))+ defer model.Close()+ defer close(releaseRequests)+ occupied, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer occupied.Close()+ source, store := t.TempDir(), filepath.Join(t.TempDir(), "conversation")+ // Mirror only PM's installed dependencies; no real user data or secrets.+ install := ""+ for _, line := range strings.Split(string(version), "\n") {+ if value, ok := strings.CutPrefix(line, "Install directory: "); ok {+ install = value+ }+ }+ if install == "" {+ t.Fatal("Hermes version did not identify its install directory")+ }+ // Old Hermes can republish its source launchers using a borrowed home's+ // tool path. Restore them before deleting that temporary home.+ launchers := filepath.Join(install, ".hermes", "bin")+ if entries, err := os.ReadDir(launchers); err == nil {+ for _, entry := range entries {+ if !entry.Type().IsRegular() {+ continue+ }+ path := filepath.Join(launchers, entry.Name())+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ info, err := entry.Info()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := os.WriteFile(path, data, info.Mode()); err != nil {+ t.Error(err)+ }+ })+ }+ }+ for _, name := range []string{"installs", "tools"} {+ if err := os.Symlink(filepath.Join(filepath.Dir(install), name), filepath.Join(source, name)); err != nil {+ t.Fatal(err)+ }+ }+ mustWrite(t, filepath.Join(source, "config.yaml"), fmt.Sprintf("model:\n provider: custom\n default: fixture-model\n base_url: %s/v1\n api_key: local-fixture-key\n api_mode: chat_completions\nmcp_servers: {}\nagent: {max_turns: 1, disabled_toolsets: [all]}\nmemory: {memory_enabled: false, user_profile_enabled: false}\ngateway:\n api_server: {enabled: true}\n", model.URL))+ mustWrite(t, filepath.Join(source, ".env"), fmt.Sprintf("API_SERVER_KEY=local-fixture-key-at-least-32-characters\nAPI_SERVER_ENABLED=false\nAPI_SERVER_HOST=127.0.0.1\nAPI_SERVER_PORT=%d\n", occupied.Addr().(*net.TCPAddr).Port))+ // A host PID must never be followed by gateway cleanup.+ mustWrite(t, filepath.Join(source, "gateway.pid"), "host fixture must stay untouched")+ var sessionID string+ for turn := range 2 {+ scratch := filepath.Join(t.TempDir(), "hermes-home")+ home, err := prepareHermesHome(scratch, source, false, []SkillContextForEnv{{Name: "fixture", Content: "Local test"}}, nil, "", store, testLogger())+ if err != nil {+ t.Fatal(err)+ }+ if home.HistoryPresent != (turn > 0) {+ t.Fatalf("turn %d history=%v", turn, home.HistoryPresent)+ }+ user := t.TempDir()+ cfg := agent.Config{ExecutablePath: cli, Logger: slog.Default(), BuiltinRuntime: true,+ Env: map[string]string{"HOME": user, "HERMES_HOME": home.Home,+ "HERMES_DISABLE_LAZY_INSTALLS": "1", "HERMES_ACP_SKIP_CONFIGURED_MCP": "1",+ "OPENAI_API_KEY": "local-fixture-key", "OPENAI_BASE_URL": model.URL + "/v1"}}+ func() {+ defer func() {+ if err := agent.StopHermesTaskGateway(cfg, home.Home); err != nil {+ t.Error(err)+ }+ if data, err := os.ReadFile(filepath.Join(home.Home, "gateway_state.json")); err == nil {+ var state struct {+ State string `json:"gateway_state"`+ }+ if err := json.Unmarshal(data, &state); err != nil || state.State != "stopped" {+ t.Errorf("task gateway did not stop: state=%s err=%v", state.State, err)+ }+ }+ }()+ backend, err := agent.New("hermes", cfg)+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "Reply with alpha without tools.", agent.ExecOptions{Cwd: user, ResumeSessionID: sessionID})+ if err != nil {+ t.Fatal(err)+ }+ for range session.Messages {+ }+ result := <-session.Result+ t.Logf("turn=%d status=%s output=%q session=%s error=%s", turn, result.Status, result.Output, result.SessionID, result.Error)+ if result.Status != "completed" || !strings.Contains(result.Output, "alpha") || result.SessionID == "" {+ t.Fatalf("unexpected result: %+v", result)+ }+ if sessionID != "" && result.SessionID != sessionID {+ t.Fatal("follow-up lost the original session")+ }+ sessionID = result.SessionID+ }()+ }+ t.Run("legacy_gateway_record", func(t *testing.T) {+ if _, err := os.Stat(filepath.Join(store, "gateway_state.json")); err == nil {+ t.Skip("gateway-backed ACP supports the interrupt flag")+ } else if !os.IsNotExist(err) {+ t.Fatal(err)+ }+ // A conversation used by a newer release may retain a stale lock after+ // downgrading to in-process ACP, whose CLI rejects gateway stop --yes.+ mustWrite(t, filepath.Join(store, "gateway.lock"), "")+ cfg := agent.Config{ExecutablePath: cli, Logger: slog.Default(),+ Env: map[string]string{"HOME": t.TempDir(), "HERMES_HOME": store}}+ if err := agent.StopHermesTaskGateway(cfg, store); err != nil {+ t.Fatalf("clean up a retained gateway record with an older CLI: %v", err)+ }+ })+ t.Run("interrupt_live_turn", func(t *testing.T) {+ if _, err := os.Stat(filepath.Join(store, "gateway_state.json")); os.IsNotExist(err) {+ t.Skip("in-process ACP has no detached gateway")+ } else if err != nil {+ t.Fatal(err)+ }+ holdRequests.Store(true)+ user := t.TempDir()+ cfg := agent.Config{ExecutablePath: cli, Logger: slog.Default(), BuiltinRuntime: true,+ Env: map[string]string{"HOME": user, "HERMES_HOME": store,+ "HERMES_DISABLE_LAZY_INSTALLS": "1", "HERMES_ACP_SKIP_CONFIGURED_MCP": "1",+ "OPENAI_API_KEY": "local-fixture-key", "OPENAI_BASE_URL": model.URL + "/v1"}}+ gatewayStop := func(interrupt bool) ([]byte, error) {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ args := []string{"--profile", "default", "gateway", "stop"}+ if interrupt {+ args = append(args, "--yes")+ }+ cmd := exec.CommandContext(ctx, cli, args...)+ cmd.Env = os.Environ()+ for key, value := range cfg.Env {+ cmd.Env = append(cmd.Env, key+"="+value)+ }+ return cmd.CombinedOutput()+ }+ // Cleanup must also work when the regression assertion fails before the+ // production stop helper is fixed; no detached gateway may outlive this test.+ defer func() {+ if output, err := gatewayStop(true); err != nil {+ t.Errorf("forced fixture cleanup failed: %v: %s", err, output)+ }+ }()+ backend, err := agent.New("hermes", cfg)+ if err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, liveTurnPrompt, agent.ExecOptions{Cwd: user, ResumeSessionID: sessionID})+ if err != nil {+ t.Fatal(err)+ }+ drained := make(chan struct{})+ go func() {+ defer close(drained)+ for range session.Messages {+ }+ }()+ select {+ case <-activeRequest:+ case <-time.After(45 * time.Second):+ t.Fatal("Hermes never started the blocked model request")+ }+ // Killing the ACP client does not stop the detached owner or its worker.+ cancel()+ select {+ case result := <-session.Result:+ if result.Status != "aborted" {+ t.Fatalf("cancelled ACP result = %+v", result)+ }+ case <-time.After(15 * time.Second):+ t.Fatal("cancelled ACP client did not exit")+ }+ <-drained+ // Prove this is still a live turn, not an idle-gateway cleanup test.+ if output, err := gatewayStop(false); err == nil || !strings.Contains(string(output), "Refusing to stop the gateway") {+ t.Fatalf("expected refusal for live work without --yes: err=%v output=%s", err, output)+ }+ if err := agent.StopHermesTaskGateway(cfg, store); err != nil {+ t.Fatalf("stop detached gateway with cancelled live turn: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(store, "gateway_state.json"))+ if err != nil {+ t.Fatal(err)+ }+ var state struct {+ State string `json:"gateway_state"`+ ActiveAgents int `json:"active_agents"`+ }+ if err := json.Unmarshal(data, &state); err != nil || state.State != "stopped" || state.ActiveAgents != 0 {+ t.Fatalf("gateway still has live work: state=%+v err=%v", state, err)+ }+ })+}diff --git a/server/internal/daemon/execenv/hermes_gateway.go b/server/internal/daemon/execenv/hermes_gateway.gonew file mode 100644index 0000000000..40ea6f210b--- /dev/null+++ b/server/internal/daemon/execenv/hermes_gateway.go@@ -0,0 +1,132 @@+package execenv++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"++ "gopkg.in/yaml.v3"+)++const hermesGatewayStateMarker = ".multica-gateway-state-v1"++func isHermesGatewayStateEntry(name string) bool {+ return name == "logs" || name == "sessions" || name == "cron" ||+ strings.HasPrefix(name, "gateway.") || strings.HasPrefix(name, "gateway_")+}++// Older overlays mirrored these paths, including the host's live PID records+// and cron jobs. Detach them once, without following links into the source home.+func prepareHermesGatewayState(home string) error {+ marker := filepath.Join(home, hermesGatewayStateMarker)+ if _, err := os.Stat(marker); err == nil {+ return nil+ } else if !os.IsNotExist(err) {+ return err+ }+ entries, err := os.ReadDir(home)+ if err != nil {+ return err+ }+ for _, entry := range entries {+ if isHermesGatewayStateEntry(entry.Name()) {+ if err := os.RemoveAll(filepath.Join(home, entry.Name())); err != nil {+ return err+ }+ }+ }+ return writeFileAtomic(marker, []byte("isolated Hermes gateway state\n"), 0o600)+}++// ACP needs the local session runtime, not messaging adapters or HTTP ingress.+// Explicit false survives credentials from both dotenv and the process env in+// old and gateway-backed Hermes. Include env-only bundled platforms, as well as+// every platform configured by the user, including third-party plugins.+// When validating a new Hermes release, check gateway.config.Platform and+// plugins/platforms for new env-only adapters and update this list.+var hermesGatewayPlatforms = []string{+ "local", "telegram", "discord", "whatsapp", "whatsapp_cloud", "slack",+ "signal", "mattermost", "matrix", "email", "sms", "dingtalk", "api_server",+ "webhook", "msgraph_webhook", "feishu", "wecom", "wecom_callback", "weixin",+ "bluebubbles", "qqbot", "yuanbao", "relay", "a2a", "buzz", "google_chat",+ "irc", "line", "ntfy", "photon", "raft", "simplex", "teams",+}++func disableHermesGatewayIngress(doc *yaml.Node) error {+ top := yamlDocumentRoot(doc)+ if top == nil {+ return fmt.Errorf("hermes gateway config: expected a mapping")+ }+ platforms := map[string]map[string]any{}+ if existing := yamlMapValue(top, "platforms"); existing != nil {+ if err := existing.Decode(&platforms); err != nil {+ return fmt.Errorf("hermes platforms config: %w", err)+ }+ detachHermesConfigAliases(doc, existing)+ }+ if platforms == nil {+ platforms = map[string]map[string]any{}+ }+ nested := resolveHermesYAMLAlias(yamlMapValue(top, "gateway"))+ if nested != nil && nested.Kind == yaml.MappingNode {+ if configured := yamlMapValue(nested, "platforms"); configured != nil {+ var entries map[string]any+ if err := configured.Decode(&entries); err != nil {+ return fmt.Errorf("hermes gateway platforms config: %w", err)+ }+ for name := range entries {+ if _, exists := platforms[name]; !exists {+ platforms[name] = nil+ }+ }+ }+ }+ for _, name := range hermesGatewayPlatforms {+ if platforms[name] == nil {+ platforms[name] = map[string]any{}+ }+ }+ for name, config := range platforms {+ if config == nil {+ config = map[string]any{}+ platforms[name] = config+ }+ config["enabled"] = false+ }+ var node yaml.Node+ if err := node.Encode(platforms); err != nil {+ return err+ }+ yamlSetMapValue(top, "platforms", &node)+ // gateway.<platform> shorthand overrides the top-level platform blocks.+ if nested != nil && nested.Kind == yaml.MappingNode {+ var settings map[string]any+ if err := nested.Decode(&settings); err != nil {+ return err+ }+ for name := range platforms {+ if config, ok := settings[name].(map[string]any); ok {+ config["enabled"] = false+ }+ }+ detachHermesConfigAliases(doc, nested)+ var derived yaml.Node+ if err := derived.Encode(settings); err != nil {+ return err+ }+ yamlSetMapValue(top, "gateway", &derived)+ }+ yamlSetMapValue(top, "multiplex_profiles", &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!bool", Value: "false"})+ return nil+}++// Preserve references elsewhere in the config before replacing an anchored section.+func detachHermesConfigAliases(doc, node *yaml.Node) {+ if node.Anchor != "" {+ expandAliasesOf(doc, node)+ }+ for _, child := range node.Content {+ detachHermesConfigAliases(doc, child)+ }+}diff --git a/server/internal/daemon/execenv/hermes_gateway_home_test.go b/server/internal/daemon/execenv/hermes_gateway_home_test.gonew file mode 100644index 0000000000..93ac0ab078--- /dev/null+++ b/server/internal/daemon/execenv/hermes_gateway_home_test.go@@ -0,0 +1,137 @@+package execenv++import (+ "os"+ "path/filepath"+ "testing"++ "gopkg.in/yaml.v3"+)++func TestHermesConversationHomeOwnsDatabase(t *testing.T) {+ shared := t.TempDir()+ store := filepath.Join(t.TempDir(), "conversation")+ first := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "review", Content: "Review code"}}+ prepared, err := prepareHermesHome(first, shared, false, skills, nil, "", store, testLogger())+ if err != nil {+ t.Fatal(err)+ }+ first = prepared.Home+ // Hermes' gateway requires the resolved DB parent to equal its resolved home.+ mustWrite(t, filepath.Join(first, "state.db"), "persisted transcript")+ home, err := filepath.EvalSymlinks(first)+ if err != nil {+ t.Fatal(err)+ }+ db, err := filepath.EvalSymlinks(filepath.Join(first, "state.db"))+ if err != nil {+ t.Fatal(err)+ }+ if filepath.Dir(db) != home {+ t.Fatalf("database parent %s is outside Hermes home %s (mount %+v)", filepath.Dir(db), home, prepared)+ }+}++func TestHermesTaskDisablesGatewayIngress(t *testing.T) {+ shared, home := t.TempDir(), filepath.Join(t.TempDir(), "hermes-home")+ mustWrite(t, filepath.Join(shared, "config.yaml"), "model: {provider: custom, default: fixture-model}\nplatforms:\n api_server: {enabled: true, port: 8642}\n discord: {enabled: true}\n custom-chat: {enabled: true}\n")+ for _, name := range []string{"gateway.pid", "gateway.lock", "gateway_state.json", "gateway.sock.path", "gateway.json", "cron/jobs.json", "sessions/sessions.json", "logs/gateway.log"} {+ mustWrite(t, filepath.Join(shared, name), "host-only")+ }+ if _, err := prepareHermesHome(home, shared, false, nil, nil, "", "", testLogger()); err != nil {+ t.Fatal(err)+ }+ for _, name := range []string{"gateway.pid", "gateway.lock", "gateway_state.json", "gateway.sock.path", "gateway.json", "cron/jobs.json", "sessions/sessions.json", "logs/gateway.log"} {+ if _, err := os.Stat(filepath.Join(home, name)); !os.IsNotExist(err) {+ t.Errorf("task inherited host runtime entry %s (err %v)", name, err)+ }+ }+ data, err := os.ReadFile(filepath.Join(home, "config.yaml"))+ if err != nil {+ t.Fatal(err)+ }+ var config struct {+ Model struct{ Default string }+ Platforms map[string]struct{ Enabled bool }+ }+ if err := yaml.Unmarshal(data, &config); err != nil {+ t.Fatal(err)+ }+ if config.Model.Default != "fixture-model" {+ t.Fatal("model configuration was lost")+ }+ for _, name := range []string{"api_server", "discord", "telegram", "custom-chat"} {+ platform, ok := config.Platforms[name]+ if !ok || platform.Enabled {+ t.Errorf("platform %s not explicitly disabled", name)+ }+ }+ // Reuse keeps task-owned gateway state, while the host remains unchanged.+ mustWrite(t, filepath.Join(home, "gateway_state.json"), "task-owned")+ if _, err := prepareHermesHome(home, shared, false, nil, nil, "", "", testLogger()); err != nil {+ t.Fatal(err)+ }+ for path, want := range map[string]string{+ filepath.Join(home, "gateway_state.json"): "task-owned",+ filepath.Join(shared, "gateway_state.json"): "host-only",+ } {+ if got, err := os.ReadFile(path); err != nil || string(got) != want {+ t.Errorf("runtime state %s = %q, %v; want %q", path, got, err, want)+ }+ }+}++func TestHermesLegacySessionLinkMigration(t *testing.T) {+ requireSymlinks(t)+ shared, scratch, store := t.TempDir(), t.TempDir(), t.TempDir()+ if _, err := prepareHermesHome(scratch, shared, false, nil, nil, "", "", testLogger()); err != nil {+ t.Fatal(err)+ }+ mustWrite(t, filepath.Join(store, "state.db"), "original transcript")+ mustWrite(t, filepath.Join(store, "state.db-wal"), "original WAL")+ if err := os.Symlink(filepath.Join(store, "state.db"), filepath.Join(scratch, "state.db")); err != nil {+ t.Fatal(err)+ }+ prepared, err := prepareHermesHome(scratch, shared, false, nil, nil, "", store, testLogger())+ if err != nil || !prepared.HistoryPresent || prepared.Home != store {+ t.Fatalf("legacy migration = %+v, %v", prepared, err)+ }+ for name, want := range map[string]string{"state.db": "original transcript", "state.db-wal": "original WAL"} {+ got, err := os.ReadFile(filepath.Join(store, name))+ if err != nil || string(got) != want {+ t.Errorf("%s = %q, %v; want %q", name, got, err, want)+ }+ }+ if fi, err := os.Lstat(scratch); err != nil || !fi.IsDir() {+ t.Fatalf("rollback task overlay must remain an ordinary directory: %v", err)+ }+}++func TestHermesDisablesNestedGatewayPlatforms(t *testing.T) {+ shared, home := t.TempDir(), t.TempDir()+ mustWrite(t, filepath.Join(shared, "config.yaml"), "template: &adapter {enabled: true, port: 8642}\ngateway:\n api_server: *adapter\n platforms:\n custom-chat: {enabled: true}\nplatforms:\n discord: *adapter\n")+ if err := writeDerivedHermesConfig(shared, home, nil, testLogger()); err != nil {+ t.Fatal(err)+ }+ data, err := os.ReadFile(filepath.Join(home, "config.yaml"))+ if err != nil {+ t.Fatal(err)+ }+ var parsed struct {+ Template struct{ Enabled bool }+ Gateway struct {+ APIServer struct{ Enabled bool } `yaml:"api_server"`+ }+ Platforms map[string]struct{ Enabled bool }+ }+ if err := yaml.Unmarshal(data, &parsed); err != nil {+ t.Fatal(err)+ }+ if !parsed.Template.Enabled || parsed.Gateway.APIServer.Enabled || parsed.Platforms["discord"].Enabled {+ t.Fatal("nested disable changed the template or left an adapter enabled")+ }+ if platform, ok := parsed.Platforms["custom-chat"]; !ok || platform.Enabled {+ t.Fatal("nested custom platform was not explicitly disabled")+ }+}diff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.goindex 33b76885ce..6ca8abdb8a 100644--- a/server/internal/daemon/execenv/hermes_home.go+++ b/server/internal/daemon/execenv/hermes_home.go@@ -15,8 +15,9 @@ import ()// Hermes discovers skills in HERMES_HOME/skills before skills.external_dirs;-// it does not scan the task workspace. Bound skills therefore use a task-local-// home overlay, while skill-less tasks keep the original home.+// it does not scan the task workspace. Bound skills therefore use an isolated+// home overlay, while skill-less tasks keep the original home. Conversation+// stores are the effective home so state.db stays inside its owning profile.//// Mirror host-home entries except task-owned overrides. The local skills directory// contains bound skills; external_dirs preserves shared skills and configured@@ -68,6 +69,10 @@ var hermesOverriddenEntries = map[string]struct{}{"active_profile": {},"profiles": {},".env": {},+ "logs": {},+ "sessions": {},+ "cron": {},+ hermesGatewayStateMarker: {},hermesTaskLocalStateMarker: {},}@@ -80,7 +85,7 @@ func isHermesOverlayOwnedEntry(name string) bool {if _, owned := hermesOverriddenEntries[name]; owned {return true}- return isHermesTaskLocalStateEntry(name)+ return isHermesTaskLocalStateEntry(name) || isHermesGatewayStateEntry(name)}func isHermesTaskLocalStateEntry(name string) bool {@@ -310,7 +315,7 @@ func hermesProfileDir(root, name string) (home string, mustExist bool, err error}// prepareHermesHome builds the per-task HERMES_HOME compatibility overlay-// described above. The daemon exports the given path as HERMES_HOME on the+// described above. The daemon exports the returned Home 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@@ -328,10 +333,10 @@ func hermesProfileDir(root, name string) (home string, mustExist bool, err error// what the Hermes child sees. memoryStore is the agent's persistent memory store// (execenv.HermesMemoryStorePath) that memories/ is linked to; empty keeps// memories/ task-local for this task. sessionStore is the conversation's-// persistent session store (execenv.HermesSessionStorePath) that state.db is-// linked to; empty — or a host that cannot create the link — keeps the session-// database task-local. The returned hermesSessionMount reports both what got-// mounted and whether the store actually holds a transcript, so the caller never+// persistent session store (execenv.HermesSessionStorePath), used as the+// effective home; empty keeps the session database task-local.+// The returned hermesSessionMount reports the effective home and whether the+// store actually holds a transcript, so the caller never// tells a task it can resume history that is not there.func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, memoryStore, sessionStore string, logger *slog.Logger) (sessions hermesSessionMount, err error) {sharedHome := strings.TrimSpace(sourceHome)@@ -344,6 +349,14 @@ func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, work}}+ if sessionStore != "" {+ sessions, err = prepareHermesSessionHome(hermesHome, sessionStore, logger)+ if err != nil {+ return hermesSessionMount{}, fmt.Errorf("prepare conversation home: %w", err)+ }+ hermesHome = sessions.Home+ }+ sessions.Home = hermesHomeif err := os.MkdirAll(hermesHome, 0o700); err != nil {return hermesSessionMount{}, fmt.Errorf("create hermes-home dir: %w", err)}@@ -355,16 +368,8 @@ func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workif err := prepareHermesTaskLocalState(hermesHome); err != nil {return hermesSessionMount{}, fmt.Errorf("prepare task-local state: %w", err)}- // Sessions: link state.db at the conversation's persistent store so the- // transcript survives the task. A store that cannot be mounted leaves the- // database task-local — the pre-existing behaviour — rather than failing the- // task. See hermes_sessions.go.- if sessionStore != "" {- mounted, err := mountHermesSessionDB(hermesHome, sessionStore, logger)- if err != nil {- return hermesSessionMount{}, fmt.Errorf("mount conversation sessions: %w", err)- }- sessions = mounted+ if err := prepareHermesGatewayState(hermesHome); err != nil {+ return hermesSessionMount{}, fmt.Errorf("prepare gateway state: %w", err)}// Memory: link memories/ at the agent's persistent store so it survives the// task, or fall back to a fresh task-local dir when there is no store (no@@ -426,6 +431,7 @@ func writeDerivedHermesEnv(sharedHome, hermesHome string) error {// 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)+ buf.WriteString("GATEWAY_MULTIPLEX_PROFILES=false\n")return writeFileAtomic(dst, []byte(buf.String()), 0o600)}@@ -587,9 +593,8 @@ func linkSharedHermesEntry(src, dst string) error {// 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+// root. Invalid config fails closed because Hermes could otherwise fall back to+// environment credentials and enable the host's messaging adapters. The file// is written 0600 (it can hold inline api_key secrets) via atomic replace, so// reuse also repairs a prior file's permissions. The terminal passthrough// allowlist preserves task credentials in tool shells without storing values.@@ -626,23 +631,27 @@ func writeDerivedHermesConfig(sharedHome, hermesHome string, env map[string]striif err := setHermesTerminalEnvPassthrough(doc); err != nil {return err}+ if err := disableHermesGatewayIngress(doc); err != nil {+ return err+ }return marshalYAMLToFile(doc, dstConfig)}var doc yaml.Nodeif err := yaml.Unmarshal(data, &doc); err != nil {- logger.Warn("execenv: hermes-home config parse failed; copying verbatim", "error", err)- return writeFileAtomic(dstConfig, data, 0o600)+ return fmt.Errorf("parse hermes config: %w", err)}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)+ return err}// 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)+ if err := disableHermesGatewayIngress(&doc); err != nil {+ return err+ }if err := setHermesTerminalEnvPassthrough(&doc); err != nil {logger.Warn("execenv: hermes-home set terminal passthrough failed; keeping other derived settings", "error", err)}@@ -847,8 +856,7 @@ func writeHermesBoundSkills(hermesHome string, workspaceSkills []SkillContextFor// 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.+ // This directory is owned by the isolated home and replaced on every run.return writeSkillFiles(skillsDir, workspaceSkills, nil)}diff --git a/server/internal/daemon/execenv/hermes_home_test.go b/server/internal/daemon/execenv/hermes_home_test.goindex 972f6efe96..4f48b3a73c 100644--- a/server/internal/daemon/execenv/hermes_home_test.go+++ b/server/internal/daemon/execenv/hermes_home_test.go@@ -968,15 +968,8 @@ func TestHermesTerminalConfigInvalidAliases(t *testing.T) {} {source, overlay := t.TempDir(), t.TempDir()mustWrite(t, filepath.Join(source, "config.yaml"), config)- if err := writeDerivedHermesConfig(source, overlay, nil, testLogger()); err != nil {- t.Fatal(err)- }- data, err := os.ReadFile(filepath.Join(overlay, "config.yaml"))- if err != nil {- t.Fatal(err)- }- if string(data) != config {- t.Errorf("invalid alias config was not preserved: got %q, want %q", data, config)+ if err := writeDerivedHermesConfig(source, overlay, nil, testLogger()); err == nil {+ t.Fatal("malformed config must fail closed before gateway ingress can start")}}cycle := &yaml.Node{Kind: yaml.AliasNode}diff --git a/server/internal/daemon/execenv/hermes_sessions.go b/server/internal/daemon/execenv/hermes_sessions.goindex 22e334fc8c..10e8c47d2e 100644--- a/server/internal/daemon/execenv/hermes_sessions.go+++ b/server/internal/daemon/execenv/hermes_sessions.go@@ -16,10 +16,9 @@ import (// get separate SQLite databases. This keeps resumable transcripts across task homes// without sharing a live database among an agent's concurrent issues.//-// Keep session storage outside the memories root. Link overlay/state.db to the-// store so SQLite places WAL and SHM sidecars beside the persistent database and-// task teardown cannot remove them. Detect provider session-ID rebinding when a-// requested session is absent.+// The conversation store is the effective HERMES_HOME, with an ordinary state.db+// and its journals inside it. Both in-process ACP and gateway-backed Hermes can+// use it without relaxing gateway database ownership checks or copying a live DB.// hermesSessionStoreRoot is the directory under the daemon's Multica profile// dir that holds every agent's persistent Hermes conversation shards.@@ -71,110 +70,53 @@ func hermesConversationSegment(task TaskContextForEnv) string {// hermesSessionMount is what a mount attempt actually achieved.//-// The two facts are deliberately separate. Mounted says state.db resolves to-// the store; HistoryPresent says the store holds a database to resume. A+// The two facts are deliberately separate. Mounted says the store is the home;+// HistoryPresent says the store holds a database to resume. A// mounted-but-empty store is the normal shape of a conversation's first turn,// and also what a GC reclaim, a profile switch or an operator's `rm` leaves// behind — treating "mounted" as "resumable" would forward a session id into an// empty database, which is the silent restart this whole change exists to kill.type hermesSessionMount struct {+ Home stringMounted boolHistoryPresent bool}-// hermesSessionLink creates the store link. Indirected so a test can simulate a-// host that cannot create symlinks — the degradation path is the one that must-// never destroy a database, so it needs coverage everywhere, not only on-// Windows.-var hermesSessionLink = os.Symlink--// hermesSessionCopy copies one file of a migration. Indirected so a test can-// fail the second file of the state.db family and prove the store is never left-// holding a partially migrated conversation.+// hermesSessionCopy copies one file of a migration. Tests can fail a sidecar+// copy to prove a partial migration never replaces the original transcript.var hermesSessionCopy = copyFile-// mountHermesSessionDB points the overlay's state.db at the conversation's-// store, so the transcript outlives the task.-//-// The order of operations is the contract. Nothing that could destroy an-// existing database happens until the link has actually been created (under a-// staging name), because the alternative — migrate, delete, then discover this-// host cannot symlink — turns a working task-local conversation into an empty-// one on exactly the hosts the degradation path exists to protect. A false-// Mounted with a nil error therefore means "nothing was touched; keep the-// database task-local", which is the pre-existing behaviour.-//-// Idempotent across Reuse: a link already pointing at the store is left alone.-// A real state.db left by an older daemon — or by a task that ran before this-// conversation had a store — is migrated into an empty store rather than-// dropped, so upgrading mid-conversation does not discard the transcript the-// user is in the middle of.-func mountHermesSessionDB(hermesHome, storeDir string, logger *slog.Logger) (hermesSessionMount, error) {- dst := filepath.Join(hermesHome, hermesSessionDBEntry)- target := filepath.Join(storeDir, hermesSessionDBEntry)-+// prepareHermesSessionHome uses the existing conversation store as the home.+// Keep the old task overlay intact for daemon rollback: an older daemon can+// still link its state.db to this same store. Never turn that task path into a+// directory link, which would let an older daemon unlink the store's own DB.+func prepareHermesSessionHome(hermesHome, storeDir string, logger *slog.Logger) (hermesSessionMount, error) {if err := os.MkdirAll(storeDir, 0o700); err != nil {- return hermesSessionMount{}, fmt.Errorf("create hermes session store %s: %w", storeDir, err)+ return hermesSessionMount{}, fmt.Errorf("create hermes session home: %w", err)}-- fi, err := os.Lstat(dst)- switch {- case err == nil && fi.Mode()&os.ModeSymlink != 0:- if current, rlErr := os.Readlink(dst); rlErr == nil && filepath.Clean(current) == filepath.Clean(target) {- // Already mounted (Reuse). The link can still be dangling — the GC- // may have reclaimed the store since the last turn — so the history- // question is answered from the store, never from the link.- touchHermesSessionStore(storeDir, logger)- return hermesSessionMount{Mounted: true, HistoryPresent: hermesStoreHasSessionDB(storeDir)}, nil+ if filepath.Clean(hermesHome) != filepath.Clean(storeDir) {+ if err := os.MkdirAll(hermesHome, 0o700); err != nil {+ return hermesSessionMount{}, err+ }+ if err := prepareHermesTaskLocalState(hermesHome); err != nil {+ return hermesSessionMount{}, err+ }+ if err := migrateHermesTaskSessionDB(hermesHome, storeDir, logger); err != nil {+ return hermesSessionMount{}, err+ }+ if err := removeHermesSessionDBFamily(hermesHome); err != nil {+ return hermesSessionMount{}, err}- case err != nil && !os.IsNotExist(err):- return hermesSessionMount{}, fmt.Errorf("stat hermes session db %s: %w", dst, err)- }-- // Prove the host can link BEFORE anything destructive. A real symlink,- // never a copy: createFileLink falls back to copying on a Windows host that- // cannot symlink, and a copied SQLite database would absorb every write of- // this turn into a file the next task throws away — worse than staying- // task-local, because it looks like it worked.- staged := filepath.Join(hermesHome, hermesSessionLinkStagingEntry)- if err := os.RemoveAll(staged); err != nil {- return hermesSessionMount{}, fmt.Errorf("clear stale session link staging %s: %w", staged, err)- }- if err := hermesSessionLink(target, staged); err != nil {- logger.Warn("execenv: hermes session store not mounted; conversation history stays task-local",- "store", storeDir,- "error", err,- )- return hermesSessionMount{}, nil- }- defer os.RemoveAll(staged) // no-op once the staging link has been renamed into place-- if err := migrateHermesTaskSessionDB(hermesHome, storeDir, logger); err != nil {- return hermesSessionMount{}, err}- if err := removeHermesSessionDBFamily(hermesHome); err != nil {+ // This store already belongs to the conversation. Mark it before the generic+ // overlay initializer, whose legacy-host migration would otherwise discard it.+ if err := writeFileAtomic(filepath.Join(storeDir, hermesTaskLocalStateMarker), []byte("conversation Hermes state\n"), 0o600); err != nil {return hermesSessionMount{}, err}- // Publish the link. Fails closed: the database is already safe in the store- // by this point, so a rename failure means a broken filesystem, not lost- // history, and the task must not start against a home with no state.db path- // at all.- if err := os.Rename(staged, dst); err != nil {- return hermesSessionMount{}, fmt.Errorf("publish hermes session link %s: %w", dst, err)- }- // Stamp the store as just-used: mounting it does not touch its mtime, so- // without this the GC's idle check could reclaim a long-idle conversation- // right as a task picks it back up.touchHermesSessionStore(storeDir, logger)- return hermesSessionMount{Mounted: true, HistoryPresent: hermesStoreHasSessionDB(storeDir)}, nil+ return hermesSessionMount{Home: storeDir, Mounted: true, HistoryPresent: hermesStoreHasSessionDB(storeDir)}, nil}-// hermesSessionLinkStagingEntry is where the store link is created before it is-// published over state.db. Dot-prefixed so isHermesTaskLocalStateEntry does not-// match it and the family cleanup cannot remove the link it is about to-// publish.-const hermesSessionLinkStagingEntry = ".multica-session-link"-// hermesStoreHasSessionDB reports whether storeDir holds a session database// with readable content. A zero-length file is what SQLite leaves after an// `open` that never wrote a page; resuming against it is the same as an absentdiff --git a/server/internal/daemon/execenv/hermes_sessions_test.go b/server/internal/daemon/execenv/hermes_sessions_test.goindex e2404a2ea0..8e97c1a959 100644--- a/server/internal/daemon/execenv/hermes_sessions_test.go+++ b/server/internal/daemon/execenv/hermes_sessions_test.go@@ -84,13 +84,14 @@ func TestPrepareHermesHomeSessionStorePersistsAcrossTasks(t *testing.T) {t.Fatal("HistoryPresent = true on a conversation's first turn, want false")}// Hermes creates state.db lazily and writes the transcript into it.- mustWrite(t, filepath.Join(firstTask, "state.db"), "transcript")+ mustWrite(t, filepath.Join(sessions.Home, "state.db"), "transcript")secondTask := filepath.Join(t.TempDir(), "hermes-home")- if _, err := prepareHermesHome(secondTask, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {+ sessions, err = prepareHermesHome(secondTask, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {t.Fatalf("prepare second task: %v", err)}- got, err := os.ReadFile(filepath.Join(secondTask, "state.db"))+ got, err := os.ReadFile(filepath.Join(sessions.Home, "state.db"))if err != nil {t.Fatalf("second task lost the conversation transcript: %v", err)}@@ -98,14 +99,14 @@ func TestPrepareHermesHomeSessionStorePersistsAcrossTasks(t *testing.T) {t.Fatalf("transcript = %q, want %q", got, "transcript")}- // It must be a link into the store, not a copy — a copy would take this- // turn's writes and throw them away with the task directory.- fi, err := os.Lstat(filepath.Join(secondTask, "state.db"))+ // The database is an ordinary file in the durable home. Task cleanup+ // cannot delete it, and gateway ownership checks accept it.+ fi, err := os.Lstat(filepath.Join(sessions.Home, "state.db"))if err != nil {t.Fatalf("lstat state.db: %v", err)}- if fi.Mode()&os.ModeSymlink == 0 {- t.Fatalf("state.db is not a link (mode %v)", fi.Mode())+ if !fi.Mode().IsRegular() {+ t.Fatalf("state.db is not a regular file (mode %v)", fi.Mode())}}@@ -124,14 +125,14 @@ func TestPrepareHermesHomeSessionStoreIsolatesConversations(t *testing.T) {filepath.Join(storeRoot, "agent-1", "default", "issue-a"), testLogger()); err != nil {t.Fatalf("prepare conversation A: %v", err)}- mustWrite(t, filepath.Join(homeA, "state.db"), "issue A transcript")+ mustWrite(t, filepath.Join(storeRoot, "agent-1", "default", "issue-a", "state.db"), "issue A transcript")homeB := filepath.Join(t.TempDir(), "hermes-home")if _, err := prepareHermesHome(homeB, sharedHome, false, skills, nil, "",filepath.Join(storeRoot, "agent-1", "default", "issue-b"), testLogger()); err != nil {t.Fatalf("prepare conversation B: %v", err)}- if _, err := os.ReadFile(filepath.Join(homeB, "state.db")); !os.IsNotExist(err) {+ if _, err := os.ReadFile(filepath.Join(storeRoot, "agent-1", "default", "issue-b", "state.db")); !os.IsNotExist(err) {t.Fatalf("conversation B can see another conversation's transcript (err = %v)", err)}}@@ -290,7 +291,7 @@ func TestPrepareHermesHomeSessionMountIsIdempotent(t *testing.T) {if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {t.Fatalf("prepare: %v", err)}- mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ mustWrite(t, filepath.Join(store, "state.db"), "transcript")if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {t.Fatalf("reuse prepare: %v", err)}@@ -373,71 +374,29 @@ func TestPruneHermesSessionStoresDisabled(t *testing.T) {}}-// TestPrepareHermesHomeLinkFailureKeepsTaskLocalDB is the degradation contract:-// on a host that cannot symlink, the mount must leave the task-local database-// exactly where it found it. Getting the order wrong — migrate, delete, then-// discover the link cannot be created — would turn a conversation that worked-// via workdir reuse into an empty one, i.e. a regression on precisely the hosts-// the fallback exists to protect.-//-// The failure is injected rather than skipped: this path must be covered on-// every host, not only on a Windows box without symlink privileges.-func TestPrepareHermesHomeLinkFailureKeepsTaskLocalDB(t *testing.T) {- sharedHome := t.TempDir()- store := filepath.Join(t.TempDir(), "issue-1")- skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}- hermesHome := filepath.Join(t.TempDir(), "hermes-home")-- if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {- t.Fatalf("prepare pre-store task: %v", err)+func TestPrepareHermesHomeSessionSurvivesTaskCleanup(t *testing.T) {+ shared, scratch := t.TempDir(), filepath.Join(t.TempDir(), "hermes-home")+ store := filepath.Join(t.TempDir(), "conversation")+ if _, err := prepareHermesHome(scratch, shared, false, nil, nil, "", "", testLogger()); err != nil {+ t.Fatal(err)}- mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")- mustWrite(t, filepath.Join(hermesHome, "state.db-wal"), "uncheckpointed tail")-- restore := stubHermesSessionLink(t, func(string, string) error {- return errors.New("symlink privilege not held")- })-- sessions, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())+ mustWrite(t, filepath.Join(scratch, "state.db"), "transcript")+ mustWrite(t, filepath.Join(scratch, "state.db-wal"), "uncheckpointed tail")+ prepared, err := prepareHermesHome(scratch, shared, false, nil, nil, "", store, testLogger())if err != nil {- t.Fatalf("prepare with unlinkable store: %v", err)- }- if sessions.Mounted || sessions.HistoryPresent {- t.Fatalf("mount = %+v, want both false when the link could not be created", sessions)- }-- // The database — and its un-checkpointed tail — must still be here.- for name, want := range map[string]string{- "state.db": "transcript",- "state.db-wal": "uncheckpointed tail",- } {- got, err := os.ReadFile(filepath.Join(hermesHome, name))- if err != nil {- t.Fatalf("%s was destroyed by a failed mount: %v", name, err)- }- if string(got) != want {- t.Fatalf("%s = %q, want %q", name, got, want)- }+ t.Fatal(err)}- if entries, err := os.ReadDir(store); err != nil {- t.Fatalf("read store: %v", err)- } else if len(entries) != 0 {- t.Fatalf("store holds %d entries after a failed mount, want 0", len(entries))+ if !prepared.Mounted || !prepared.HistoryPresent || prepared.Home != store {+ t.Fatalf("unexpected conversation home: %+v", prepared)}-- // And once the host can link again, the same overlay mounts and carries the- // database over — nothing was lost in between.- restore()- sessions, err = prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())- if err != nil {- t.Fatalf("prepare after link support returns: %v", err)- }- if !sessions.Mounted || !sessions.HistoryPresent {- t.Fatalf("mount = %+v, want mounted with history after recovery", sessions)+ if err := os.RemoveAll(scratch); err != nil {+ t.Fatal(err)}- got, err := os.ReadFile(filepath.Join(store, "state.db"))- if err != nil || string(got) != "transcript" {- t.Fatalf("store db = %q (err %v), want the preserved transcript", got, err)+ for name, want := range map[string]string{"state.db": "transcript", "state.db-wal": "uncheckpointed tail"} {+ got, err := os.ReadFile(filepath.Join(prepared.Home, name))+ if err != nil || string(got) != want {+ t.Fatalf("persistent %s = %q, %v; want %q", name, got, err, want)+ }}}@@ -514,7 +473,7 @@ func TestPrepareHermesHomeMountedEmptyStoreReportsNoHistory(t *testing.T) {if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {t.Fatalf("prepare first turn: %v", err)}- mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ mustWrite(t, filepath.Join(store, "state.db"), "transcript")sessions, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())if err != nil {@@ -825,26 +784,7 @@ func TestPrepareHermesHomeStoreCleanupHandlesUnexpectedEntryTypes(t *testing.T)})}-// stubHermesSessionLink swaps the symlink primitive for the duration of a test-// and returns a restore func, so a test can assert both the failure and the-// recovery in one run.-func stubHermesSessionLink(t *testing.T, fn func(target, link string) error) (restore func()) {- t.Helper()- prev := hermesSessionLink- hermesSessionLink = fn- restored := false- restore = func() {- if !restored {- hermesSessionLink = prev- restored = true- }- }- t.Cleanup(restore)- return restore-}--// stubHermesSessionCopy swaps the migration's copy primitive, same contract as-// stubHermesSessionLink.+// stubHermesSessionCopy injects migration failures until the returned restore runs.func stubHermesSessionCopy(t *testing.T, fn func(src, dst string) error) (restore func()) {t.Helper()prev := hermesSessionCopydiff --git a/server/pkg/agent/hermes_gateway.go b/server/pkg/agent/hermes_gateway.gonew file mode 100644index 0000000000..bfc1805a55--- /dev/null+++ b/server/pkg/agent/hermes_gateway.go@@ -0,0 +1,65 @@+package agent++import (+ "context"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"+)++// StopHermesTaskGateway retires the gateway of a daemon-created Hermes home.+// Gateway-backed ACP detaches its execution owner from the stdio process; it+// must exit before the next task inherits this conversation's home, otherwise+// tool shells retain the preceding task's credentials. In-process ACP creates+// no gateway records, so older Hermes versions need no extra invocation.+func StopHermesTaskGateway(cfg Config, home string) error {+ if home == "" || cfg.Env["HERMES_HOME"] != home {+ return nil+ }+ found := false+ for _, name := range []string{"gateway.pid", "gateway.lock"} {+ fi, err := os.Lstat(filepath.Join(home, name))+ if os.IsNotExist(err) {+ continue+ }+ if err != nil {+ return err+ }+ if !fi.Mode().IsRegular() {+ return fmt.Errorf("refusing to stop Hermes through non-local %s", name)+ }+ found = true+ }+ if !found {+ return nil+ }+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ stop := func(interrupt bool) ([]byte, error) {+ args := []string{"--profile", "default", "gateway", "stop"}+ if interrupt {+ args = append(args, "--yes")+ }+ cmd := cfg.commandAt(cfg.ExecutablePath).exec(ctx, args...)+ hideAgentWindow(cmd)+ cmd.Env = buildEnv(cfg.Env)+ cmd.Env = append(cmd.Env, "HERMES_DISABLE_LAZY_INSTALLS=1")+ return combinedOutputOwned(cmd, cfg.Logger)+ }+ output, err := stop(true)+ var exitErr *exec.ExitError+ if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 &&+ strings.HasSuffix(strings.TrimSpace(string(output)), "error: unrecognized arguments: --yes") {+ // Old in-process ACP has no interrupt flag. A downgraded conversation+ // can retain a gateway lock from a newer release; only retry parser errors.+ _, err = stop(false)+ }+ if err != nil {+ return fmt.Errorf("stop task Hermes gateway: %w", err)+ }+ return nil+}diff --git a/server/pkg/agent/hermes_gateway_unix_test.go b/server/pkg/agent/hermes_gateway_unix_test.gonew file mode 100644index 0000000000..7602849665--- /dev/null+++ b/server/pkg/agent/hermes_gateway_unix_test.go@@ -0,0 +1,93 @@+//go:build !windows++package agent++import (+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestStopHermesTaskGateway(t *testing.T) {+ home, tools := t.TempDir(), t.TempDir()+ record := filepath.Join(tools, "invocation")+ path := filepath.Join(tools, "hermes")+ writeTestExecutable(t, path, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" \"$HERMES_HOME\" > \"$RECORD\"\n"))+ cfg := Config{ExecutablePath: path, LaunchPrefix: []string{"wrapped"}, Logger: slog.Default(),+ Env: map[string]string{"HERMES_HOME": home, "RECORD": record}}+ if err := StopHermesTaskGateway(cfg, home); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(record); !os.IsNotExist(err) {+ t.Fatal("in-process ACP must not invoke gateway cleanup")+ }+ if err := os.WriteFile(filepath.Join(home, "gateway.lock"), []byte("owned gateway"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := StopHermesTaskGateway(cfg, home); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(record)+ if err != nil {+ t.Fatal(err)+ }+ if want := "wrapped\n--profile\ndefault\ngateway\nstop\n--yes\n" + home + "\n"; string(got) != want {+ t.Fatalf("cleanup invocation = %q, want %q", got, want)+ }+}++func TestStopHermesTaskGatewayRejectsHostState(t *testing.T) {+ home, host := t.TempDir(), t.TempDir()+ path := filepath.Join(host, "gateway.pid")+ if err := os.WriteFile(path, []byte("host gateway"), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(path, filepath.Join(home, "gateway.pid")); err != nil {+ t.Fatal(err)+ }+ cfg := Config{ExecutablePath: filepath.Join(home, "must-not-run"), Env: map[string]string{"HERMES_HOME": home}}+ if err := StopHermesTaskGateway(cfg, home); err == nil || !strings.Contains(err.Error(), "non-local") {+ t.Fatalf("cleanup through host PID link = %v, want refusal", err)+ }+}++func TestStopHermesTaskGatewayLegacyFlag(t *testing.T) {+ for _, tc := range []struct {+ name, output, code string+ wantCalls int+ wantErr bool+ }{+ {"unsupported flag", "hermes: error: unrecognized arguments: --yes", "2", 2, false},+ {"busy gateway", "Refusing to stop the gateway while sessions are live", "1", 1, true},+ {"other parser error", "hermes: error: unrecognized arguments: --profile", "2", 1, true},+ {"runtime error", "hermes: error: unrecognized arguments: --yes", "1", 1, true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ home, tools := t.TempDir(), t.TempDir()+ record, path := filepath.Join(tools, "invocation"), filepath.Join(tools, "hermes")+ writeTestExecutable(t, path, []byte("#!/bin/sh\nprintf '%s\\n' \"$@\" >> \"$RECORD\"\ncase \"$*\" in *--yes) printf '%s\\n' \"$STOP_ERROR\" >&2; exit \"$STOP_EXIT\";; esac\n"))+ if err := os.WriteFile(filepath.Join(home, "gateway.lock"), nil, 0o600); err != nil {+ t.Fatal(err)+ }+ cfg := Config{ExecutablePath: path, Logger: slog.Default(), Env: map[string]string{+ "HERMES_HOME": home, "RECORD": record, "STOP_ERROR": tc.output, "STOP_EXIT": tc.code,+ }}+ if err := StopHermesTaskGateway(cfg, home); (err != nil) != tc.wantErr {+ t.Fatalf("stop error = %v, wantErr=%v", err, tc.wantErr)+ }+ got, err := os.ReadFile(record)+ if err != nil {+ t.Fatal(err)+ }+ want := "--profile\ndefault\ngateway\nstop\n--yes\n"+ if tc.wantCalls == 2 {+ want += "--profile\ndefault\ngateway\nstop\n"+ }+ if string(got) != want {+ t.Fatalf("cleanup invocations = %q, want %q", got, want)+ }+ })+ }+}