Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6053: fix(daemon): give Hermes conversations a session that survives the task (#6845)
Bohan Jiang28a7176328e0
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 77a42a402a..79363fd841 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -260,6 +260,7 @@ Daemon behavior is configured via flags or environment variables:| GC repo cache TTL (`.repos`) | — | `MULTICA_GC_REPO_TTL` | `720h` (30d; set `0` to disable) || GC repo maintenance | — | `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` (set `false`/`0` to disable heavy Git maintenance only) || GC Hermes memory TTL (per-agent `memories/`) | — | `MULTICA_GC_HERMES_MEMORY_TTL` | `2160h` (90d; set `0` to disable) |+| GC Hermes session TTL (per-conversation `state.db`) | — | `MULTICA_GC_HERMES_SESSION_TTL` | `336h` (14d; set `0` to disable) |#### Workspace garbage collection@@ -274,6 +275,7 @@ The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk spaceShort worktree cleanup and eligible cache eviction continue on every GC cycle, including while agents are active. Heavy repo maintenance (`reflog expire` and `git gc`) starts only while the daemon is otherwise idle. A checkout or newly claimed task cancels it and takes priority; interrupted work remains pending for a later idle GC cycle. Operators can disable only these heavy commands with `MULTICA_GC_REPO_MAINTENANCE_ENABLED=false` without disabling worktree cleanup or cache eviction.+- **Hermes session store reclamation** — a conversation's Hermes transcript (`state.db`) lives at `<profile dir>/hermes-sessions/<agent-id>/<hermes-profile>/<conversation>/`, outside any task directory, so a follow-up turn can resume it (see [Hermes agent memory](#hermes-agent-memory)). A store untouched for `MULTICA_GC_HERMES_SESSION_TTL` is removed. The default matches the Codex session store rather than the memory store above: these hold full transcripts, and reclaiming an idle one costs a thread that starts fresh (with a continuity notice), not an agent that forgot what it learned. A store a running task holds is never reclaimed.- **Hermes memory store reclamation** — a Hermes agent's long-term memory (`memories/`) lives at `<profile dir>/hermes-state/<agent-id>/<hermes-profile>/`, outside any task directory, so it survives across tasks and issues (see [Hermes agent memory](#hermes-agent-memory)). A store untouched for `MULTICA_GC_HERMES_MEMORY_TTL` is removed, giving a deleted agent's memory an eventual-reclamation guarantee. The default is deliberately long: these are a handful of markdown files, and reclaiming one is user-visible amnesia rather than a cache miss. A store a running task holds is never reclaimed.Configured patterns are basename-only — entries containing `/` or `\` are silently dropped — and `.git` subtrees are never descended into. The managed Codex cache is matched by its exact relative path, so a repository's own `.sandbox-bin` is not removed unless an operator explicitly adds that basename to `MULTICA_GC_ARTIFACT_PATTERNS`. The default list (`node_modules`, `.next`, `.turbo`) is intentionally narrow; extend it per deployment if your repos consistently produce other regenerable directories (for example, `MULTICA_GC_ARTIFACT_PATTERNS=node_modules,.next,.turbo,target,__pycache__`). To disable artifact cleanup entirely, including the managed Codex cache, set `MULTICA_GC_ARTIFACT_TTL=0`.@@ -364,7 +366,7 @@ Consequences worth knowing:- **Memory is agent-scoped but runtime-local.** One agent's memory is never visible to another, and the user's own `~/.hermes/memories` is never read or written. The store lives in this runtime's Multica profile directory, so it does **not** follow the agent to another machine — an agent that runs on two runtimes has a separate memory line on each. Everything else in the home — auth, config, plugins — is still shared from the user's real home by symlink, so the agent does not need its own login.- **To carry existing local memory in**, copy it into the store once: `cp -R ~/.hermes/memories/. "<profile dir>/hermes-state/<agent-id>/default/"`. To wipe an agent's memory, delete that directory.-- **Session history is not covered.** `state.db` and its WAL sidecars stay task-local: sharing a live SQLite database across one agent's concurrent tasks needs lock and consistency handling (plus Windows byte-range locks on `-shm`) that plain memory files do not. The agent remembers accumulated notes, not previous transcripts.+- **Conversation history is covered too, in a separate store.** Hermes keeps every ACP session in `<HERMES_HOME>/state.db`, which the overlay links to a per-conversation store at `<profile dir>/hermes-sessions/<agent-id>/<hermes-profile>/<issue-id | chat_\<chat-session-id\>>/`, so a follow-up turn resumes the actual transcript. The shard is per conversation rather than per agent on purpose: tasks of one conversation run one after another, so a shard has a single writer at a time, while two issues never share a database. A host that cannot create the link (Windows without symlink privileges) keeps the database task-local instead, untouched — the link is proven creatable before anything is moved, and a copy is never used, because a copied SQLite database would absorb the turn's writes into a file the next task discards.- **Concurrent tasks of one agent are last-writer-wins.** Hermes rewrites its memory files whole, so two tasks writing memory at the same time can overwrite each other.- **Every Hermes agent gets the overlay in practice**, so every one of them gets a persistent memory store. The daemon builds the overlay only when a task carries skills, but the server appends Multica's built-in skills to every agent's skill set (`LoadAgentSkillBundles`), so that list is never empty — leaving an agent's own skill list empty does not opt out of the overlay, and is not a way to keep using the host's `~/.hermes/memories`.diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex bf9cd5d70e..35f4ac5f74 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -71,6 +71,7 @@ const (DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts once a task has been completed this longDefaultGCCodexSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-issue Codex session stores untouched this longDefaultGCHermesMemoryTTL = 90 * 24 * time.Hour // 90 days — reclaim per-agent Hermes memory stores untouched this long (long: reclaiming these is visible amnesia, and they are a few markdown files)+ DefaultGCHermesSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-conversation Hermes session stores untouched this long (matches Codex: these hold transcripts, and losing an idle one restarts the thread rather than the agent's notes)DefaultGCRepoTTL = 30 * 24 * time.Hour // 30 days — evict a bare repo cache no task has checked out this longDefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release)@@ -108,6 +109,7 @@ type Config struct {GCRepoMaintenanceEnabled bool // run reflog expiry and git gc after stale agent refs are removed (default: true; disable independently as an operational kill switch)GCCodexSessionTTL time.Duration // reclaim a per-issue Codex session store (~/.codex/multica-sessions/<agent>/<issue>) untouched for at least this long, so a done/abandoned issue's conversation history does not accumulate forever (default: 14d, set 0 to disable)GCHermesMemoryTTL time.Duration // reclaim a per-agent Hermes memory store (<profile dir>/hermes-state/<agent>/<profile>) untouched for at least this long, so a deleted agent's memory does not sit on disk forever (default: 90d, set 0 to disable)+ GCHermesSessionTTL time.Duration // reclaim a per-conversation Hermes session store (<profile dir>/hermes-sessions/<agent>/<profile>/<conversation>) untouched for at least this long, so a done or abandoned conversation's transcript does not accumulate forever (default: 14d, set 0 to disable)AutoUpdateEnabled bool // periodically check for a newer CLI release and self-update when idle (default: true on Multica Cloud, false on self-host)AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)AutoReloadEnabled bool // restart when the multica binary on disk no longer matches the running version (default: true for CLI-launched daemons)@@ -427,6 +429,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ gcHermesSessionTTL, err := durationFromEnv("MULTICA_GC_HERMES_SESSION_TTL", DefaultGCHermesSessionTTL)+ if err != nil {+ return Config{}, err+ }gcRepoTTL, err := durationFromEnv("MULTICA_GC_REPO_TTL", DefaultGCRepoTTL)if err != nil {return Config{}, err@@ -486,6 +492,7 @@ func LoadConfig(overrides Overrides) (Config, error) {GCRepoMaintenanceEnabled: gcRepoMaintenanceEnabled,GCCodexSessionTTL: gcCodexSessionTTL,GCHermesMemoryTTL: gcHermesMemoryTTL,+ GCHermesSessionTTL: gcHermesSessionTTL,AutoUpdateEnabled: autoUpdateEnabled,AutoUpdateCheckInterval: autoUpdateInterval,AutoReloadEnabled: autoReloadEnabled,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex a0f8218714..c4fe9071f6 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5352,23 +5352,37 @@ func providerNeedsInlineSystemPrompt(provider string) bool {}}-// gateResumeToReusedWorkdir clears the task's prior session unless the task-// runs in the exact workdir the session was recorded against, and reports-// whether that workdir was reused. CLI backends key their session stores to-// the cwd (Claude Code looks sessions up under ~/.claude/projects/<encoded-cwd>/),-// so a session id from a different workdir can never resolve: the CLI exits-// within a second and the run fails before doing any work — permanently,-// because the failed run records no session and the next claim serves the-// same stale pointer again. This fires whenever the prior workdir no longer-// exists (GC'd after the issue went done, daemon reinstall, manual cleanup)-// and execenv.Reuse fell back to a fresh Prepare (GitHub #3854).-func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, envWorkDir string, taskLog *slog.Logger) bool {- reused := task.PriorWorkDir != "" && envWorkDir == task.PriorWorkDir+// gateResumeToReusedWorkdir clears the task's prior session unless this run+// can actually reach the store the session lives in, and reports whether that+// held. CLI backends key their session stores to the cwd (Claude Code looks+// sessions up under ~/.claude/projects/<encoded-cwd>/), so a session id from a+// different workdir can never resolve: the CLI exits within a second and the+// run fails before doing any work — permanently, because the failed run+// records no session and the next claim serves the same stale pointer again.+// This fires whenever the prior workdir no longer exists (GC'd after the issue+// went done, daemon reinstall, manual cleanup) and execenv.Reuse fell back to a+// fresh Prepare (GitHub #3854).+//+// A matching workdir is not sufficient on its own. Hermes keys its sessions to+// HERMES_HOME — the per-task overlay under envRoot — not to the cwd, and the+// two keys come apart precisely in the local_directory flow: reuse is disabled+// there (shouldReusePriorWorkdir), so every task builds a fresh overlay with an+// empty state.db, while envWorkDir stays the user's own directory and therefore+// still equals PriorWorkDir. The gate read "reused" and forwarded a session id+// that could not possibly resolve, and Hermes answers an unresolvable resume by+// silently starting over (GH #6806). sessionHomeReachable is the provider's own+// answer to "can a prior session still be found here?" — for Hermes, whether+// the conversation's session store got mounted (execenv.Environment+// HermesSessionStore) — and false drops the resume with the same disclosure as+// a workdir mismatch.+func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, envWorkDir string, sessionHomeReachable bool, taskLog *slog.Logger) bool {+ reused := task.PriorWorkDir != "" && envWorkDir == task.PriorWorkDir && sessionHomeReachableif !reused && task.PriorSessionID != "" {- taskLog.Info("dropping prior session: workdir not reused, per-cwd session cannot resolve",+ taskLog.Info("dropping prior session: session store not reachable from this run","session_id", task.PriorSessionID,"prior_workdir", task.PriorWorkDir,"workdir", envWorkDir,+ "session_home_reachable", sessionHomeReachable,)task.PriorSessionID = ""taskCtx.PriorSessionResumed = false@@ -5382,6 +5396,38 @@ func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, ereturn reused}+// sessionHomeReachable reports whether a session recorded by a prior task on+// this conversation can still be found from THIS run's environment, for+// providers that key their sessions somewhere other than the cwd.+//+// Only Hermes does today: its transcripts live in `<HERMES_HOME>/state.db`,+// which is the per-task overlay under envRoot. Forwarding a session id into a+// database that does not hold it is what produced a conversation restarting+// from zero every turn (GH #6806), so the question has to be about the+// database, not about the plumbing:+//+// - With the conversation's session store mounted, the answer is whether that+// store actually holds a transcript. A mount onto an empty store is the+// normal shape of a first turn — and also of a store the GC reclaimed+// between turns, a switched Hermes profile, or a dangling link left by an+// older overlay. Reading "mounted" as "resumable" would forward a dead id+// into every one of those.+// - With no store, the transcript is the overlay's own task-local file, which+// survives exactly when this run reused the prior task's env root.+//+// Every other provider is keyed by cwd (or resolves its own store), so the+// workdir comparison in gateResumeToReusedWorkdir remains the whole answer and+// this returns true.+func sessionHomeReachable(provider string, env *execenv.Environment, envReused bool) bool {+ if provider != "hermes" {+ return true+ }+ if env.HermesSessionStore != "" {+ return env.HermesSessionHistoryPresent+ }+ return envReused+}+// shouldReusePriorWorkdir keeps the local_directory lock invariant without// forcing every squad-leader follow-up onto a fresh provider session. Worker// tasks already expose their current local-directory assignment, so their@@ -6022,6 +6068,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar hermesSourceMustExist boolvar hermesEnv map[string]stringvar hermesMemoryStore string+ var hermesSessionStore stringif provider == "hermes" {sel := agent.ParseHermesProfileArgs(agentCustomArgs)res := execenv.ResolveHermesProfile(agentEnvOverrides["HERMES_HOME"], sel.Name, sel.Found, sel.Inline)@@ -6045,6 +6092,17 @@ 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+ // 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+ // writer, while two issues never share a database. Guarded from the GC+ // for the whole task, as the stores above and below.+ if store := execenv.HermesSessionStorePath(d.cfg.Profile, task.AgentID, res.SourceHome, taskCtx); store != "" {+ hermesSessionStore = store+ d.markActiveStore(store)+ defer d.unmarkActiveStore(store)+ }}// Reasonix locates its user config from the environment (REASONIX_HOME, and// the platform config dirs behind it), which an agent's custom_env may@@ -6066,6 +6124,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot idefer d.unmarkActiveStore(store)}}+ envReused := falseif shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot) {var err errorenv, err = d.reuseExecutionEnvironment(prepareCtx, execenv.ReuseParams{@@ -6083,6 +6142,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iHermesSourceMustExist: hermesSourceMustExist,HermesEnv: hermesEnv,HermesMemoryStore: hermesMemoryStore,+ HermesSessionStore: hermesSessionStore,ReasonixEnv: reasonixEnv,CodexCustomArgs: codexSandboxArgs,Task: taskCtx,@@ -6090,6 +6150,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif err != nil {return TaskResult{}, fmt.Errorf("reuse execution environment: %w", err)}+ // Reuse can decline (nil) and fall through to a fresh Prepare below.+ // Whether it did decides whether an env-root-scoped session store — the+ // Hermes overlay's task-local state.db — carried over from the prior task.+ envReused = env != nil}if env == nil {var err error@@ -6109,6 +6173,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iHermesSourceMustExist: hermesSourceMustExist,HermesEnv: hermesEnv,HermesMemoryStore: hermesMemoryStore,+ HermesSessionStore: hermesSessionStore,ReasonixEnv: reasonixEnv,CodexCustomArgs: codexSandboxArgs,Task: taskCtx,@@ -6157,7 +6222,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot icancelPrepare()_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)- reused := gateResumeToReusedWorkdir(&task, &taskCtx, env.WorkDir, taskLog)+ reused := gateResumeToReusedWorkdir(&task, &taskCtx, env.WorkDir, sessionHomeReachable(provider, env, envReused), taskLog)// A reused workdir is necessary but not sufficient for a Codex resume: the// prior thread's rollout must actually be present in this task's CODEX_HOME// sessions (MUL-4424 isolates them). Drop the resume before the brief isdiff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex bc03525a16..c0c93cb37e 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1934,12 +1934,17 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {t.Parallel()tests := []struct {- name string- sessionID string- priorDir string- envDir string- wantSession string- wantReused bool+ name string+ sessionID string+ priorDir string+ envDir string+ // sessionHomeUnreachable models a provider whose session store this run+ // cannot reach even though the workdir matches — the Hermes+ // local_directory case (GH #6806). Zero value keeps the cwd-keyed+ // providers' behaviour.+ sessionHomeUnreachable bool+ wantSession string+ wantReused bool}{{name: "same workdir keeps session",@@ -1973,6 +1978,19 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {wantSession: "",wantReused: false,},+ {+ // The local_directory flow: workdir is the user's own directory+ // and therefore identical across tasks, but reuse is disabled so+ // the session store is a fresh, empty one. Forwarding the id here+ // is what made every turn silently restart the conversation.+ name: "matching workdir but unreachable session store drops session",+ sessionID: "sess-1",+ priorDir: "/repo",+ envDir: "/repo",+ sessionHomeUnreachable: true,+ wantSession: "",+ wantReused: false,+ },}for _, tt := range tests {@@ -1980,7 +1998,7 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {task := Task{PriorSessionID: tt.sessionID, PriorWorkDir: tt.priorDir}taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: tt.sessionID != ""}- reused := gateResumeToReusedWorkdir(&task, &taskCtx, tt.envDir, slog.Default())+ reused := gateResumeToReusedWorkdir(&task, &taskCtx, tt.envDir, !tt.sessionHomeUnreachable, slog.Default())if reused != tt.wantReused {t.Fatalf("reused = %v, want %v", reused, tt.wantReused)@@ -2001,6 +2019,79 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {}}+func TestSessionHomeReachable(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ provider string+ env *execenv.Environment+ envReused bool+ wantReturn bool+ }{+ {+ // Every non-Hermes backend keys its sessions by cwd (or resolves+ // its own store), so this predicate must not narrow their gate.+ name: "cwd-keyed provider is always reachable",+ provider: "claude",+ env: &execenv.Environment{},+ wantReturn: true,+ },+ {+ name: "hermes with a mounted store holding history",+ provider: "hermes",+ env: &execenv.Environment{+ HermesSessionStore: "/profile/hermes-sessions/a/default/issue-1",+ HermesSessionHistoryPresent: true,+ },+ wantReturn: true,+ },+ {+ // Mounted onto nothing: a first turn, a store the GC reclaimed+ // between turns, a switched profile, or a dangling link. Reading+ // "mounted" as "resumable" here would forward a dead session id.+ name: "hermes with a mounted but empty session store",+ provider: "hermes",+ env: &execenv.Environment{HermesSessionStore: "/profile/hermes-sessions/a/default/issue-1"},+ wantReturn: false,+ },+ {+ // A store is mounted, so the env-reuse fallback must not override+ // the store's own answer — the transcript lives in the store now.+ name: "hermes with an empty store is not rescued by env reuse",+ provider: "hermes",+ env: &execenv.Environment{HermesSessionStore: "/profile/hermes-sessions/a/default/issue-1"},+ envReused: true,+ wantReturn: false,+ },+ {+ // No store, but the prior task's env root — and therefore its+ // overlay's task-local state.db — carried over.+ name: "hermes on a reused env root",+ provider: "hermes",+ env: &execenv.Environment{},+ envReused: true,+ wantReturn: true,+ },+ {+ // The GH #6806 shape: a fresh overlay with an empty state.db, so+ // no session recorded by a prior task can be found here.+ name: "hermes on a fresh overlay with no store",+ provider: "hermes",+ env: &execenv.Environment{},+ wantReturn: false,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := sessionHomeReachable(tt.provider, tt.env, tt.envReused); got != tt.wantReturn {+ t.Fatalf("sessionHomeReachable() = %v, want %v", got, tt.wantReturn)+ }+ })+ }+}+// newCodexStoreGuardDaemon builds a Daemon with only the per-issue Codex session// store guard initialised — enough to exercise the reserve-vs-mark protocol.func newCodexStoreGuardDaemon() *Daemon {diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 6c4fd577a7..f1e88e6a53 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -82,6 +82,12 @@ type PrepareParams struct {// the task. Empty keeps memories/ task-local — no agent to key on, or the// 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+ // 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.+ HermesSessionStore string// 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.@@ -264,6 +270,19 @@ 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 string+ // HermesSessionHistoryPresent reports that the mounted store actually holds+ // a session database — a prior turn's transcript this task can resume.+ // Mounting alone does not imply it: a conversation's first turn, a store the+ // GC reclaimed between turns, a switched Hermes profile and an operator's+ // `rm` all mount cleanly onto nothing. The daemon reads THIS, not the store+ // path, as the answer to "can a prior session id still resolve here?" — see+ // gateResumeToReusedWorkdir.+ HermesSessionHistoryPresent bool// QwenpawWorkspace is the path to the per-task QwenPaw workspace directory// (set only for the qwenpaw provider). It is populated with the bound skills// and their skill.json manifest with enabled: true, so the skills are@@ -415,10 +434,15 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {// Emptying an agent's own skill list is NOT a way to opt out of the overlay.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, params.HermesMemoryStore, logger); err != nil {+ sessions, err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, params.HermesSessionStore, logger)+ if err != nil {return nil, fmt.Errorf("execenv: prepare hermes-home: %w", err)}env.HermesHome = hermesHome+ if sessions.Mounted {+ env.HermesSessionStore = params.HermesSessionStore+ env.HermesSessionHistoryPresent = sessions.HistoryPresent+ }}if params.Provider == "qwenpaw" {qwenpawWorkspace := filepath.Join(envRoot, "qwenpaw-workspace")@@ -518,13 +542,15 @@ type ReuseParams struct {// loop) keep the "never delete the user's directory" invariant on// reuse paths.LocalDirectory bool- // HermesSourceHome, HermesEnv and HermesMemoryStore mirror PrepareParams on- // reuse so the Hermes overlay re-derives against the agent's current source- // home / profile, external_dirs vars, and memory store.+ // HermesSourceHome, HermesEnv, HermesMemoryStore and HermesSessionStore+ // mirror PrepareParams on reuse so the Hermes overlay re-derives against the+ // agent's current source home / profile, external_dirs vars, memory store and+ // conversation session store.HermesSourceHome stringHermesSourceMustExist boolHermesEnv map[string]stringHermesMemoryStore string+ HermesSessionStore string// ReasonixEnv mirrors PrepareParams.ReasonixEnv on reuse so the rewritten// reasonix.toml keeps restating the owner's current permissions.ReasonixEnv map[string]string@@ -686,7 +712,8 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {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, params.HermesMemoryStore, logger); err != nil {+ sessions, err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, params.HermesSessionStore, logger)+ if 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@@ -695,8 +722,16 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {return nil}env.HermesHome = hermesHome+ env.HermesSessionStore = ""+ env.HermesSessionHistoryPresent = false+ if sessions.Mounted {+ env.HermesSessionStore = params.HermesSessionStore+ env.HermesSessionHistoryPresent = sessions.HistoryPresent+ }} else {env.HermesHome = ""+ env.HermesSessionStore = ""+ env.HermesSessionHistoryPresent = falseif err := os.RemoveAll(hermesHome); err != nil {logger.Warn("execenv: remove stale hermes-home failed", "error", err)}diff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.goindex d95ebf6dd4..3acc7d5597 100644--- a/server/internal/daemon/execenv/hermes_home.go+++ b/server/internal/daemon/execenv/hermes_home.go@@ -47,8 +47,11 @@ import (// the agent's persistent store so it survives across tasks and issues// (hermes_memory.go); it is a fresh per-task dir only when no store applies;// - keeps the state.db SQLite session store and its journal sidecars-// overlay-owned too: Hermes creates them lazily, Reuse preserves them for-// the task, and host conversation history is never linked or copied;+// overlay-owned: the host's conversation history is never linked or copied.+// state.db is then linked to the conversation's own persistent store+// (hermes_sessions.go) so a multi-turn conversation survives the task; it+// stays a task-local file only when there is no store to key on, or on a+// host that cannot create the link;// - 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,@@ -370,50 +373,69 @@ func hermesProfileDir(root, name string) (home string, mustExist bool, err error// sanitized effective env used to expand ${VAR} in external_dirs so it matches// 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.-func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, memoryStore string, logger *slog.Logger) error {+// 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+// 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)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)+ return hermesSessionMount{}, 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)+ return hermesSessionMount{}, 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)+ return hermesSessionMount{}, fmt.Errorf("chmod hermes-home dir: %w", err)}if err := prepareHermesTaskLocalState(hermesHome); err != nil {- return fmt.Errorf("prepare task-local state: %w", err)+ 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}// 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// agent to key on, or an unresolvable profile dir). See hermes_memory.go.if memoryStore != "" {if err := mountHermesMemories(hermesHome, memoryStore, logger); err != nil {- return fmt.Errorf("mount agent memories: %w", err)+ return hermesSessionMount{}, fmt.Errorf("mount agent memories: %w", err)}} else if err := detachHermesMemories(hermesHome); err != nil {- return fmt.Errorf("create task memories dir: %w", err)+ return hermesSessionMount{}, 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)+ return hermesSessionMount{}, 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)+ return hermesSessionMount{}, fmt.Errorf("derive hermes config: %w", err)}if err := writeDerivedHermesEnv(sharedHome, hermesHome); err != nil {- return fmt.Errorf("derive hermes .env: %w", err)+ return hermesSessionMount{}, fmt.Errorf("derive hermes .env: %w", err)+ }+ if err := writeHermesBoundSkills(hermesHome, workspaceSkills, logger); err != nil {+ return hermesSessionMount{}, err}- return writeHermesBoundSkills(hermesHome, workspaceSkills, logger)+ return sessions, nil}// writeDerivedHermesEnv writes the task-local .env: the source home's .envdiff --git a/server/internal/daemon/execenv/hermes_home_test.go b/server/internal/daemon/execenv/hermes_home_test.goindex 7af492ac11..0fd28d0c5f 100644--- a/server/internal/daemon/execenv/hermes_home_test.go+++ b/server/internal/daemon/execenv/hermes_home_test.go@@ -65,7 +65,7 @@ func TestPrepareHermesHomeOverlay(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -129,7 +129,7 @@ func TestHermesDisablesExternalMemoryProvider(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -157,7 +157,7 @@ func TestHermesDerivedConfigRebasesRelativeExternalDirs(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -185,7 +185,7 @@ func TestHermesExternalDirsExpandsSanitizedEnv(t *testing.T) {hermesHome := filepath.Join(t.TempDir(), "hermes-home")env := map[string]string{"TEAM_SKILLS": "/srv/team"} // MYSTERY_VAR set nowhereskills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, env, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, env, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -211,7 +211,7 @@ func TestHermesBoundSkillKeepsNaturalSlug(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -238,7 +238,7 @@ func TestHermesOverlayIsolatesMemories(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -256,7 +256,7 @@ func TestHermesOverlayIsolatesMemories(t *testing.T) {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 {+ 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" {@@ -279,7 +279,7 @@ func TestHermesOverlayKeepsSessionDatabaseTaskLocal(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}for _, name := range stateFiles {@@ -290,7 +290,7 @@ func TestHermesOverlayKeepsSessionDatabaseTaskLocal(t *testing.T) {mustWrite(t, filepath.Join(sharedHome, name), "UPDATED HOST "+name)}- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome (reuse) failed: %v", err)}for _, name := range stateFiles {@@ -330,7 +330,7 @@ func TestHermesOverlayMigratesLegacySessionDatabase(t *testing.T) {mustWrite(t, walPath, "LEGACY COPY state.db-wal")}skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}for _, name := range stateFiles {@@ -347,7 +347,7 @@ func TestHermesOverlayMigratesLegacySessionDatabase(t *testing.T) {}mustWrite(t, filepath.Join(hermesHome, "state.db"), "TASK DB")- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome (reuse) failed: %v", err)}if data, err := os.ReadFile(filepath.Join(hermesHome, "state.db")); err != nil {@@ -366,7 +366,7 @@ func TestHermesOverlayPermissions(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -397,7 +397,7 @@ func TestHermesOverlayReconcilesDeletedSharedEntry(t *testing.T) {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 {+ 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 {@@ -406,7 +406,7 @@ func TestHermesOverlayReconcilesDeletedSharedEntry(t *testing.T) {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 {+ 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) {@@ -424,7 +424,7 @@ func TestPrepareHermesHomeFailsClosed(t *testing.T) {}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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err == nil {t.Fatal("expected prepareHermesHome to fail closed on an unreadable shared config")}}@@ -554,7 +554,7 @@ func TestHermesExternalDirsExpandsAgainstSelectedProfileHome(t *testing.T) {hermesHome := filepath.Join(t.TempDir(), "hermes-home")env := map[string]string{"HERMES_HOME": profileHome} // as the daemon sets itskills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}- if err := prepareHermesHome(hermesHome, profileHome, true, skills, env, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, profileHome, true, skills, env, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -582,7 +582,7 @@ func TestHermesOverlayEnvPinsHomeAfterDotenvOverride(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sourceHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}@@ -618,7 +618,7 @@ func TestHermesOverlayEnvCreatedWhenSourceHasNone(t *testing.T) {sourceHome := t.TempDir() // no .env presenthermesHome := filepath.Join(t.TempDir(), "hermes-home")skills := []SkillContextForEnv{{Name: "Review Helper", Content: "x"}}- if err := prepareHermesHome(hermesHome, sourceHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sourceHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}env := applyDotenvOverride(t, filepath.Join(hermesHome, ".env"))@@ -721,7 +721,7 @@ func TestHermesOverlayDoesNotMirrorStickyProfile(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepareHermesHome failed: %v", err)}for _, name := range []string{"active_profile", "profiles"} {@@ -741,7 +741,7 @@ func TestPrepareHermesHomeFailsOnMissingNamedProfile(t *testing.T) {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 {+ if _, err := prepareHermesHome(hermesHome, missingProfileHome, true, skills, nil, "", "", testLogger()); err == nil {t.Fatal("expected a missing named profile home to fail closed")}}diff --git a/server/internal/daemon/execenv/hermes_memory.go b/server/internal/daemon/execenv/hermes_memory.goindex 430150ec3d..b8a326670f 100644--- a/server/internal/daemon/execenv/hermes_memory.go+++ b/server/internal/daemon/execenv/hermes_memory.go@@ -225,7 +225,7 @@ func migrateHermesTaskMemories(taskDir, storeDir string, logger *slog.Logger) erreturn nil}- staging, err := newHermesMemoryStaging(storeDir)+ staging, err := newHermesStoreStaging(storeDir)if err != nil {return err}@@ -238,7 +238,7 @@ func migrateHermesTaskMemories(taskDir, storeDir string, logger *slog.Logger) er}}- promoted, err := promoteHermesMemoryStaging(staging, storeDir)+ promoted, err := promoteHermesStoreStaging(staging, storeDir, hermesStorePopulated)if err != nil {return err}@@ -250,12 +250,15 @@ func migrateHermesTaskMemories(taskDir, storeDir string, logger *slog.Logger) erreturn nil}-// newHermesMemoryStaging creates the scratch directory the migration copies+// newHermesStoreStaging creates the scratch directory a store migration copies// into. It is a sibling of the store so the promoting rename stays within one-// filesystem, and dot-prefixed so it is obvious it is not a profile's store.+// filesystem, and dot-prefixed so it is obvious it is not a store of its own.+// Shared by the memory migration here and the session-database migration in+// hermes_sessions.go: both delete their source once the copy reports success,+// so both need the same all-or-nothing publish.// MkdirTemp already creates it 0700, the same mode the store itself is created// with, so there is no follow-up chmod that could fail and strand it.-func newHermesMemoryStaging(storeDir string) (string, error) {+func newHermesStoreStaging(storeDir string) (string, error) {parent := filepath.Dir(storeDir)if err := os.MkdirAll(parent, 0o700); err != nil {return "", fmt.Errorf("create hermes memory store parent %s: %w", parent, err)@@ -267,39 +270,48 @@ func newHermesMemoryStaging(storeDir string) (string, error) {return staging, nil}-// promoteHermesMemoryStaging publishes a fully-copied staging dir as the store,+// promoteHermesStoreStaging publishes a fully-copied staging dir as the store,// reporting whether this caller won. The empty store dir (if any) is removed// first: os.Remove only succeeds on an empty directory, so a store another task// already populated makes this a no-op, and Windows rejects a rename onto an// existing directory outright.//// Losing the race is not an error — the winner's store holds the same agent's-// memory — but it has to be positively confirmed, never inferred from any+// state — but it has to be positively confirmed, never inferred from any// failure. The caller deletes the source directory whenever this returns// (false, nil), so a permission error, a read-only filesystem or a Windows// sharing violation must fail closed instead of passing for "someone else// published".-func promoteHermesMemoryStaging(staging, storeDir string) (bool, error) {+//+// published answers "did a competitor already publish real state here?" and is+// the caller's to define, because the two stores disagree about what an+// occupied directory looks like: any entry at all means memory, while a session+// store can hold a zero-length database or orphan journal sidecars that carry no+// transcript. Sharing one definition let a session migration read the store as+// empty, copy into staging, then read it as occupied at publish time and report+// a lost race — after which the caller deleted a source database that had never+// been carried over.+func promoteHermesStoreStaging(staging, storeDir string, published func(string) bool) (bool, error) {if err := os.Remove(storeDir); err != nil && !os.IsNotExist(err) {- if hermesMemoryStorePopulated(storeDir) {- return false, nil // non-empty: another task published first+ if published(storeDir) {+ return false, nil // another task published first}- return false, fmt.Errorf("clear empty hermes memory store %s before publishing: %w", storeDir, err)+ return false, fmt.Errorf("clear empty hermes store %s before publishing: %w", storeDir, err)}if err := os.Rename(staging, storeDir); err != nil {- if hermesMemoryStorePopulated(storeDir) {+ if published(storeDir) {return false, nil // lost a narrow race between the remove and the rename}- return false, fmt.Errorf("publish hermes memory store %s: %w", storeDir, err)+ return false, fmt.Errorf("publish hermes store %s: %w", storeDir, err)}return true, nil}-// hermesMemoryStorePopulated reports whether storeDir is *confirmed* to hold+// hermesStorePopulated reports whether storeDir is *confirmed* to hold// entries. Anything it cannot confirm — an unreadable directory, a path that is// not a directory — is false, so a caller asking "did another task publish?"// treats uncertainty as no.-func hermesMemoryStorePopulated(storeDir string) bool {+func hermesStorePopulated(storeDir string) bool {entries, err := os.ReadDir(storeDir)return err == nil && len(entries) > 0}diff --git a/server/internal/daemon/execenv/hermes_memory_test.go b/server/internal/daemon/execenv/hermes_memory_test.goindex 8f260bda2e..6bfcc5ea6d 100644--- a/server/internal/daemon/execenv/hermes_memory_test.go+++ b/server/internal/daemon/execenv/hermes_memory_test.go@@ -87,14 +87,14 @@ func TestPrepareHermesHomeMemoryStorePersistsAcrossTasks(t *testing.T) {skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}firstTask := filepath.Join(t.TempDir(), "hermes-home")- if err := prepareHermesHome(firstTask, sharedHome, false, skills, nil, store, testLogger()); err != nil {+ if _, err := prepareHermesHome(firstTask, sharedHome, false, skills, nil, store, "", testLogger()); err != nil {t.Fatalf("prepare first task: %v", err)}// Hermes writes memory back into <HERMES_HOME>/memories during the run.mustWrite(t, filepath.Join(firstTask, "memories", "MEMORY.md"), "prefers tabs")secondTask := filepath.Join(t.TempDir(), "hermes-home")- if err := prepareHermesHome(secondTask, sharedHome, false, skills, nil, store, testLogger()); err != nil {+ if _, err := prepareHermesHome(secondTask, sharedHome, false, skills, nil, store, "", testLogger()); err != nil {t.Fatalf("prepare second task: %v", err)}got, err := os.ReadFile(filepath.Join(secondTask, "memories", "MEMORY.md"))@@ -125,13 +125,13 @@ func TestPrepareHermesHomeMemoryStoreIsolatesAgents(t *testing.T) {skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}homeA := filepath.Join(t.TempDir(), "hermes-home")- if err := prepareHermesHome(homeA, sharedHome, false, skills, nil, filepath.Join(stateRoot, "agent-a", "default"), testLogger()); err != nil {+ if _, err := prepareHermesHome(homeA, sharedHome, false, skills, nil, filepath.Join(stateRoot, "agent-a", "default"), "", testLogger()); err != nil {t.Fatalf("prepare agent A: %v", err)}mustWrite(t, filepath.Join(homeA, "memories", "MEMORY.md"), "agent A secret")homeB := filepath.Join(t.TempDir(), "hermes-home")- if err := prepareHermesHome(homeB, sharedHome, false, skills, nil, filepath.Join(stateRoot, "agent-b", "default"), testLogger()); err != nil {+ if _, err := prepareHermesHome(homeB, sharedHome, false, skills, nil, filepath.Join(stateRoot, "agent-b", "default"), "", testLogger()); err != nil {t.Fatalf("prepare agent B: %v", err)}if _, err := os.Stat(filepath.Join(homeB, "memories", "MEMORY.md")); !os.IsNotExist(err) {@@ -148,7 +148,7 @@ func TestPrepareHermesHomeWithoutStore(t *testing.T) {hermesHome := filepath.Join(t.TempDir(), "hermes-home")skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepare: %v", err)}fi, err := os.Lstat(filepath.Join(hermesHome, "memories"))@@ -177,13 +177,13 @@ func TestPrepareHermesHomeWithoutStoreDetachesExistingStoreLink(t *testing.T) {skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}// Run once with the store mounted.- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, store, testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, store, "", testLogger()); err != nil {t.Fatalf("prepare with store: %v", err)}mustWrite(t, filepath.Join(hermesHome, "memories", "MEMORY.md"), "persistent memory")// The same overlay is reused by a task that resolves no store.- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepare without store: %v", err)}@@ -213,12 +213,12 @@ func TestPrepareHermesHomeWithoutStoreKeepsTaskLocalMemories(t *testing.T) {hermesHome := filepath.Join(t.TempDir(), "hermes-home")skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("first prepare: %v", err)}mustWrite(t, filepath.Join(hermesHome, "memories", "MEMORY.md"), "task memory")- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("reuse prepare: %v", err)}if _, err := os.Stat(filepath.Join(hermesHome, "memories", "MEMORY.md")); err != nil {@@ -416,7 +416,7 @@ func TestPromoteHermesMemoryStagingClassifiesRemoveFailures(t *testing.T) {staging := filepath.Join(parent, ".default.migrating-x")mustWrite(t, filepath.Join(staging, "MEMORY.md"), "loser")- promoted, err := promoteHermesMemoryStaging(staging, storeDir)+ promoted, err := promoteHermesStoreStaging(staging, storeDir, hermesStorePopulated)if err != nil {t.Fatalf("a populated store should be a lost race, not an error: %v", err)}@@ -448,7 +448,7 @@ func TestPromoteHermesMemoryStagingClassifiesRemoveFailures(t *testing.T) {}t.Cleanup(func() { _ = os.Chmod(parent, 0o700) })- promoted, err := promoteHermesMemoryStaging(staging, storeDir)+ promoted, err := promoteHermesStoreStaging(staging, storeDir, hermesStorePopulated)if promoted {t.Fatalf("promote reported success against an unremovable store")}@@ -492,13 +492,13 @@ func TestPrepareHermesHomeMigratesTaskLocalMemories(t *testing.T) {skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}// Simulate the old layout: a task-local memories dir with accumulated state.- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepare pre-store overlay: %v", err)}mustWrite(t, filepath.Join(hermesHome, "memories", "MEMORY.md"), "carried over")store := filepath.Join(t.TempDir(), "hermes-state", "agent-1", "default")- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, store, testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, store, "", testLogger()); err != nil {t.Fatalf("prepare with store: %v", err)}got, err := os.ReadFile(filepath.Join(store, "MEMORY.md"))@@ -519,7 +519,7 @@ func TestPrepareHermesHomeMigrationKeepsExistingStore(t *testing.T) {hermesHome := filepath.Join(t.TempDir(), "hermes-home")skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {t.Fatalf("prepare pre-store overlay: %v", err)}mustWrite(t, filepath.Join(hermesHome, "memories", "MEMORY.md"), "stale task copy")@@ -527,7 +527,7 @@ func TestPrepareHermesHomeMigrationKeepsExistingStore(t *testing.T) {store := filepath.Join(t.TempDir(), "hermes-state", "agent-1", "default")mustWrite(t, filepath.Join(store, "MEMORY.md"), "authoritative agent memory")- if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, store, testLogger()); err != nil {+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, store, "", testLogger()); err != nil {t.Fatalf("prepare with store: %v", err)}got, err := os.ReadFile(filepath.Join(store, "MEMORY.md"))diff --git a/server/internal/daemon/execenv/hermes_sessions.go b/server/internal/daemon/execenv/hermes_sessions.gonew file mode 100644index 0000000000..140ccac15f--- /dev/null+++ b/server/internal/daemon/execenv/hermes_sessions.go@@ -0,0 +1,482 @@+package execenv++import (+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "sync"+ "time"++ "github.com/multica-ai/multica/server/internal/cli"+)++// Background+//+// Hermes persists every ACP session — the actual conversation transcript — in+// the SQLite database at `<HERMES_HOME>/state.db` (acp_adapter/session.py).+// Because Multica has to take over HERMES_HOME to inject bound skills, that+// database landed inside the per-task overlay, which made a Hermes agent's+// conversation last exactly one task.+//+// The failure was silent, which is what made it expensive. `session/resume`+// against a database that does not hold the session does not fail: Hermes+// creates a fresh session and answers with an ordinary success frame+// (acp_adapter/server.py resume_session), so the daemon believed it had+// resumed, re-sent the same dead id on every later turn, and the user saw a+// conversation that restarted from zero with nothing in the logs (GH #6806).+// The backend now detects that rebind (resolveHermesResumedSessionID), and+// this file removes the cause.+//+// The store is keyed by (agent, hermes profile, conversation):+//+// <multica profile dir>/hermes-sessions/<agent>/<hermes profile>/<conversation>/state.db+//+// Keying to the conversation — the issue, or `chat_<id>` for a chat session —+// is what makes this safe to share where #6693 could not. Its stated reason+// for leaving state.db task-local was concurrency: one agent's parallel tasks+// would write one live SQLite database, which needs lock and consistency work+// (plus Windows byte-range locks on `-shm`) that plain memory files do not.+// Tasks of the SAME conversation are serial by construction — a follow-up is+// dispatched after its predecessor reports — so the shard has one writer at a+// time, while two different issues get two different databases and never meet.+//+// The (agent, profile) prefix matches the memory store's scoping exactly, so+// pointing an agent at another Hermes profile gives it a fresh conversation+// line just as it gives it a fresh memory line. It is a sibling root rather+// than a subdirectory of `hermes-state/<agent>/<profile>` because that+// directory IS the agent's memories dir (the overlay links `memories/`+// straight at it), so nesting sessions inside it would surface them to Hermes+// as a memory entry.+//+// The overlay mounts the shard by symlinking `<overlay>/state.db` at+// `<store>/state.db`. SQLite resolves the link when it derives the `-wal` and+// `-shm` paths, so the journal sidecars are created in the store next to the+// database rather than in the task directory, and a task teardown can never+// take the write-ahead log with it.++// hermesSessionStoreRoot is the directory under the daemon's Multica profile+// dir that holds every agent's persistent Hermes conversation shards.+const hermesSessionStoreRoot = "hermes-sessions"++// hermesSessionDBEntry is the database file name inside both the store and the+// overlay home — Hermes resolves it relative to HERMES_HOME.+const hermesSessionDBEntry = "state.db"++// HermesSessionStorePath returns the persistent session store for+// (daemonProfile, agentID, sourceHome, conversation), or "" when the session+// database must stay task-local — no agent to key on, no conversation to key+// on (neither an issue nor a chat session), or an unresolvable Multica profile+// dir. The daemon marks the returned path in-use for the task's duration so+// PruneHermesSessionStores never reclaims it mid-mount.+func HermesSessionStorePath(daemonProfile, agentID, sourceHome string, task TaskContextForEnv) string {+ agent := sanitizePathSegment(agentID)+ if agent == "" {+ return ""+ }+ conversation := hermesConversationSegment(task)+ if conversation == "" {+ return ""+ }+ profileDir, err := cli.ProfileDir(daemonProfile)+ if err != nil {+ return ""+ }+ return filepath.Join(profileDir, hermesSessionStoreRoot, agent,+ hermesMemoryProfileSegment(sourceHome), conversation)+}++// hermesConversationSegment maps a task to the conversation its transcript+// belongs to: the issue it runs on, or the chat session when there is no+// issue. Same derivation as the per-issue Codex session store+// (codexSessionStoreKey), so both providers agree on what "one conversation"+// means. Returns "" for a task that belongs to neither, which keeps its+// session database task-local rather than inventing a shard nothing will+// resume.+func hermesConversationSegment(task TaskContextForEnv) string {+ if issue := sanitizePathSegment(task.IssueID); issue != "" {+ return issue+ }+ if chat := sanitizePathSegment(task.ChatSessionID); chat != "" {+ return "chat_" + chat+ }+ return ""+}++// 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+// 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 {+ Mounted bool+ HistoryPresent 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.+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)++ if err := os.MkdirAll(storeDir, 0o700); err != nil {+ return hermesSessionMount{}, fmt.Errorf("create hermes session store %s: %w", storeDir, 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+ }+ 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 {+ 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+}++// 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 content. A zero-length file is what SQLite leaves after an `open` that+// never wrote a page, and resuming against it is the same amnesia as an absent+// one — so it counts as no history, not as history.+func hermesStoreHasSessionDB(storeDir string) bool {+ fi, err := os.Stat(filepath.Join(storeDir, hermesSessionDBEntry))+ return err == nil && fi.Mode().IsRegular() && fi.Size() > 0+}++// migrateHermesTaskSessionDB carries a task-local state.db into an empty store+// so a daemon upgrade does not restart the conversation that is already in+// flight. The journal sidecars come with it: a database whose task was killed+// mid-write holds its most recent commits in `-wal`, and carrying the database+// alone would silently truncate the transcript to the last checkpoint.+//+// The whole family is copied into a staging directory and published with one+// rename, exactly as the memory store's migration does, because the caller+// deletes the source as soon as this returns nil. Copying straight into the+// store would let a failure after the main database land leave a store that+// looks migrated: the next attempt would skip the migration, delete the source,+// and take the un-checkpointed tail of the conversation with it.+//+// Only an empty store is migrated into — a store that already holds a database+// is this conversation's real history and must never be overwritten.+func migrateHermesTaskSessionDB(hermesHome, storeDir string, logger *slog.Logger) error {+ if hermesStoreHasSessionDB(storeDir) {+ return nil // store already holds this conversation — never overwrite it+ }++ entries, err := os.ReadDir(hermesHome)+ if err != nil {+ return fmt.Errorf("read overlay home %s: %w", hermesHome, err)+ }+ family := make([]string, 0, 3)+ for _, entry := range entries {+ if isHermesTaskLocalStateEntry(entry.Name()) && entry.Type().IsRegular() {+ family = append(family, entry.Name())+ }+ }+ if len(family) == 0 {+ return nil+ }++ staging, err := newHermesStoreStaging(storeDir)+ if err != nil {+ return err+ }+ defer os.RemoveAll(staging) // no-op once the staging dir has been promoted++ for _, name := range family {+ if err := hermesSessionCopy(filepath.Join(hermesHome, name), filepath.Join(staging, name)); err != nil {+ return fmt.Errorf("migrate task-local hermes session db %s into %s: %w", name, storeDir, err)+ }+ }++ promoted, err := publishHermesSessionStaging(staging, storeDir)+ if err != nil {+ return err+ }+ if !promoted {+ logger.Info("execenv: another task published this conversation's session store first; keeping it", "store", storeDir)+ return nil+ }+ logger.Info("execenv: migrated task-local hermes session db into conversation store",+ "store", storeDir,+ "files", len(family),+ )+ return nil+}++// publishHermesSessionStaging publishes a fully-copied staging dir as the+// conversation's store, reporting whether this caller won.+//+// It exists because "occupied" means something different here than it does for+// the memory store. A session store can hold state.db family remnants that+// carry no transcript at all — a zero-length database from an `open` that never+// wrote a page, or journal sidecars orphaned by a killed task — and the+// migration above has already decided those are not history. The generic+// publish would disagree: it reads any entry as a competitor's published state,+// report a lost race, and the caller would then delete a source database that+// was never carried over. So the remnants are cleared first (they are, by the+// definition this file uses everywhere, nothing), and the occupancy question is+// answered with the same predicate the migration asked.+//+// A store that cannot be cleared is NOT reported as a lost race: the shared+// promote fails closed, the migration returns the error, and the caller keeps+// the source database.+//+// The check, the cleanup and the promote hold hermesSessionPublishMu as one+// step. Deciding the remnants are nothing and then deleting them by path name+// is only sound while nothing can replace them in between: without the lock, a+// competitor could publish a real transcript after this caller's check, and the+// cleanup would delete the winner's database as a remnant — after the winner+// already reported success and discarded its source.+func publishHermesSessionStaging(staging, storeDir string) (bool, error) {+ hermesSessionPublishMu.Lock()+ defer hermesSessionPublishMu.Unlock()+ if hermesStoreHasSessionDB(storeDir) {+ return false, nil // a competitor published a real transcript first+ }+ if hermesSessionPublishBarrier != nil {+ hermesSessionPublishBarrier(storeDir)+ }+ if err := removeHermesSessionDBFamily(storeDir); err != nil {+ return false, err+ }+ return promoteHermesStoreStaging(staging, storeDir, hermesStoreHasSessionDB)+}++// hermesSessionPublishMu serializes every session-store publish in this+// process. In-process mutual exclusion is the real thing here, not an+// approximation: the daemon is the store tree's only writer — tasks, the+// migration and even the GC's reservation guard (Daemon.activeStores) all live+// in one process — so two publishers can only ever be two goroutines of this+// daemon. One process-wide mutex rather than a per-store map because a publish+// happens at most once per conversation (the first mount that finds a+// task-local database) and its critical section is a stat, a few unlinks and a+// rename; contention is not a factor worth bookkeeping for.+var hermesSessionPublishMu sync.Mutex++// hermesSessionPublishBarrier, when non-nil, runs inside the locked region+// between the occupancy check and the remnant cleanup — the exact window the+// lock exists to close. Tests park a publisher here to prove a competitor+// cannot interleave a publish into that window. Always nil in production.+var hermesSessionPublishBarrier func(storeDir string)++// removeHermesSessionDBFamily clears a directory's state.db family. Called+// once the database is either safely in the store or deliberately being+// replaced by the link; leaving a stale `-wal` next to the link would be+// dead weight SQLite never reads (it derives the sidecar paths from the+// resolved store path) and a confusing thing to find in a task directory.+//+// Only entries this code can identify are removed, and never recursively: a+// regular file is SQLite's, and a symlink is a prior mount's store link (left+// when the store path changed under a live overlay, e.g. a profile switch+// mid-conversation) — os.Remove unlinks it without touching its target. A+// directory or any other irregular type under a state.db name is not a+// database remnant this code recognises, and deleting content it cannot+// identify is exactly the failure this file exists to prevent, so it fails+// closed and the caller keeps its source.+func removeHermesSessionDBFamily(dir string) error {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return fmt.Errorf("read %s: %w", dir, err)+ }+ for _, entry := range entries {+ if !isHermesTaskLocalStateEntry(entry.Name()) {+ continue+ }+ path := filepath.Join(dir, entry.Name())+ if t := entry.Type(); !t.IsRegular() && t&os.ModeSymlink == 0 {+ return fmt.Errorf("refusing to remove hermes session state %s: unexpected %s under a state.db name", path, t)+ }+ if err := os.Remove(path); err != nil {+ return fmt.Errorf("remove task-local hermes session state %s: %w", path, err)+ }+ }+ return nil+}++// touchHermesSessionStore refreshes storeDir's mtime — the signal the GC reads+// as last activity. Best-effort: a failed touch only risks an over-eager+// prune, which the daemon's active-store guard still prevents.+func touchHermesSessionStore(storeDir string, logger *slog.Logger) {+ now := time.Now()+ if err := os.Chtimes(storeDir, now, now); err != nil {+ logger.Warn("execenv: refresh hermes session store activity failed", "store", storeDir, "error", err)+ }+}++// PruneHermesSessionStores reclaims per-conversation Hermes session stores+// untouched within retention. They live outside the task-scoped envRoot the+// task GC reclaims — that is the point, the transcript has to outlive the+// task — so without this a finished issue's conversation would sit on disk+// forever and deleting the issue or the agent would not remove it.+// retention <= 0 disables pruning entirely.+//+// Retention is shorter than the memory store's by design: this holds full+// transcripts rather than a handful of markdown notes, and losing an idle+// conversation's replay is a resume that starts fresh (with a continuity+// notice), not the agent forgetting what it learned.+//+// reserve (may be nil) atomically claims a store for deletion exactly as+// PruneCodexSessionStores uses it: ok=false means a live task holds the store,+// so it is left alone. nil disables the guard (tests).+func PruneHermesSessionStores(daemonProfile string, retention time.Duration, now time.Time, reserve func(storeDir string) (commit func(), ok bool), logger *slog.Logger) (removed int, bytesFreed int64) {+ if retention <= 0 {+ return 0, 0+ }+ profileDir, err := cli.ProfileDir(daemonProfile)+ if err != nil {+ return 0, 0+ }+ root := filepath.Join(profileDir, hermesSessionStoreRoot)+ agents, err := os.ReadDir(root)+ if err != nil {+ return 0, 0 // not created yet, or unreadable — nothing to prune+ }+ for _, a := range agents {+ if !a.IsDir() {+ continue+ }+ agentDir := filepath.Join(root, a.Name())+ profiles, err := os.ReadDir(agentDir)+ if err != nil {+ continue+ }+ keptProfiles := 0+ for _, p := range profiles {+ if !p.IsDir() {+ continue+ }+ profileStoreDir := filepath.Join(agentDir, p.Name())+ conversations, err := os.ReadDir(profileStoreDir)+ if err != nil {+ keptProfiles+++ continue+ }+ kept := 0+ for _, conv := range conversations {+ if !conv.IsDir() {+ continue+ }+ storeDir := filepath.Join(profileStoreDir, conv.Name())+ // Same "newest mtime is last activity, plus total size" walk the+ // memory store prunes on; SQLite bumps the database's mtime on+ // every commit, so an advancing conversation keeps its shard fresh.+ newest, size := hermesMemoryStoreStat(storeDir)+ if newest.IsZero() || now.Sub(newest) <= retention {+ kept+++ continue+ }+ var commit func()+ if reserve != nil {+ c, ok := reserve(storeDir)+ if !ok {+ kept+++ continue+ }+ commit = c+ }+ err := os.RemoveAll(storeDir)+ if commit != nil {+ commit()+ }+ if err != nil {+ logger.Warn("execenv: prune hermes session store failed", "store", storeDir, "error", err)+ kept+++ continue+ }+ removed+++ bytesFreed += size+ }+ // Drop the profile dir once its last conversation is gone, then the+ // agent dir once its last profile is, so the tree does not leave+ // empty shells behind. os.Remove only succeeds on an empty+ // directory, so anything still holding content keeps its parents.+ if kept > 0 {+ keptProfiles+++ continue+ }+ if err := os.Remove(profileStoreDir); err != nil {+ keptProfiles+++ }+ }+ if keptProfiles == 0 {+ _ = os.Remove(agentDir)+ }+ }+ return removed, bytesFreed+}diff --git a/server/internal/daemon/execenv/hermes_sessions_test.go b/server/internal/daemon/execenv/hermes_sessions_test.gonew file mode 100644index 0000000000..2996ededbd--- /dev/null+++ b/server/internal/daemon/execenv/hermes_sessions_test.go@@ -0,0 +1,845 @@+package execenv++import (+ "errors"+ "os"+ "path/filepath"+ "runtime"+ "sync/atomic"+ "testing"+ "time"+)++// TestHermesSessionStorePathLayout pins the on-disk layout an operator (and+// the GC below) depends on:+// <profile dir>/hermes-sessions/<agent>/<hermes profile>/<conversation>.+func TestHermesSessionStorePathLayout(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ agent := "11111111-2222-3333-4444-555555555555"+ issue := "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"+ got := HermesSessionStorePath("", agent, filepath.Join(platformDefaultHermesHome(), "profiles", "research"),+ TaskContextForEnv{AgentID: agent, IssueID: issue})+ want := filepath.Join(home, ".multica", hermesSessionStoreRoot, agent, "research", issue)+ if got != want {+ t.Fatalf("store path = %q, want %q", got, want)+ }+}++// TestHermesSessionStorePathScoping covers which tasks get a shard at all, and+// that two conversations of one agent never share one.+func TestHermesSessionStorePathScoping(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ const agent = "agent-1"+ issueA := HermesSessionStorePath("", agent, "", TaskContextForEnv{IssueID: "issue-a"})+ issueB := HermesSessionStorePath("", agent, "", TaskContextForEnv{IssueID: "issue-b"})+ if issueA == "" || issueA == issueB {+ t.Fatalf("two issues must get distinct stores, got %q and %q", issueA, issueB)+ }++ chat := HermesSessionStorePath("", agent, "", TaskContextForEnv{ChatSessionID: "sess-1"})+ if filepath.Base(chat) != "chat_sess-1" {+ t.Fatalf("chat conversation segment = %q, want chat_sess-1", filepath.Base(chat))+ }+ // An issue task and a chat task can never collide even on equal ids.+ if same := HermesSessionStorePath("", agent, "", TaskContextForEnv{IssueID: "sess-1"}); same == chat {+ t.Fatalf("issue and chat conversations collided on %q", chat)+ }++ // No agent, or no conversation, means no store: the session database stays+ // task-local rather than landing in a shard nothing will resume.+ if got := HermesSessionStorePath("", "", "", TaskContextForEnv{IssueID: "issue-a"}); got != "" {+ t.Fatalf("store path without an agent = %q, want empty", got)+ }+ if got := HermesSessionStorePath("", agent, "", TaskContextForEnv{}); got != "" {+ t.Fatalf("store path without a conversation = %q, want empty", got)+ }+}++// TestPrepareHermesHomeSessionStorePersistsAcrossTasks is the regression test+// for GH #6806: two tasks of one conversation must see the same state.db, so a+// resume can actually find the transcript. Each task builds a fresh overlay, so+// this can only hold if state.db resolves to the conversation's store.+func TestPrepareHermesHomeSessionStorePersistsAcrossTasks(t *testing.T) {+ requireSymlinks(t)+ t.Parallel()+ sharedHome := t.TempDir()+ store := filepath.Join(t.TempDir(), "hermes-sessions", "agent-1", "default", "issue-1")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ firstTask := filepath.Join(t.TempDir(), "hermes-home")+ sessions, err := prepareHermesHome(firstTask, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {+ t.Fatalf("prepare first task: %v", err)+ }+ if !sessions.Mounted {+ t.Fatal("first task reported the session store as not mounted")+ }+ if sessions.HistoryPresent {+ 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")++ secondTask := filepath.Join(t.TempDir(), "hermes-home")+ if _, err := prepareHermesHome(secondTask, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {+ t.Fatalf("prepare second task: %v", err)+ }+ got, err := os.ReadFile(filepath.Join(secondTask, "state.db"))+ if err != nil {+ t.Fatalf("second task lost the conversation transcript: %v", err)+ }+ if string(got) != "transcript" {+ 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"))+ 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())+ }+}++// TestPrepareHermesHomeSessionStoreIsolatesConversations guards the property+// that makes sharing safe at all: one conversation's transcript is never+// visible to another, so two issues of the same agent cannot write one database.+func TestPrepareHermesHomeSessionStoreIsolatesConversations(t *testing.T) {+ requireSymlinks(t)+ t.Parallel()+ sharedHome := t.TempDir()+ storeRoot := t.TempDir()+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ homeA := filepath.Join(t.TempDir(), "hermes-home")+ if _, err := prepareHermesHome(homeA, sharedHome, false, skills, nil, "",+ 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")++ 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) {+ t.Fatalf("conversation B can see another conversation's transcript (err = %v)", err)+ }+}++// TestPrepareHermesHomeWithoutSessionStoreKeepsStateTaskLocal covers the+// no-store path (no agent or no conversation to key on): state.db must stay an+// ordinary task-local file, exactly as before.+func TestPrepareHermesHomeWithoutSessionStoreKeepsStateTaskLocal(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ sessions, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger())+ if err != nil {+ t.Fatalf("prepare: %v", err)+ }+ if sessions.Mounted {+ t.Fatal("Mounted = true without a session store")+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ fi, err := os.Lstat(filepath.Join(hermesHome, "state.db"))+ if err != nil {+ t.Fatalf("lstat state.db: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Fatal("state.db is a link with no store to point at")+ }+}++// TestPrepareHermesHomeMigratesTaskLocalSessionDB covers the upgrade path: a+// conversation already in flight when the daemon gains a session store must not+// restart. The journal sidecars come along, or the last commits would be lost.+func TestPrepareHermesHomeMigratesTaskLocalSessionDB(t *testing.T) {+ requireSymlinks(t)+ t.Parallel()+ sharedHome := t.TempDir()+ store := filepath.Join(t.TempDir(), "issue-1")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")++ // A task-local database left by an older daemon.+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {+ t.Fatalf("prepare pre-store task: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ mustWrite(t, filepath.Join(hermesHome, "state.db-wal"), "uncheckpointed tail")++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {+ t.Fatalf("prepare with store: %v", err)+ }+ got, err := os.ReadFile(filepath.Join(store, "state.db"))+ if err != nil {+ t.Fatalf("in-flight transcript was dropped: %v", err)+ }+ if string(got) != "transcript" {+ t.Fatalf("migrated transcript = %q, want %q", got, "transcript")+ }+ wal, err := os.ReadFile(filepath.Join(store, "state.db-wal"))+ if err != nil {+ t.Fatalf("write-ahead log was dropped: %v", err)+ }+ if string(wal) != "uncheckpointed tail" {+ t.Fatalf("migrated wal = %q, want %q", wal, "uncheckpointed tail")+ }+}++// TestPrepareHermesHomeMigrationNeverOverwritesStore is the other half of the+// migration contract: a store that already holds this conversation's history is+// the real transcript and a stray task-local database must not replace it.+func TestPrepareHermesHomeMigrationNeverOverwritesStore(t *testing.T) {+ requireSymlinks(t)+ t.Parallel()+ sharedHome := t.TempDir()+ store := filepath.Join(t.TempDir(), "issue-1")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")++ mustWrite(t, filepath.Join(store, "state.db"), "the real transcript")++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {+ t.Fatalf("prepare pre-store task: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "a stray task-local db")++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {+ t.Fatalf("prepare with store: %v", err)+ }+ got, err := os.ReadFile(filepath.Join(store, "state.db"))+ if err != nil {+ t.Fatalf("read store db: %v", err)+ }+ if string(got) != "the real transcript" {+ t.Fatalf("store db = %q, want the pre-existing transcript", got)+ }+}++// TestPrepareHermesHomeSessionMountIsIdempotent covers Reuse: rebuilding the+// overlay for a follow-up turn in the same task directory must leave the link+// (and therefore the live database) alone.+func TestPrepareHermesHomeSessionMountIsIdempotent(t *testing.T) {+ requireSymlinks(t)+ t.Parallel()+ 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, "", store, testLogger()); err != nil {+ t.Fatalf("prepare: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {+ t.Fatalf("reuse prepare: %v", err)+ }++ got, err := os.ReadFile(filepath.Join(store, "state.db"))+ if err != nil {+ t.Fatalf("reuse dropped the transcript: %v", err)+ }+ if string(got) != "transcript" {+ t.Fatalf("transcript = %q, want %q", got, "transcript")+ }+}++func TestPruneHermesSessionStores(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ root := filepath.Join(home, ".multica", hermesSessionStoreRoot)+ idle := filepath.Join(root, "agent-1", "default", "issue-idle")+ fresh := filepath.Join(root, "agent-1", "default", "issue-fresh")+ held := filepath.Join(root, "agent-2", "default", "issue-held")+ for _, dir := range []string{idle, fresh, held} {+ mustWrite(t, filepath.Join(dir, "state.db"), "transcript")+ }++ now := time.Now()+ old := now.Add(-30 * 24 * time.Hour)+ for _, dir := range []string{idle, held} {+ if err := os.Chtimes(filepath.Join(dir, "state.db"), old, old); err != nil {+ t.Fatalf("age store: %v", err)+ }+ if err := os.Chtimes(dir, old, old); err != nil {+ t.Fatalf("age store dir: %v", err)+ }+ }++ reserve := func(storeDir string) (func(), bool) {+ if storeDir == held {+ return nil, false // a live task holds it+ }+ return func() {}, true+ }++ removed, freed := PruneHermesSessionStores("", 14*24*time.Hour, now, reserve, testLogger())+ if removed != 1 {+ t.Fatalf("removed = %d, want 1", removed)+ }+ if freed <= 0 {+ t.Fatalf("bytesFreed = %d, want > 0", freed)+ }+ if _, err := os.Stat(idle); !os.IsNotExist(err) {+ t.Fatalf("idle conversation survived the prune (err = %v)", err)+ }+ if _, err := os.Stat(fresh); err != nil {+ t.Fatalf("recently used conversation was reclaimed: %v", err)+ }+ if _, err := os.Stat(held); err != nil {+ t.Fatalf("conversation held by a live task was reclaimed: %v", err)+ }+}++func TestPruneHermesSessionStoresDisabled(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ store := filepath.Join(home, ".multica", hermesSessionStoreRoot, "agent-1", "default", "issue-1")+ mustWrite(t, filepath.Join(store, "state.db"), "transcript")+ old := time.Now().Add(-365 * 24 * time.Hour)+ if err := os.Chtimes(store, old, old); err != nil {+ t.Fatalf("age store: %v", err)+ }++ if removed, _ := PruneHermesSessionStores("", 0, time.Now(), nil, testLogger()); removed != 0 {+ t.Fatalf("removed = %d with retention disabled, want 0", removed)+ }+ if _, err := os.Stat(store); err != nil {+ t.Fatalf("store was reclaimed with retention disabled: %v", err)+ }+}++// 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)+ }+ 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())+ 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)+ }+ }+ 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))+ }++ // 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)+ }+ 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)+ }+}++// TestPrepareHermesHomeMigrationIsAtomic covers a migration that dies between+// the main database and its write-ahead log. Copying straight into the store+// would leave a store that LOOKS migrated: the next attempt would skip the+// migration, delete the source, and take the un-checkpointed tail of the+// conversation with it. The store must stay empty until the whole family is+// there, and the retry must carry everything.+func TestPrepareHermesHomeMigrationIsAtomic(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)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ mustWrite(t, filepath.Join(hermesHome, "state.db-wal"), "uncheckpointed tail")++ restore := stubHermesSessionCopy(t, func(src, dst string) error {+ if filepath.Base(src) == "state.db-wal" {+ return errors.New("disk full")+ }+ return copyFile(src, dst)+ })++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err == nil {+ t.Fatal("prepare succeeded despite a failed migration, want an error")+ }++ // Nothing published, nothing deleted.+ if hermesStoreHasSessionDB(store) {+ t.Fatal("store holds a database after a half-failed migration")+ }+ for _, name := range []string{"state.db", "state.db-wal"} {+ if _, err := os.Stat(filepath.Join(hermesHome, name)); err != nil {+ t.Fatalf("source %s was removed after a failed migration: %v", name, err)+ }+ }++ restore()+ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err != nil {+ t.Fatalf("retry after a failed migration: %v", err)+ }+ for name, want := range map[string]string{+ "state.db": "transcript",+ "state.db-wal": "uncheckpointed tail",+ } {+ got, err := os.ReadFile(filepath.Join(store, name))+ if err != nil {+ t.Fatalf("retry did not carry %s over: %v", name, err)+ }+ if string(got) != want {+ t.Fatalf("%s = %q, want %q", name, got, want)+ }+ }+}++// TestPrepareHermesHomeMountedEmptyStoreReportsNoHistory covers the two shapes+// where the plumbing is fine but there is nothing to resume: a store the GC+// reclaimed between turns, and a dangling link an older overlay left pointing at+// a store that no longer exists. Reading "mounted" as "resumable" here is what+// would let a dead session id through to Hermes, which answers it by silently+// starting over.+func TestPrepareHermesHomeMountedEmptyStoreReportsNoHistory(t *testing.T) {+ requireSymlinks(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, "", store, testLogger()); err != nil {+ t.Fatalf("prepare first turn: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")++ sessions, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {+ t.Fatalf("prepare second turn: %v", err)+ }+ if !sessions.HistoryPresent {+ t.Fatal("HistoryPresent = false with a written transcript, want true")+ }++ // The GC reclaims the store between turns; the overlay's link survives and+ // now dangles.+ if err := os.RemoveAll(store); err != nil {+ t.Fatalf("simulate gc reclaim: %v", err)+ }+ sessions, err = prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {+ t.Fatalf("prepare after gc reclaim: %v", err)+ }+ if !sessions.Mounted {+ t.Fatal("Mounted = false after the store was recreated, want true")+ }+ if sessions.HistoryPresent {+ t.Fatal("HistoryPresent = true over a reclaimed store — a dead session id would be forwarded")+ }++ // An empty file is the other shape of nothing: SQLite leaves one behind for+ // an open that never wrote a page, and resuming against it is the same+ // amnesia as resuming against an absent one.+ mustWrite(t, filepath.Join(store, "state.db"), "")+ sessions, err = prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {+ t.Fatalf("prepare with an empty db: %v", err)+ }+ if sessions.HistoryPresent {+ t.Fatal("HistoryPresent = true for a zero-length database, want false")+ }+}++// TestPrepareHermesHomeMigrationIntoSemanticallyEmptyStore covers the store+// that holds state.db family remnants but no transcript — a zero-length+// database from an `open` that never wrote a page, or orphan sidecars left by a+// killed task. The migration reads those as "no history" and proceeds; the+// publish step must agree, because the caller deletes the source the moment the+// migration reports success. Disagreeing means the source database and its+// un-checkpointed tail are deleted in favour of a database with nothing in it.+func TestPrepareHermesHomeMigrationIntoSemanticallyEmptyStore(t *testing.T) {+ requireSymlinks(t)++ tests := []struct {+ name string+ remnants map[string]string+ // wantMoved expects the source transcript to end up in the store;+ // wantFailClosed expects the migration to refuse instead — either is+ // acceptable, silently dropping the source is not.+ wantMoved bool+ wantFailClosed bool+ }{+ {+ name: "zero-length database",+ remnants: map[string]string{"state.db": ""},+ wantMoved: true,+ },+ {+ name: "orphan sidecars, no database",+ remnants: map[string]string{"state.db-wal": "orphan tail", "state.db-shm": "orphan index"},+ wantMoved: true,+ },+ {+ // The one case that must NOT be overwritten: a real transcript+ // published by a concurrent task of the same conversation.+ name: "real database is never overwritten",+ remnants: map[string]string{"state.db": "the winner's transcript"},+ wantMoved: false,+ },+ {+ // Something in the store that is neither history nor a clearable+ // remnant. There is no safe publish here, so the migration must+ // fail rather than report a lost race and let the caller delete the+ // source.+ name: "unclearable store fails closed",+ remnants: map[string]string{"state.db": "", "stray.txt": "not ours"},+ wantFailClosed: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(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")++ for name, content := range tt.remnants {+ mustWrite(t, filepath.Join(store, name), content)+ }++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {+ t.Fatalf("prepare pre-store task: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")+ mustWrite(t, filepath.Join(hermesHome, "state.db-wal"), "uncheckpointed tail")++ sessions, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {+ if !tt.wantFailClosed {+ t.Fatalf("prepare: %v", err)+ }+ // Failing closed is only acceptable with the source intact.+ for _, name := range []string{"state.db", "state.db-wal"} {+ got, statErr := os.ReadFile(filepath.Join(hermesHome, name))+ if statErr != nil {+ t.Fatalf("prepare failed (%v) AND dropped the source %s: %v", err, name, statErr)+ }+ if len(got) == 0 {+ t.Fatalf("source %s was emptied by a failed migration", name)+ }+ }+ return+ }+ if tt.wantFailClosed {+ t.Fatal("prepare succeeded on a store it cannot safely publish into, want an error")+ }+ if !sessions.Mounted || !sessions.HistoryPresent {+ t.Fatalf("mount = %+v, want mounted with history", sessions)+ }++ got, err := os.ReadFile(filepath.Join(store, "state.db"))+ if err != nil {+ t.Fatalf("read store db: %v", err)+ }+ if tt.wantMoved {+ if string(got) != "transcript" {+ t.Fatalf("store db = %q, want the migrated transcript — the source was dropped for an empty store", got)+ }+ wal, err := os.ReadFile(filepath.Join(store, "state.db-wal"))+ if err != nil || string(wal) != "uncheckpointed tail" {+ t.Fatalf("store wal = %q (err %v), want the migrated tail", wal, err)+ }+ } else if string(got) != "the winner's transcript" {+ t.Fatalf("store db = %q, want the pre-existing transcript left untouched", got)+ }+ })+ }+}++// TestHermesSessionStorePublishSerializesCompetitors pins the publish+// protocol's mutual exclusion with a deterministic interleaving. The first+// publisher is parked inside the critical section — after its occupancy check,+// before its remnant cleanup — which is exactly the window where an+// unsynchronized competitor used to be able to publish a real transcript and+// have it deleted as a remnant by the parked publisher's stale decision. With+// the lock, the competitor cannot enter that window at all: it waits, its own+// check sees the winner's database, and it reports a lost race without+// touching anything.+func TestHermesSessionStorePublishSerializesCompetitors(t *testing.T) {+ store := filepath.Join(t.TempDir(), "issue-1")+ // The semantically-empty shape both publishers read as "no history".+ mustWrite(t, filepath.Join(store, "state.db"), "")++ mkStaging := func(label string) string {+ staging, err := newHermesStoreStaging(store)+ if err != nil {+ t.Fatalf("staging for %s: %v", label, err)+ }+ mustWrite(t, filepath.Join(staging, "state.db"), label+" transcript")+ mustWrite(t, filepath.Join(staging, "state.db-wal"), label+" tail")+ return staging+ }+ firstStaging := mkStaging("first")+ secondStaging := mkStaging("second")++ entered := make(chan struct{}, 2)+ release := make(chan struct{})+ var parkedFirst atomic.Bool+ stubHermesSessionPublishBarrier(t, func(string) {+ entered <- struct{}{}+ if parkedFirst.CompareAndSwap(false, true) {+ <-release+ }+ })++ type outcome struct {+ label string+ promoted bool+ err error+ }+ results := make(chan outcome, 2)+ publish := func(label, staging string) {+ promoted, err := publishHermesSessionStaging(staging, store)+ results <- outcome{label, promoted, err}+ }++ go publish("first", firstStaging)+ <-entered // the first publisher is parked between its check and its cleanup+ go publish("second", secondStaging)++ close(release)+ byLabel := map[string]outcome{}+ for range 2 {+ r := <-results+ byLabel[r.label] = r+ }+ for _, r := range byLabel {+ if r.err != nil {+ t.Fatalf("publish %s: %v", r.label, r.err)+ }+ }+ if !byLabel["first"].promoted || byLabel["second"].promoted {+ t.Fatalf("promoted = first:%v second:%v, want the parked first publisher to win and the second to positively lose",+ byLabel["first"].promoted, byLabel["second"].promoted)+ }++ // The loser never reached the destructive window: its occupancy check+ // already saw the winner's published database.+ select {+ case <-entered:+ t.Fatal("the losing publisher entered the check-to-cleanup window — the interleaving that deletes a freshly published transcript")+ default:+ }++ // The winner's family is in the store byte-intact.+ for name, want := range map[string]string{+ "state.db": "first transcript",+ "state.db-wal": "first tail",+ } {+ got, err := os.ReadFile(filepath.Join(store, name))+ if err != nil || string(got) != want {+ t.Fatalf("store %s = %q (err %v), want the winner's %q untouched", name, got, err, want)+ }+ }+ // The loser's staging was not consumed, so its caller still holds a+ // complete copy of the source it will now yield with.+ for _, name := range []string{"state.db", "state.db-wal"} {+ if _, err := os.Stat(filepath.Join(secondStaging, name)); err != nil {+ t.Fatalf("loser's staging %s was destroyed: %v", name, err)+ }+ }+}++// TestPrepareHermesHomeStoreCleanupHandlesUnexpectedEntryTypes covers the+// state.db-named entries the cleanup must not treat as removable SQLite+// remnants. A directory under a family name is content this code cannot+// identify — the publish must fail closed with the source preserved rather+// than delete it recursively. A symlink is a prior mount's store link: it is+// unlinked (never followed), and its target must survive.+func TestPrepareHermesHomeStoreCleanupHandlesUnexpectedEntryTypes(t *testing.T) {+ requireSymlinks(t)++ t.Run("directory under a family name fails closed", func(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")++ mustWrite(t, filepath.Join(store, "state.db"), "")+ mustWrite(t, filepath.Join(store, "state.db-wal", "nested.txt"), "content this code cannot identify")++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {+ t.Fatalf("prepare pre-store task: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger()); err == nil {+ t.Fatal("prepare succeeded over a store entry it cannot identify, want fail closed")+ }+ if got, err := os.ReadFile(filepath.Join(store, "state.db-wal", "nested.txt")); err != nil || string(got) != "content this code cannot identify" {+ t.Fatalf("unidentified store content = %q (err %v), want it untouched", got, err)+ }+ if got, err := os.ReadFile(filepath.Join(hermesHome, "state.db")); err != nil || string(got) != "transcript" {+ t.Fatalf("source db = %q (err %v), want it preserved on a failed publish", got, err)+ }+ })++ t.Run("symlink remnant is unlinked without touching its target", func(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")++ target := filepath.Join(t.TempDir(), "not-a-remnant.db")+ mustWrite(t, target, "someone else's database")+ mustWrite(t, filepath.Join(store, "state.db"), "")+ if err := os.Symlink(target, filepath.Join(store, "state.db-shm")); err != nil {+ t.Fatalf("plant symlink remnant: %v", err)+ }++ if _, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", "", testLogger()); err != nil {+ t.Fatalf("prepare pre-store task: %v", err)+ }+ mustWrite(t, filepath.Join(hermesHome, "state.db"), "transcript")++ sessions, err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", store, testLogger())+ if err != nil {+ t.Fatalf("prepare: %v", err)+ }+ if !sessions.Mounted || !sessions.HistoryPresent {+ t.Fatalf("mount = %+v, want mounted with history", sessions)+ }+ if got, err := os.ReadFile(filepath.Join(store, "state.db")); err != nil || string(got) != "transcript" {+ t.Fatalf("store db = %q (err %v), want the migrated transcript", got, err)+ }+ if got, err := os.ReadFile(target); err != nil || string(got) != "someone else's database" {+ t.Fatalf("symlink target = %q (err %v), want it untouched by the unlink", got, err)+ }+ if _, err := os.Lstat(filepath.Join(store, "state.db-shm")); !os.IsNotExist(err) {+ t.Fatalf("symlink remnant still present (lstat err %v), want it unlinked", err)+ }+ })+}++// 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.+func stubHermesSessionCopy(t *testing.T, fn func(src, dst string) error) (restore func()) {+ t.Helper()+ prev := hermesSessionCopy+ hermesSessionCopy = fn+ restored := false+ restore = func() {+ if !restored {+ hermesSessionCopy = prev+ restored = true+ }+ }+ t.Cleanup(restore)+ return restore+}++// stubHermesSessionPublishBarrier swaps the publish barrier for the duration+// of a test, same contract as stubHermesSessionLink.+func stubHermesSessionPublishBarrier(t *testing.T, fn func(storeDir string)) (restore func()) {+ t.Helper()+ prev := hermesSessionPublishBarrier+ hermesSessionPublishBarrier = fn+ restored := false+ restore = func() {+ if !restored {+ hermesSessionPublishBarrier = prev+ restored = true+ }+ }+ t.Cleanup(restore)+ return restore+}++// requireSymlinks skips a test on a host that cannot create symlinks. The+// production path degrades to a task-local database there rather than copying,+// so there is nothing to assert about the mounted layout.+func requireSymlinks(t *testing.T) {+ t.Helper()+ if runtime.GOOS != "windows" {+ return+ }+ dir := t.TempDir()+ if err := os.Symlink(filepath.Join(dir, "target"), filepath.Join(dir, "link")); err != nil {+ t.Skipf("symlinks unavailable on this host: %v", err)+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex e2483857bf..f30e2ec132 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -68,10 +68,11 @@ type gcStats struct {// hermesMemoryStoresReclaimed is counted separately from storesReclaimed:// the two stores hold different things on different TTLs, so folding them// into one number would make either figure unreadable for an operator.- hermesMemoryStoresReclaimed int // per-agent Hermes memory stores reclaimed past their TTL- repoCachesReclaimed int // bare repo caches under .repos evicted past their TTL- bytesReclaimed int64 // total bytes freed in this cycle- byPattern map[string]int // configured basename or managed path label -> reclaim count+ hermesMemoryStoresReclaimed int // per-agent Hermes memory stores reclaimed past their TTL+ hermesSessionStoresReclaimed int // per-conversation Hermes session stores reclaimed past their TTL+ repoCachesReclaimed int // bare repo caches under .repos evicted past their TTL+ bytesReclaimed int64 // total bytes freed in this cycle+ byPattern map[string]int // configured basename or managed path label -> reclaim count}// runGC performs a single GC scan across all workspace directories.@@ -124,7 +125,15 @@ func (d *Daemon) runGC(ctx context.Context) {stats.bytesReclaimed += storeBytes}- if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 {+ // And per-conversation Hermes session stores, which outlive the task for the+ // same reason (that is what fixes #6806) but hold transcripts rather than+ // notes — so they get the shorter, Codex-like retention.+ if storesRemoved, storeBytes := execenv.PruneHermesSessionStores(d.cfg.Profile, d.cfg.GCHermesSessionTTL, time.Now(), d.reserveStoreForDeletion, d.logger); storesRemoved > 0 {+ stats.hermesSessionStoresReclaimed += storesRemoved+ stats.bytesReclaimed += storeBytes+ }++ if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.hermesSessionStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 {d.logger.Info("gc: cycle complete","cleaned", stats.cleaned,"orphaned", stats.orphaned,@@ -133,6 +142,7 @@ func (d *Daemon) runGC(ctx context.Context) {"artifact_removed", stats.artifactRemoved,"codex_session_stores_reclaimed", stats.storesReclaimed,"hermes_memory_stores_reclaimed", stats.hermesMemoryStoresReclaimed,+ "hermes_session_stores_reclaimed", stats.hermesSessionStoresReclaimed,"repo_caches_reclaimed", stats.repoCachesReclaimed,"bytes_reclaimed", stats.bytesReclaimed,"by_pattern", stats.byPattern,diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.goindex b617c3ffee..6670aea062 100644--- a/server/pkg/agent/hermes.go+++ b/server/pkg/agent/hermes.go@@ -354,6 +354,13 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt// resume. Only that is curable by starting a fresh session, so// handshake/network failures below must leave it false.var resumeRejected bool+ // True only when session/resume actually landed on the session we+ // asked for. Hermes answers a resume of a session its state.db no+ // longer holds by silently creating a fresh one (acp_adapter/server.py+ // resume_session: "not found, creating new"), so this is what decides+ // whether the turn must carry a continuity notice — see the prompt+ // assembly below.+ var resumeLanded bool// The stop reason session/prompt reported, when it answered at all.// Read once the turn has fully settled — see the resumed-session check// after the provider-error promotion below.@@ -410,9 +417,8 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOptresCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}return}- var changed bool- sessionID, changed = resolveResumedSessionID(opts.ResumeSessionID, result)- if changed {+ sessionID, resumeLanded = resolveHermesResumedSessionID(opts.ResumeSessionID, result)+ if !resumeLanded {b.cfg.Logger.Warn("agent returned a different session id on resume — original was likely lost; continuing with the new id","backend", "hermes","requested", opts.ResumeSessionID,@@ -518,7 +524,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt_, err = c.request(runCtx, "session/prompt", map[string]any{"sessionId": sessionID,"prompt": []map[string]any{- {"type": "text", "text": prompt},+ {"type": "text", "text": hermesTurnText(prompt, opts.ResumeExpected, resumeLanded, opts.ResumeContinuityNotice)},},})if err != nil {@@ -1139,13 +1145,17 @@ const hermesResumeLostError = "hermes could not restore the resumed session; it// unknown session as a JSON-RPC error. Its ACP adapter answers// `session/prompt` for a session it cannot load with an ordinary success// frame carrying stopReason=refusal (acp_adapter/server.py, the one place it-// emits that reason), and `session/resume` echoes nothing back — the ACP-// ResumeSessionResponse schema has no sessionId field at all, unlike-// NewSessionResponse — so resolveResumedSessionID keeps the id we asked for.-// Nothing in the exchange is an error, which is why the isACPSessionNotFound-// branches at set_model and prompt time never fire for this runtime and every-// later dispatch on the same (agent, issue) pair loops on the dead session-// (GH #6150).+// emits that reason), and `session/resume` returns an ordinary success frame+// whatever happened — the ACP ResumeSessionResponse schema has no sessionId+// field at all, unlike NewSessionResponse. Nothing in the exchange is an+// error, which is why the isACPSessionNotFound branches at set_model and+// prompt time never fire for this runtime and every later dispatch on the same+// (agent, issue) pair loops on the dead session (GH #6150).+//+// This stays necessary alongside resolveHermesResumedSessionID, which reads+// `_meta.hermes.sessionProvenance` to catch the rebind at resume time: that+// covers the runtime answering with a DIFFERENT session, while this covers it+// answering with the one we asked for and then refusing to run it.//// Both conditions are required. stopReason=refusal alone is a legitimate// model refusal, and refusing a resumed turn after real work is not a lost@@ -1835,6 +1845,75 @@ func resolveResumedSessionID(requested string, response json.RawMessage) (stringreturn got, got != requested}+// resolveHermesResumedSessionID is the Hermes-specific reading of a+// session/resume response: it returns the live session id and whether the+// resume actually LANDED on the session we asked for.+//+// The shared resolver above is not enough here because ACP's+// ResumeSessionResponse has no sessionId field at all (acp/schema.py+// ResumeSessionResponse), unlike NewSessionResponse. Hermes answers a resume+// of a session its state.db no longer holds by silently creating a fresh one+// (acp_adapter/server.py resume_session: "not found, creating new") and+// replies with an ordinary success frame, so the rebind used to be+// indistinguishable from a real resume: the daemon re-sent the same dead id+// every turn and the user got a conversation that restarted from zero with no+// error anywhere (GH #6806).+//+// Hermes does report the session it actually served the request with on+// `_meta.hermes.sessionProvenance`, which is the only signal available. A+// response carrying neither shape falls back to the requested id and reports+// landed=true, so a runtime that reports nothing keeps its previous behaviour+// rather than declaring every turn's history lost.+//+// That residual blind spot is bounded on the daemon side: the resume gate only+// hands a session id to a run whose session store actually holds a transcript+// (sessionHomeReachable), so a silent runtime can misreport a stale session but+// never an absent one.+func resolveHermesResumedSessionID(requested string, response json.RawMessage) (string, bool) {+ got := extractACPSessionID(response)+ if got == "" {+ got = extractACPProvenanceSessionID(response)+ }+ if got == "" {+ return requested, true+ }+ return got, got == requested+}++// extractACPProvenanceSessionID pulls the session id Hermes reports on+// `_meta.hermes.sessionProvenance.acpSessionId` — the ACP-facing id of the+// session the server actually served the request with. `currentHermesSessionId`+// is the agent-internal id of the same session and is deliberately not read:+// the two diverge when Hermes compresses a session into a successor, and only+// the ACP id is the one we address later prompts to.+func extractACPProvenanceSessionID(result json.RawMessage) string {+ var r struct {+ Meta struct {+ Hermes struct {+ SessionProvenance struct {+ ACPSessionID string `json:"acpSessionId"`+ } `json:"sessionProvenance"`+ } `json:"hermes"`+ } `json:"_meta"`+ }+ if err := json.Unmarshal(result, &r); err != nil {+ return ""+ }+ return strings.TrimSpace(r.Meta.Hermes.SessionProvenance.ACPSessionID)+}++// hermesTurnText prepends the caller's continuity notice when this task meant+// to continue a conversation but the resume landed on a fresh session. Same+// contract as the codex backend's codexTurnInput: the notice is empty whenever+// the daemon's own prompt already carries it, so a turn can never pay for the+// paragraph twice.+func hermesTurnText(prompt string, resumeExpected, resumeLanded bool, notice string) string {+ if resumeExpected && !resumeLanded {+ return notice + prompt+ }+ return prompt+}+// buildHermesSessionParams constructs the params map for the ACP `session/new`// request. The `model` field is only included when non-empty so Hermes falls// back to its default only when no explicit model was configured.diff --git a/server/pkg/agent/hermes_resume_test.go b/server/pkg/agent/hermes_resume_test.gonew file mode 100644index 0000000000..5fc3a44bbc--- /dev/null+++ b/server/pkg/agent/hermes_resume_test.go@@ -0,0 +1,221 @@+package agent++import (+ "context"+ "encoding/json"+ "log/slog"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"+ "time"+)++func TestResolveHermesResumedSessionIDPrefersTopLevelID(t *testing.T) {+ t.Parallel()++ id, landed := resolveHermesResumedSessionID("ses_old", json.RawMessage(`{"sessionId":"ses_old"}`))+ if id != "ses_old" || !landed {+ t.Fatalf("got (%q, %v), want (ses_old, true)", id, landed)+ }+}++func TestResolveHermesResumedSessionIDReadsProvenanceMeta(t *testing.T) {+ t.Parallel()++ // Hermes' real session/resume shape: no top-level sessionId (the ACP+ // ResumeSessionResponse schema has no such field), and the session it+ // actually served the turn with reported under _meta.+ response := json.RawMessage(`{+ "_meta":{"hermes":{"sessionProvenance":{+ "acpSessionId":"ses_new",+ "currentHermesSessionId":"ses_new",+ "sessionKind":"root"+ }}},+ "models":{"currentModelId":"openai:gpt-5"}+ }`)++ id, landed := resolveHermesResumedSessionID("ses_old", response)+ if id != "ses_new" {+ t.Fatalf("session id = %q, want ses_new (the session hermes silently rebound to)", id)+ }+ if landed {+ t.Fatal("landed = true, want false: the requested session was not the one resumed")+ }+}++func TestResolveHermesResumedSessionIDProvenanceMatchingIsALanding(t *testing.T) {+ t.Parallel()++ response := json.RawMessage(`{"_meta":{"hermes":{"sessionProvenance":{"acpSessionId":"ses_old"}}}}`)++ id, landed := resolveHermesResumedSessionID("ses_old", response)+ if id != "ses_old" || !landed {+ t.Fatalf("got (%q, %v), want (ses_old, true)", id, landed)+ }+}++func TestResolveHermesResumedSessionIDSilentResponseKeepsRequested(t *testing.T) {+ t.Parallel()++ // A runtime that reports neither shape (an older Hermes, or a custom ACP+ // server) must not be read as "history lost" on every turn — that would+ // staple a continuity notice onto every single turn it ever runs. Keep the+ // requested id and assume the resume landed.+ //+ // This is the one case the backend genuinely cannot resolve, and it is why+ // the daemon-side gate matters: sessionHomeReachable stops a dead id from+ // reaching a store with no transcript in the first place, so this fallback+ // only has to cover a store that DOES hold history and a runtime that will+ // not say which session it used.+ for _, response := range []string{`{}`, `{"models":{}}`, `not json`} {+ id, landed := resolveHermesResumedSessionID("ses_old", json.RawMessage(response))+ if id != "ses_old" || !landed {+ t.Fatalf("response %q: got (%q, %v), want (ses_old, true)", response, id, landed)+ }+ }+}++func TestHermesTurnTextPrependsNoticeOnlyWhenResumeMissed(t *testing.T) {+ t.Parallel()++ const notice = "NOTICE: prior conversation unavailable.\n\n"+ tests := []struct {+ name string+ resumeExpected bool+ resumeLanded bool+ want string+ }{+ {name: "resume landed", resumeExpected: true, resumeLanded: true, want: "do the thing"},+ {name: "resume missed", resumeExpected: true, resumeLanded: false, want: notice + "do the thing"},+ {name: "no resume expected", resumeExpected: false, resumeLanded: false, want: "do the thing"},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := hermesTurnText("do the thing", tt.resumeExpected, tt.resumeLanded, notice); got != tt.want {+ t.Fatalf("hermesTurnText() = %q, want %q", got, tt.want)+ }+ })+ }+}++// TestHermesBackendSurfacesSilentSessionRebind is the end-to-end shape of+// GH #6806: hermes answers session/resume for a session it no longer holds by+// creating a fresh one and replying with an ordinary success frame. The turn+// must run under the NEW id and carry the continuity notice, instead of+// reporting the dead id back as if the conversation had continued.+func TestHermesBackendSurfacesSilentSessionRebind(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ tests := []struct {+ name string+ servedID string+ wantSessionID string+ wantNotice bool+ }{+ {+ name: "rebound session surfaces the loss",+ servedID: "ses_new",+ wantSessionID: "ses_new",+ wantNotice: true,+ },+ {+ name: "real resume says nothing",+ servedID: "ses_old",+ wantSessionID: "ses_old",+ wantNotice: false,+ },+ }++ const notice = "CONTINUITY NOTICE: the prior session is gone.\n\n"++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ tempDir := t.TempDir()+ fakePath := filepath.Join(tempDir, "hermes")+ capturePath := filepath.Join(tempDir, "prompt.json")+ script := `#!/bin/sh+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"+ ;;+ *'"method":"session/resume"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"_meta":{"hermes":{"sessionProvenance":{"acpSessionId":"'"$HERMES_TEST_SERVED_ID"'"}}}}}\n' "$id"+ ;;+ *'"method":"session/prompt"'*)+ printf '%s' "$line" > "$HERMES_TEST_CAPTURE"+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"+ exit 0+ ;;+ esac+done+`+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("hermes", Config{+ ExecutablePath: fakePath,+ Logger: slog.Default(),+ Env: map[string]string{+ "HERMES_TEST_CAPTURE": capturePath,+ "HERMES_TEST_SERVED_ID": tt.servedID,+ },+ })+ if err != nil {+ t.Fatalf("new hermes backend: %v", err)+ }++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()+ session, err := backend.Execute(ctx, "do the thing", ExecOptions{+ ResumeSessionID: "ses_old",+ ResumeExpected: true,+ ResumeContinuityNotice: notice,+ Timeout: 10 * time.Second,+ })+ if err != nil {+ t.Fatalf("execute: %v", err)+ }+ for range session.Messages {+ }++ select {+ case result := <-session.Result:+ if result.SessionID != tt.wantSessionID {+ t.Fatalf("result.SessionID = %q, want %q", result.SessionID, tt.wantSessionID)+ }+ case <-time.After(10 * time.Second):+ t.Fatal("timeout waiting for terminal result")+ }++ captured, err := os.ReadFile(capturePath)+ if err != nil {+ t.Fatalf("read captured prompt: %v", err)+ }+ var frame struct {+ Params struct {+ Prompt []struct {+ Text string `json:"text"`+ } `json:"prompt"`+ } `json:"params"`+ }+ if err := json.Unmarshal(captured, &frame); err != nil {+ t.Fatalf("parse captured prompt %q: %v", captured, err)+ }+ if len(frame.Params.Prompt) != 1 {+ t.Fatalf("prompt blocks = %d, want 1", len(frame.Params.Prompt))+ }+ text := frame.Params.Prompt[0].Text+ if gotNotice := strings.HasPrefix(text, notice); gotNotice != tt.wantNotice {+ t.Fatalf("prompt carries notice = %v, want %v (prompt %q)", gotNotice, tt.wantNotice, text)+ }+ if !strings.HasSuffix(text, "do the thing") {+ t.Fatalf("prompt %q lost the original task text", text)+ }+ })+ }+}