Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5932: fix(daemon): give Hermes agents memory that survives the task (#6693)
Bohan Jiangf26b97e395f5
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex d5f5c7b329..7a863fe611 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -220,6 +220,7 @@ Daemon behavior is configured via flags or environment variables:| GC artifact TTL (open issues) | — | `MULTICA_GC_ARTIFACT_TTL` | `12h` (set `0` to disable) || GC artifact patterns | — | `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` || GC repo cache TTL (`.repos`) | — | `MULTICA_GC_REPO_TTL` | `720h` (30d; set `0` to disable) |+| GC Hermes memory TTL (per-agent `memories/`) | — | `MULTICA_GC_HERMES_MEMORY_TTL` | `2160h` (90d; set `0` to disable) |#### Workspace garbage collection@@ -231,6 +232,8 @@ The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk space- **Repo cache eviction** — the bare git clones under `.repos/` are shared object stores: each task workdir is a `git worktree` off one of them rather than its own clone, so a task's `.git` is only a pointer file. They are evicted only when all of the following hold: the repo is no longer attached to any workspace this daemon watches, it has no worktrees left, and no task has created a worktree from it for `MULTICA_GC_REPO_TTL`. A cache created before this stamp existed is not treated as ancient — its clock starts at the first GC cycle that sees it, so upgrading does not wipe every cache. Evicting is safe by construction: the next task that needs the repo re-clones it on demand, so a wrong eviction costs a clone, not a failure.+- **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`.`multica daemon disk-usage` reports the `.repos` footprint on its own line rather than folding it into the per-task totals — every task in a workspace checks out from that shared cache, so attributing it to individual task directories would double-count it. Note that the repo cache is reclaimed on the schedule above and not by any per-issue status change, so it is normal for it to persist after every task directory is gone.@@ -260,6 +263,7 @@ Agent-specific overrides:| `MULTICA_OPENCLAW_MODEL` | Override the OpenClaw model used || `MULTICA_HERMES_PATH` | Custom path to the `hermes` binary || `MULTICA_HERMES_MODEL` | Override the Hermes model used |+| `MULTICA_HERMES_TASK_MEMORY` | Revert Hermes memory to a fresh task-local `memories/` per task (see [Hermes agent memory](#hermes-agent-memory)) || `MULTICA_PI_PATH` | Custom path to the `pi` binary || `MULTICA_PI_MODEL` | Override the Pi model used || `MULTICA_CURSOR_PATH` | Custom path to the `cursor-agent` binary |@@ -305,6 +309,25 @@ If a configured server produces no tools, check the daemon log for those warningThe daemon launches QwenPaw as `qwenpaw acp --workspace <per-task dir>`. It writes the task brief to `AGENTS.md`, and materialises the run's bound skills into `<per-task dir>/skills/` plus a `skill.json` manifest, so QwenPaw discovers them through its own workspace skill discovery. `acp` and `--workspace` are reserved: `custom_args` cannot override them. QwenPaw is the one runtime with no `MULTICA_QWENPAW_MODEL`: its `session/set_model` writes to a shared, persistent agent config rather than the session, so Multica never sends it a model and leaves that choice to QwenPaw's own configuration.+#### Hermes agent memory++Hermes discovers skills only from its own home, so binding Multica skills to a Hermes agent makes the daemon build a per-task `HERMES_HOME` overlay for that agent. The agent's long-term memory (`memories/`) does **not** live inside that task-scoped overlay: it is linked to a persistent store at++```+<profile dir>/hermes-state/<agent-id>/<hermes-profile>/+```++so the same agent keeps its memory across tasks and issues. `<hermes-profile>` is the profile the agent resolves to (`default`, a named profile from `-p/--profile` or `active_profile`, or a hash for an out-of-tree custom `HERMES_HOME`) — pointing an agent at a different profile gives it a different memory line, matching Hermes' own "a profile is an isolated instance" model.++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.+- **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.+- **A Hermes agent with no skills bound gets no overlay at all** and therefore still runs against the user's real `~/.hermes`, memory included — unchanged behaviour.+- `MULTICA_HERMES_TASK_MEMORY=1` on the daemon reverts to the previous behaviour, a fresh task-local `memories/` per task.+`MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, `MULTICA_CODEBUDDY_ARGS`, `MULTICA_QWEN_ARGS`, and `MULTICA_QWENPAW_ARGS` are parsed with POSIX shellword quoting, so values such as `--model "gpt-5.1 codex" --sandbox read-only` are split like a shell command line. Agent arguments are applied in this order: hardcoded Multica defaults, daemon-wide env defaults, then per-agent `custom_args` from the task.### Self-Hosted Serverdiff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 59e6b9128b..d94dd1aab7 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -70,6 +70,7 @@ const (DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issuesDefaultGCCodexSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-issue Codex session stores untouched this long+ DefaultGCHermesMemoryTTL = 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)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)@@ -105,6 +106,7 @@ type Config struct {GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)GCRepoTTL time.Duration // evict a cached bare repo under .repos once no task has created a worktree from it for this long, it has no worktrees left, and it is no longer attached to any watched workspace (default: 30d, set 0 to disable)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)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)@@ -420,6 +422,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ gcHermesMemoryTTL, err := durationFromEnv("MULTICA_GC_HERMES_MEMORY_TTL", DefaultGCHermesMemoryTTL)+ if err != nil {+ return Config{}, err+ }gcRepoTTL, err := durationFromEnv("MULTICA_GC_REPO_TTL", DefaultGCRepoTTL)if err != nil {return Config{}, err@@ -476,6 +482,7 @@ func LoadConfig(overrides Overrides) (Config, error) {GCArtifactPatterns: gcArtifactPatterns,GCRepoTTL: gcRepoTTL,GCCodexSessionTTL: gcCodexSessionTTL,+ GCHermesMemoryTTL: gcHermesMemoryTTL,AutoUpdateEnabled: autoUpdateEnabled,AutoUpdateCheckInterval: autoUpdateInterval,AutoReloadEnabled: autoReloadEnabled,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 32f1d7d762..be555e9a6c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -511,10 +511,10 @@ type Daemon struct {activeEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)deletingEnvRoots map[string]bool // env roots reserved by GC; new tasks wait until the mutation finishes- activeCodexStoresMu sync.Mutex- activeCodexStoresCond *sync.Cond // signalled when an in-flight store deletion finishes, so a blocked markActive can proceed- activeCodexStores map[string]int // per-conversation Codex session store path -> live-task refcount; guards the store from GC mid-task (MUL-4424)- deletingCodexStores map[string]bool // store paths a GC delete has reserved; markActive waits these out so a task never mounts a store mid-removal+ activeStoresMu sync.Mutex+ activeStoresCond *sync.Cond // signalled when an in-flight store deletion finishes, so a blocked markActive can proceed+ activeStores map[string]int // persistent store path (per-conversation Codex sessions, per-agent Hermes memories) -> live-task refcount; guards the store from GC mid-task (MUL-4424)+ deletingStores map[string]bool // store paths a GC delete has reserved; markActive waits these out so a task never mounts a store mid-removal// localPathLocks serialises agent tasks whose project resource is a// local_directory pinned to this daemon. Two tasks targeting the same@@ -575,8 +575,8 @@ func New(cfg Config, logger *slog.Logger) *Daemon {wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),deletingEnvRoots: make(map[string]bool),- activeCodexStores: make(map[string]int),- deletingCodexStores: make(map[string]bool),+ activeStores: make(map[string]int),+ deletingStores: make(map[string]bool),localPathLocks: NewLocalPathLocker(),runtimeGoneInflight: make(map[string]struct{}),pendingWorkInflight: make(map[string]struct{}),@@ -590,7 +590,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {wsRPC: newWSRPCClient(wsRPCResponseGrace),}d.activeEnvRootsCond = sync.NewCond(&d.activeEnvRootsMu)- d.activeCodexStoresCond = sync.NewCond(&d.activeCodexStoresMu)+ d.activeStoresCond = sync.NewCond(&d.activeStoresMu)// Seed the copy-on-write availability set from the startup probe. Callers// must go through d.agents() from here on; cfg.Agents is the initial value// only and does not track later refreshes.@@ -5847,6 +5847,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ivar hermesSourceHome stringvar hermesSourceMustExist boolvar hermesEnv map[string]string+ var hermesMemoryStore stringif provider == "hermes" {sel := agent.ParseHermesProfileArgs(agentCustomArgs)res := execenv.ResolveHermesProfile(agentEnvOverrides["HERMES_HOME"], sel.Name, sel.Found, sel.Inline)@@ -5860,6 +5861,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ihermesEnv = map[string]string{}}hermesEnv["HERMES_HOME"] = res.SourceHome+ // The overlay links memories/ here so the agent's long-term memory+ // survives the task instead of being reset by every run (#6638). Keyed on+ // the resolved source home so switching an agent's profile switches its+ // memory line, matching Hermes' own "a profile is an isolated instance"+ // model. Guarded from the GC for the whole task, as the Codex store below.+ if store := execenv.HermesMemoryStorePath(d.cfg.Profile, task.AgentID, res.SourceHome); store != "" {+ hermesMemoryStore = store+ d.markActiveStore(store)+ defer d.unmarkActiveStore(store)+ }}// Guard this task's per-issue Codex session store from the GC for the whole// task, starting before Prepare/Reuse mounts it — so a prune that samples the@@ -5867,8 +5878,8 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// of a long-idle issue (MUL-4424). No-op for non-Codex tasks / no stable key.if provider == "codex" {if store := execenv.CodexSessionStorePath(d.cfg.Profile, taskCtx); store != "" {- d.markActiveCodexStore(store)- defer d.unmarkActiveCodexStore(store)+ d.markActiveStore(store)+ defer d.unmarkActiveStore(store)}}if shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot) {@@ -5887,6 +5898,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iHermesSourceHome: hermesSourceHome,HermesSourceMustExist: hermesSourceMustExist,HermesEnv: hermesEnv,+ HermesMemoryStore: hermesMemoryStore,CodexCustomArgs: codexSandboxArgs,Task: taskCtx,})@@ -5911,6 +5923,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iHermesSourceHome: hermesSourceHome,HermesSourceMustExist: hermesSourceMustExist,HermesEnv: hermesEnv,+ HermesMemoryStore: hermesMemoryStore,CodexCustomArgs: codexSandboxArgs,Task: taskCtx,}@@ -7350,56 +7363,58 @@ func (d *Daemon) reserveEnvRootForGC(envRoot string) (release func(), ok bool) {}, true}-// markActiveCodexStore records that a task is about to use the given per-issue-// Codex session store, so the GC never reclaims it mid-task — the store lives-// outside the env root, so isActiveEnvRoot does not cover it (MUL-4424). If a GC+// markActiveStore records that a task is about to use the given persistent+// store — a per-issue Codex session store or a per-agent Hermes memory store —+// so the GC never reclaims it mid-task. These stores live outside the env root,+// so isActiveEnvRoot does not cover them (MUL-4424). If a GC// delete has already reserved this store, we wait for that removal to finish// before claiming it, so a task never mounts a store mid-removal; the store is// then recreated fresh by Prepare. Reference-counted like the env-root guard.-func (d *Daemon) markActiveCodexStore(store string) {+func (d *Daemon) markActiveStore(store string) {if store == "" {return}- d.activeCodexStoresMu.Lock()- defer d.activeCodexStoresMu.Unlock()- for d.deletingCodexStores[store] {- d.activeCodexStoresCond.Wait()+ d.activeStoresMu.Lock()+ defer d.activeStoresMu.Unlock()+ for d.deletingStores[store] {+ d.activeStoresCond.Wait()}- d.activeCodexStores[store]+++ d.activeStores[store]++}-func (d *Daemon) unmarkActiveCodexStore(store string) {+func (d *Daemon) unmarkActiveStore(store string) {if store == "" {return}- d.activeCodexStoresMu.Lock()- defer d.activeCodexStoresMu.Unlock()- if d.activeCodexStores[store] <= 1 {- delete(d.activeCodexStores, store)+ d.activeStoresMu.Lock()+ defer d.activeStoresMu.Unlock()+ if d.activeStores[store] <= 1 {+ delete(d.activeStores, store)return}- d.activeCodexStores[store]--+ d.activeStores[store]--}-// reserveCodexStoreForDeletion atomically checks that no live task holds store+// reserveStoreForDeletion atomically checks that no live task holds store// and, if so, marks it reserved so no task can claim it until the caller runs// the returned commit (after the actual removal). ok=false means a task holds it-// — do not delete. This is the exclusive protocol PruneCodexSessionStores needs:+// — do not delete. This is the exclusive protocol the store pruners+// (PruneCodexSessionStores, PruneHermesMemoryStores) need:// the "confirm inactive" and the mark happen under one lock acquisition, so a-// markActiveCodexStore either loses the check (store stays) or blocks on the+// markActiveStore either loses the check (store stays) or blocks on the// reservation, closing the stat->remove race (MUL-4424).-func (d *Daemon) reserveCodexStoreForDeletion(store string) (commit func(), ok bool) {- d.activeCodexStoresMu.Lock()- defer d.activeCodexStoresMu.Unlock()- if d.activeCodexStores[store] > 0 || d.deletingCodexStores[store] {+func (d *Daemon) reserveStoreForDeletion(store string) (commit func(), ok bool) {+ d.activeStoresMu.Lock()+ defer d.activeStoresMu.Unlock()+ if d.activeStores[store] > 0 || d.deletingStores[store] {return nil, false}- d.deletingCodexStores[store] = true+ d.deletingStores[store] = truereturn func() {- d.activeCodexStoresMu.Lock()- delete(d.deletingCodexStores, store)- d.activeCodexStoresCond.Broadcast()- d.activeCodexStoresMu.Unlock()+ d.activeStoresMu.Lock()+ delete(d.deletingStores, store)+ d.activeStoresCond.Broadcast()+ d.activeStoresMu.Unlock()}, true}diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex d2905d1db2..368106cf3b 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1984,10 +1984,10 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {// store guard initialised — enough to exercise the reserve-vs-mark protocol.func newCodexStoreGuardDaemon() *Daemon {d := &Daemon{- activeCodexStores: map[string]int{},- deletingCodexStores: map[string]bool{},+ activeStores: map[string]int{},+ deletingStores: map[string]bool{},}- d.activeCodexStoresCond = sync.NewCond(&d.activeCodexStoresMu)+ d.activeStoresCond = sync.NewCond(&d.activeStoresMu)return d}@@ -1999,13 +1999,13 @@ func TestCodexStoreGuard_MarkBeforeReserveBlocksDeletion(t *testing.T) {d := newCodexStoreGuardDaemon()const store = "/stores/agent/issue"- d.markActiveCodexStore(store)- if _, ok := d.reserveCodexStoreForDeletion(store); ok {+ d.markActiveStore(store)+ if _, ok := d.reserveStoreForDeletion(store); ok {t.Fatal("reserve must refuse a store a live task already holds")}- d.unmarkActiveCodexStore(store)+ d.unmarkActiveStore(store)- commit, ok := d.reserveCodexStoreForDeletion(store)+ commit, ok := d.reserveStoreForDeletion(store)if !ok {t.Fatal("reserve should succeed once the store is inactive")}@@ -2020,20 +2020,20 @@ func TestCodexStoreGuard_ReserveBlocksMarkUntilCommit(t *testing.T) {d := newCodexStoreGuardDaemon()const store = "/stores/agent/issue"- commit, ok := d.reserveCodexStoreForDeletion(store)+ commit, ok := d.reserveStoreForDeletion(store)if !ok {t.Fatal("reserve should succeed on an inactive store")}marked := make(chan struct{})go func() {- d.markActiveCodexStore(store)+ d.markActiveStore(store)close(marked)}()select {case <-marked:- t.Fatal("markActiveCodexStore must block while the store is reserved for deletion")+ t.Fatal("markActiveStore must block while the store is reserved for deletion")case <-time.After(100 * time.Millisecond):}@@ -2042,10 +2042,10 @@ func TestCodexStoreGuard_ReserveBlocksMarkUntilCommit(t *testing.T) {select {case <-marked:case <-time.After(2 * time.Second):- t.Fatal("markActiveCodexStore must proceed after the reservation is committed")+ t.Fatal("markActiveStore must proceed after the reservation is committed")}// The store is now active, so a fresh reserve must be refused.- if _, ok := d.reserveCodexStoreForDeletion(store); ok {+ if _, ok := d.reserveStoreForDeletion(store); ok {t.Fatal("store must be active after the blocked mark proceeds")}}@@ -2057,15 +2057,15 @@ func TestCodexStoreGuard_SecondReserveRefusedWhileDeleting(t *testing.T) {d := newCodexStoreGuardDaemon()const store = "/stores/agent/issue"- commit, ok := d.reserveCodexStoreForDeletion(store)+ commit, ok := d.reserveStoreForDeletion(store)if !ok {t.Fatal("first reserve should succeed")}- if _, ok := d.reserveCodexStoreForDeletion(store); ok {+ if _, ok := d.reserveStoreForDeletion(store); ok {t.Fatal("a second reserve must be refused while a removal is in flight")}commit()- commit2, ok := d.reserveCodexStoreForDeletion(store)+ commit2, ok := d.reserveStoreForDeletion(store)if !ok {t.Fatal("reserve should succeed again after the prior removal committed")}diff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.goindex cab27a3771..4c6871fd14 100644--- a/server/internal/daemon/execenv/codex_home.go+++ b/server/internal/daemon/execenv/codex_home.go@@ -393,25 +393,25 @@ func codexSessionStoreNamespace(profile string) string {// direct chats use a prefixed chat_session_id so the two namespaces cannot// collide. Returns "" when neither stable identifier is available.func codexSessionStoreKey(profile string, task TaskContextForEnv) string {- storeID := sanitizeCodexPathSegment(task.IssueID)+ storeID := sanitizePathSegment(task.IssueID)if storeID == "" {- chatID := sanitizeCodexPathSegment(task.ChatSessionID)+ chatID := sanitizePathSegment(task.ChatSessionID)if chatID == "" {return ""}storeID = "chat_" + chatID}- agent := sanitizeCodexPathSegment(task.AgentID)+ agent := sanitizePathSegment(task.AgentID)if agent == "" {agent = "_"}return filepath.Join(codexSessionStoreNamespace(profile), agent, storeID)}-// sanitizeCodexPathSegment reduces s to the characters a UUID uses (hex plus+// sanitizePathSegment reduces s to the characters a UUID uses (hex plus// dashes/underscores), dropping everything else so the result is always a single// safe path segment — no separators, no "..", no drive letters.-func sanitizeCodexPathSegment(s string) string {+func sanitizePathSegment(s string) string {var b strings.Builderfor _, r := range s {switch {diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 8ebe7d67de..225f97b024 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -77,6 +77,11 @@ type PrepareParams struct {// is absent — set when an explicit named profile was requested so a typo// doesn't silently seed from an empty home and drop the user's auth/config.HermesSourceMustExist bool+ // HermesMemoryStore is the agent's persistent Hermes memory store+ // (HermesMemoryStorePath) the overlay links memories/ to, so memory outlives+ // the task. Empty keeps memories/ task-local — no agent to key on, or the+ // MULTICA_HERMES_TASK_MEMORY rollback switch is engaged.+ HermesMemoryStore 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.@@ -380,7 +385,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {// hermes_home.go.if params.Provider == "hermes" && len(params.Task.AgentSkills) > 0 {hermesHome := filepath.Join(envRoot, "hermes-home")- if err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, logger); err != nil {+ if err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, logger); err != nil {return nil, fmt.Errorf("execenv: prepare hermes-home: %w", err)}env.HermesHome = hermesHome@@ -474,12 +479,13 @@ type ReuseParams struct {// loop) keep the "never delete the user's directory" invariant on// reuse paths.LocalDirectory bool- // HermesSourceHome and HermesEnv mirror PrepareParams on reuse so the Hermes- // overlay re-derives against the agent's current source home / profile and- // external_dirs vars.+ // HermesSourceHome, 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 stringHermesSourceMustExist boolHermesEnv map[string]string+ HermesMemoryStore string// CodexCustomArgs mirrors PrepareParams.CodexCustomArgs on reuse so the// Windows sandbox decision honors a `-c windows.sandbox=...` override here// too (MUL-4957).@@ -629,7 +635,7 @@ 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, logger); err != nil {+ if err := prepareHermesHome(hermesHome, params.HermesSourceHome, params.HermesSourceMustExist, params.Task.AgentSkills, params.HermesEnv, params.HermesMemoryStore, logger); err != nil {// Fail closed: a half-built overlay must not run. Returning nil// makes the daemon fall back to a fresh Prepare, whose error// then blocks dispatch rather than silently dropping the bounddiff --git a/server/internal/daemon/execenv/hermes_home.go b/server/internal/daemon/execenv/hermes_home.goindex f54ff17a2b..d8dab795c9 100644--- a/server/internal/daemon/execenv/hermes_home.go+++ b/server/internal/daemon/execenv/hermes_home.go@@ -40,10 +40,12 @@ import (// the user's global/builtin skills read-only without copying them;// - populates the task-local `skills/` dir with ONLY the Multica-bound skills,// which take precedence because Hermes lists the home skills dir first;-// - keeps `memories/` overlay-owned (a fresh per-task dir), NOT symlinked to-// the shared home: Hermes loads and writes back MEMORY.md/USER.md there, and-// per-agent memory is a Multica product concern — the host's local Hermes-// memory must not bleed into a task, nor task memory back out to the host;+// - keeps `memories/` overlay-owned, NOT symlinked to the shared home: Hermes+// loads and writes back MEMORY.md/USER.md there, and per-agent memory is a+// Multica product concern — the host's local Hermes memory must not bleed+// into a task, nor task memory back out to the host. The overlay links it to+// 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;@@ -63,7 +65,7 @@ import (// reconciliation:// - skills/ task-local, only the bound skills// - config.yaml derived config with absolutized external_dirs-// - memories/ fresh per-task dir, isolated from the host's memory+// - memories/ link to the agent's persistent store, isolated from the host// - marker below records that legacy shared SQLite state was detached//// The state.db SQLite family is classified dynamically by@@ -366,8 +368,10 @@ func hermesProfileDir(root, name string) (home string, mustExist bool, err error// source home is absent — set for an explicitly named profile so a typo doesn't// silently seed from an empty dir and drop the user's auth/config. env is the// sanitized effective env used to expand ${VAR} in external_dirs so it matches-// what the Hermes child sees.-func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, logger *slog.Logger) error {+// what the Hermes child sees. memoryStore is the agent's persistent memory store+// (execenv.HermesMemoryStorePath) that memories/ is linked to; empty keeps the+// pre-MUL-5932 task-local dir, which is what the rollback switch produces.+func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workspaceSkills []SkillContextForEnv, env map[string]string, memoryStore string, logger *slog.Logger) error {sharedHome := strings.TrimSpace(sourceHome)if sharedHome == "" {sharedHome = platformDefaultHermesHome()@@ -389,9 +393,14 @@ func prepareHermesHome(hermesHome, sourceHome string, sourceMustExist bool, workif err := prepareHermesTaskLocalState(hermesHome); err != nil {return fmt.Errorf("prepare task-local state: %w", err)}- // Fresh, isolated per-task memories dir (idempotent — preserved across reuse- // so the task/issue lifecycle keeps its own memory).- if err := os.MkdirAll(filepath.Join(hermesHome, "memories"), 0o700); err != nil {+ // 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 the rollback switch is engaged). See hermes_memory.go.+ if memoryStore != "" {+ if err := mountHermesMemories(hermesHome, memoryStore, logger); err != nil {+ return fmt.Errorf("mount agent memories: %w", err)+ }+ } else if err := detachHermesMemories(hermesHome); err != nil {return fmt.Errorf("create task memories dir: %w", err)}diff --git a/server/internal/daemon/execenv/hermes_home_test.go b/server/internal/daemon/execenv/hermes_home_test.goindex b25b0d328c..7af492ac11 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.gonew file mode 100644index 0000000000..a63a2449a6--- /dev/null+++ b/server/internal/daemon/execenv/hermes_memory.go@@ -0,0 +1,493 @@+package execenv++import (+ "crypto/sha256"+ "encoding/hex"+ "fmt"+ "io/fs"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "time"++ "github.com/multica-ai/multica/server/internal/cli"+)++// Background+//+// Hermes keeps its long-term memory (MEMORY.md / USER.md and whatever else the+// agent writes back) in `<HERMES_HOME>/memories/`. Multica has to take over+// HERMES_HOME to inject an agent's bound skills — Hermes discovers skills only+// from its own home, never from the workspace (see hermes_home.go) — so the+// overlay inherited the decision of where memory lives and made it task-local.+//+// Nobody designed the two behaviours that produced (issue #6638):+//+// - An agent WITH skills bound got a fresh memories/ per task, so it forgot+// everything between tasks. Users read that as "Hermes 失忆", and it changed+// the moment they bound an unrelated skill, with no UI signal.+// - An agent with NO skills bound built no overlay at all, ran against the+// user's real ~/.hermes, and therefore shared one memories/ with every+// other skill-less agent, task, and issue on the runtime.+//+// This file makes memory an agent-scoped store Multica owns:+//+// <multica profile dir>/hermes-state/<agent>/<hermes profile>/memories+//+// linked into the per-task overlay. Memory then survives across tasks and issues+// for the same agent, never touches the user's home, and is invisible to other+// agents. The shape is deliberately identical to the per-issue Codex session+// store (codex_home.go) and the per-agent Reasonix state home — same lifecycle,+// same GC, same active-store guard.+//+// Scoping to (hermes profile, agent) rather than agent alone mirrors Hermes' own+// model, where a profile is an isolated instance: pointing an agent at a+// different profile gives it a different identity, so it gets a different memory+// line. Same semantics as the Codex store keying on (profile, agent, issue).+//+// Deliberately NOT covered here:+//+// - The session database (state.db and its WAL sidecars) stays task-local.+// Sharing a live SQLite database between one agent's concurrent tasks needs+// lock and consistency work — plus Windows byte-range locks on -shm — that+// plain memory files do not. Users get "remembers the agreements", not+// "remembers the transcript".+// - Skill-less Hermes agents still run against the host home unchanged.+// Tightening that would break the only workaround #6638's reporter has, and+// it belongs with the platform-wide memory_scope work (MUL-5969).+//+// Known trade-off, shared with the host-passthrough behaviour it replaces: one+// agent's concurrent tasks write the same files and Hermes rewrites them whole,+// so concurrent memory updates are last-writer-wins.++// hermesMemoryStoreRoot is the directory under the daemon's Multica profile dir+// that holds every agent's persistent Hermes state. `hermes-state` (not+// `hermes-memories`) because state.db joins it when the session half is solved.+const hermesMemoryStoreRoot = "hermes-state"++// hermesMemoriesEntry is the name of the memory directory inside both the store+// and the overlay home — Hermes resolves it relative to HERMES_HOME.+const hermesMemoriesEntry = "memories"++// MulticaHermesTaskMemoryEnv is the rollback switch. Anything truthy (1, true,+// yes, on; case-insensitive) restores the pre-MUL-5932 behaviour of a fresh+// task-local memories/ dir per task, for an operator who needs to revert without+// waiting for a release. Everything else (including unset) keeps memory+// agent-scoped and persistent.+const MulticaHermesTaskMemoryEnv = "MULTICA_HERMES_TASK_MEMORY"++// hermesTaskLocalMemoryForced reports whether the rollback switch is engaged.+func hermesTaskLocalMemoryForced() bool {+ switch strings.ToLower(strings.TrimSpace(os.Getenv(MulticaHermesTaskMemoryEnv))) {+ case "1", "true", "yes", "on":+ return true+ }+ return false+}++// HermesMemoryStorePath returns the persistent memory store for (daemonProfile,+// agentID, sourceHome), or "" when memory must stay task-local — the rollback+// switch is engaged, there is no agent to key on, or the Multica profile dir+// cannot be resolved. The daemon marks the returned path in-use for the task's+// duration so PruneHermesMemoryStores never reclaims it mid-mount.+//+// daemonProfile namespaces by Multica profile for free: profile dirs are already+// disjoint, so a staging daemon's GC can never see a production daemon's stores+// and no hashed namespace segment is needed (unlike the Codex store, which lives+// in the shared ~/.codex).+func HermesMemoryStorePath(daemonProfile, agentID, sourceHome string) string {+ if hermesTaskLocalMemoryForced() {+ return ""+ }+ agent := sanitizePathSegment(agentID)+ if agent == "" {+ return ""+ }+ profileDir, err := cli.ProfileDir(daemonProfile)+ if err != nil {+ return ""+ }+ return filepath.Join(profileDir, hermesMemoryStoreRoot, agent, hermesMemoryProfileSegment(sourceHome))+}++// hermesMemoryProfileSegment maps a resolved Hermes source home to the store+// segment that identifies it. Named profiles and the default home keep their+// readable name so an operator (and the documented one-off import) can find the+// directory; an out-of-tree custom HERMES_HOME falls back to a hash of its path,+// which is opaque but cannot collide with a differently-located home of the same+// basename.+func hermesMemoryProfileSegment(sourceHome string) string {+ home := strings.TrimSpace(sourceHome)+ if home == "" {+ return "default"+ }+ if abs, err := filepath.Abs(home); err == nil {+ home = abs+ }+ home = filepath.Clean(home)+ nativeRoot := filepath.Clean(platformDefaultHermesHome())+ if home == nativeRoot {+ return "default"+ }+ // <root>/profiles/<name> — the shape ResolveHermesProfile produces for an+ // explicit -p/--profile, a sticky active_profile, or a profile-scoped+ // custom_env HERMES_HOME. Profiles of the native root keep their bare name;+ // a profile of some other root gets its root hashed in, so `<a>/profiles/x`+ // and `<b>/profiles/x` cannot share one memory line.+ if root := filepath.Dir(filepath.Dir(home)); filepath.Base(filepath.Dir(home)) == "profiles" {+ if name := sanitizePathSegment(filepath.Base(home)); name != "" {+ if root == nativeRoot {+ return name+ }+ return name + "_" + hashHermesHomePath(root)+ }+ }+ return "h_" + hashHermesHomePath(home)+}++// hashHermesHomePath returns a short, filesystem-safe digest of an absolute+// home path — enough to keep two same-named homes in different locations apart+// without pushing the segment near the 255-byte filename limit.+func hashHermesHomePath(path string) string {+ sum := sha256.Sum256([]byte(path))+ return hex.EncodeToString(sum[:8])+}++// mountHermesMemories points the overlay's memories/ at storeDir, so the agent's+// memory outlives the task. Idempotent across Reuse: a link already pointing at+// the store is left alone.+//+// A real memories/ directory left by an older daemon (or by a task that ran with+// the rollback switch on) is migrated into the store rather than discarded — but+// only into an empty store, so an upgrade never overwrites memory the agent has+// already accumulated. A migration that cannot complete fails the overlay rather+// than dropping the directory it could not carry over.+func mountHermesMemories(hermesHome, storeDir string, logger *slog.Logger) error {+ dst := filepath.Join(hermesHome, hermesMemoriesEntry)++ if fi, err := os.Lstat(dst); err == nil {+ if fi.Mode()&os.ModeSymlink != 0 {+ if target, rlErr := os.Readlink(dst); rlErr == nil && filepath.Clean(target) == filepath.Clean(storeDir) {+ if err := os.MkdirAll(storeDir, 0o700); err != nil {+ return fmt.Errorf("create hermes memory store %s: %w", storeDir, err)+ }+ touchHermesMemoryStore(storeDir, logger)+ return nil+ }+ } else if fi.IsDir() {+ // Runs before the store dir is created, so migration can publish a+ // fully-copied tree with one atomic rename. Fails closed: the source+ // dir below is only removed once every entry is safely in the store.+ if err := migrateHermesTaskMemories(dst, storeDir, logger); err != nil {+ return err+ }+ }+ if err := os.RemoveAll(dst); err != nil {+ return fmt.Errorf("remove stale memories path %s: %w", dst, err)+ }+ } else if !os.IsNotExist(err) {+ return fmt.Errorf("stat memories path %s: %w", dst, err)+ }++ if err := os.MkdirAll(storeDir, 0o700); err != nil {+ return fmt.Errorf("create hermes memory store %s: %w", storeDir, err)+ }+ if err := createDirLink(storeDir, dst); err != nil {+ return fmt.Errorf("link memories to store %s: %w", storeDir, 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 agent's memory+ // right as a task picks it back up.+ touchHermesMemoryStore(storeDir, logger)+ return nil+}++// migrateHermesTaskMemories copies the contents of a pre-existing task-local+// memories dir into an empty store, so upgrading a daemon does not drop what an+// in-flight task had already remembered.+//+// The caller removes the source directory as soon as this returns nil, so+// "nil" has to mean "the source is safe to delete" and nothing else. Three+// rules follow from that:+//+// - It copies rather than moves. A move is faster but fails across+// filesystems — the workspaces root and the Multica profile dir can be on+// different volumes — and a partial move leaves data in neither place.+// - It never reports success for anything it did not carry over. An I/O+// error reading either directory, or an entry it will not copy (symlink,+// device node — a link copied verbatim could point the store outside+// itself), is an error, not a silent skip.+// - It publishes with a single atomic rename from a staging directory, so+// two tasks of the same agent migrating at once cannot interleave into one+// half-populated store. First writer wins; the loser discards its staging+// and takes the winner's store, which is the same outcome as finding a+// store that was already populated.+//+// Only an absent or empty store is migrated into, so an upgrade never+// overwrites memory the agent has already accumulated.+func migrateHermesTaskMemories(taskDir, storeDir string, logger *slog.Logger) error {+ stored, err := os.ReadDir(storeDir)+ switch {+ case err == nil && len(stored) > 0:+ return nil // store already holds this agent's memory — never overwrite it+ case err != nil && !os.IsNotExist(err):+ // Treating this as "nothing to migrate" would delete the source below.+ return fmt.Errorf("read hermes memory store %s: %w", storeDir, err)+ }++ entries, err := os.ReadDir(taskDir)+ if err != nil {+ return fmt.Errorf("read task-local hermes memories %s: %w", taskDir, err)+ }+ if len(entries) == 0 {+ return nil+ }++ staging, err := newHermesMemoryStaging(storeDir)+ if err != nil {+ return err+ }+ defer os.RemoveAll(staging) // no-op once the staging dir has been promoted++ for _, entry := range entries {+ src := filepath.Join(taskDir, entry.Name())+ if err := copyHermesMemoryEntry(src, filepath.Join(staging, entry.Name()), entry); err != nil {+ return fmt.Errorf("migrate task-local hermes memory %s into %s: %w", src, storeDir, err)+ }+ }++ promoted, err := promoteHermesMemoryStaging(staging, storeDir)+ if err != nil {+ return err+ }+ if !promoted {+ logger.Info("execenv: another task populated the hermes memory store first; keeping it", "store", storeDir)+ return nil+ }+ logger.Info("execenv: migrated task-local hermes memories into agent store", "store", storeDir, "entries", len(entries))+ return nil+}++// newHermesMemoryStaging creates the scratch directory the 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.+// 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) {+ parent := filepath.Dir(storeDir)+ if err := os.MkdirAll(parent, 0o700); err != nil {+ return "", fmt.Errorf("create hermes memory store parent %s: %w", parent, err)+ }+ staging, err := os.MkdirTemp(parent, "."+filepath.Base(storeDir)+".migrating-")+ if err != nil {+ return "", fmt.Errorf("create hermes memory staging dir in %s: %w", parent, err)+ }+ return staging, nil+}++// promoteHermesMemoryStaging 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+// 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) {+ if err := os.Remove(storeDir); err != nil && !os.IsNotExist(err) {+ if hermesMemoryStorePopulated(storeDir) {+ return false, nil // non-empty: another task published first+ }+ return false, fmt.Errorf("clear empty hermes memory store %s before publishing: %w", storeDir, err)+ }+ if err := os.Rename(staging, storeDir); err != nil {+ if hermesMemoryStorePopulated(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 true, nil+}++// hermesMemoryStorePopulated 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 {+ entries, err := os.ReadDir(storeDir)+ return err == nil && len(entries) > 0+}++// copyHermesMemoryEntry copies one entry of a memories dir into the staging+// tree. Anything that is not a regular file or a directory is refused rather+// than skipped: the caller deletes the source on success, so a silent skip+// would be a silent loss.+func copyHermesMemoryEntry(src, dst string, entry os.DirEntry) error {+ switch {+ case entry.IsDir():+ return copyHermesMemoryTree(src, dst)+ case entry.Type().IsRegular():+ return copyFile(src, dst)+ default:+ return fmt.Errorf("refusing to migrate %s: unsupported entry type %s", src, entry.Type())+ }+}++// copyHermesMemoryTree copies a directory under a memories dir recursively.+// Unlike copyDirTree it refuses (rather than skips) nested symlinks and other+// irregular files, for the same reason: this copy is the only thing standing+// between the source and its deletion.+func copyHermesMemoryTree(src, dst string) error {+ return filepath.WalkDir(src, func(path string, d fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ rel, err := filepath.Rel(src, path)+ if err != nil {+ return err+ }+ target := filepath.Join(dst, rel)+ switch {+ case d.IsDir():+ return os.MkdirAll(target, 0o700)+ case d.Type().IsRegular():+ return copyFile(path, target)+ default:+ return fmt.Errorf("refusing to migrate %s: unsupported entry type %s", path, d.Type())+ }+ })+}++// detachHermesMemories gives the overlay a real, task-local memories dir. It is+// the rollback path (MULTICA_HERMES_TASK_MEMORY), so it must actively replace a+// link left by a previous run against the persistent store: a reused overlay+// still carries that link, and MkdirAll would follow it and silently succeed,+// leaving the task writing to a store the daemon no longer guards from the GC.+// An existing real directory is kept — that is this task's own memory.+func detachHermesMemories(hermesHome string) error {+ dst := filepath.Join(hermesHome, hermesMemoriesEntry)+ if fi, err := os.Lstat(dst); err == nil {+ if fi.Mode()&os.ModeSymlink == 0 && fi.IsDir() {+ return nil+ }+ if err := os.RemoveAll(dst); err != nil {+ return fmt.Errorf("detach memories path %s: %w", dst, err)+ }+ } else if !os.IsNotExist(err) {+ return fmt.Errorf("stat memories path %s: %w", dst, err)+ }+ return os.MkdirAll(dst, 0o700)+}++// touchHermesMemoryStore 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 touchHermesMemoryStore(storeDir string, logger *slog.Logger) {+ now := time.Now()+ if err := os.Chtimes(storeDir, now, now); err != nil {+ logger.Warn("execenv: refresh hermes memory store activity failed", "store", storeDir, "error", err)+ }+}++// PruneHermesMemoryStores reclaims per-agent Hermes memory stores untouched+// within retention. The stores live outside the task-scoped envRoot the task GC+// reclaims — that is the point, memory has to outlive the task — so without this+// a deleted agent's memory would sit on disk forever. retention <= 0 disables+// pruning entirely.+//+// The default retention is deliberately long: unlike Codex rollouts (gigabytes+// of transcript) these are a handful of markdown files, and reclaiming an+// agent's memory is user-visible amnesia, not just a cache miss.+//+// 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 PruneHermesMemoryStores(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, hermesMemoryStoreRoot)+ 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+ }+ kept := 0+ for _, p := range profiles {+ if !p.IsDir() {+ continue+ }+ storeDir := filepath.Join(agentDir, p.Name())+ 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 memory store failed", "store", storeDir, "error", err)+ kept+++ continue+ }+ removed+++ bytesFreed += size+ }+ // Drop the agent dir once its last profile store is gone, so the tree+ // does not leave empty <agent>/ shells behind.+ if kept == 0 {+ _ = os.Remove(agentDir)+ }+ }+ return removed, bytesFreed+}++// hermesMemoryStoreStat walks dir once, returning the newest modification time+// seen (the store's last activity) and its total byte size (for GC accounting).+func hermesMemoryStoreStat(dir string) (newest time.Time, size int64) {+ _ = filepath.WalkDir(dir, func(_ string, d os.DirEntry, err error) error {+ if err != nil {+ return nil+ }+ info, ierr := d.Info()+ if ierr != nil {+ return nil+ }+ if info.ModTime().After(newest) {+ newest = info.ModTime()+ }+ if !d.IsDir() {+ size += info.Size()+ }+ return nil+ })+ return newest, size+}diff --git a/server/internal/daemon/execenv/hermes_memory_test.go b/server/internal/daemon/execenv/hermes_memory_test.gonew file mode 100644index 0000000000..5d71bd1acb--- /dev/null+++ b/server/internal/daemon/execenv/hermes_memory_test.go@@ -0,0 +1,617 @@+package execenv++import (+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "sync"+ "testing"+ "time"+)++// TestHermesMemoryProfileSegment covers the store segment derived from a+// resolved source home: named profiles and the default home stay readable (an+// operator has to be able to find the directory), an out-of-tree custom home+// falls back to a hash of its path.+func TestHermesMemoryProfileSegment(t *testing.T) {+ t.Parallel()++ if got := hermesMemoryProfileSegment(""); got != "default" {+ t.Fatalf("empty source home segment = %q, want default", got)+ }+ if got := hermesMemoryProfileSegment(platformDefaultHermesHome()); got != "default" {+ t.Fatalf("platform default segment = %q, want default", got)+ }+ // A profile of the native root keeps its bare, readable name.+ native := filepath.Join(platformDefaultHermesHome(), "profiles", "research")+ if got := hermesMemoryProfileSegment(native); got != "research" {+ t.Fatalf("native named profile segment = %q, want research", got)+ }+ // Same profile name under a different root must not share a memory line.+ root := t.TempDir()+ foreign := hermesMemoryProfileSegment(filepath.Join(root, "profiles", "research"))+ if foreign == "research" {+ t.Fatalf("foreign-root profile collided with the native one on %q", foreign)+ }+ if !strings.HasPrefix(foreign, "research_") {+ t.Fatalf("foreign-root profile segment = %q, want a research_<hash> form", foreign)+ }++ custom := hermesMemoryProfileSegment(filepath.Join(root, "custom-home"))+ if !strings.HasPrefix(custom, "h_") {+ t.Fatalf("custom home segment = %q, want an h_ hash", custom)+ }+ // Same basename in a different location must not collide.+ other := hermesMemoryProfileSegment(filepath.Join(root, "nested", "custom-home"))+ if custom == other {+ t.Fatalf("distinct custom homes collided on %q", custom)+ }+}++// TestHermesMemoryStorePathLayout pins the on-disk layout the documented+// one-off import depends on: <profile dir>/hermes-state/<agent>/<profile>.+func TestHermesMemoryStorePathLayout(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ agent := "11111111-2222-3333-4444-555555555555"+ got := HermesMemoryStorePath("", agent, filepath.Join(platformDefaultHermesHome(), "profiles", "research"))+ want := filepath.Join(home, ".multica", hermesMemoryStoreRoot, agent, "research")+ if got != want {+ t.Fatalf("store path = %q, want %q", got, want)+ }+}++// TestHermesMemoryStorePathDisabled covers the two ways memory stays+// task-local: no agent to key on, and the operator rollback switch.+func TestHermesMemoryStorePathDisabled(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ if got := HermesMemoryStorePath("", "", ""); got != "" {+ t.Fatalf("store path without an agent = %q, want empty", got)+ }++ t.Setenv(MulticaHermesTaskMemoryEnv, "1")+ if got := HermesMemoryStorePath("", "agent-1", ""); got != "" {+ t.Fatalf("store path with the rollback switch on = %q, want empty", got)+ }+}++// TestPrepareHermesHomeMemoryStorePersistsAcrossTasks is the regression test for+// #6638: an agent with skills bound must keep its memory between tasks. Each+// task gets a fresh overlay home, so the memory can only survive if memories/+// resolves to the shared per-agent store.+func TestPrepareHermesHomeMemoryStorePersistsAcrossTasks(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ store := filepath.Join(t.TempDir(), "hermes-state", "agent-1", "default")+ 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 {+ 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 {+ t.Fatalf("prepare second task: %v", err)+ }+ got, err := os.ReadFile(filepath.Join(secondTask, "memories", "MEMORY.md"))+ if err != nil {+ t.Fatalf("second task lost the agent's memory: %v", err)+ }+ if string(got) != "prefers tabs" {+ t.Fatalf("memory content = %q, want %q", got, "prefers tabs")+ }++ // The link must point at the store, not hold a copy — otherwise the next+ // task's writes would diverge from it.+ fi, err := os.Lstat(filepath.Join(secondTask, "memories"))+ if err != nil {+ t.Fatalf("lstat memories: %v", err)+ }+ if fi.Mode()&os.ModeSymlink == 0 {+ t.Fatalf("memories is not a link (mode %v)", fi.Mode())+ }+}++// TestPrepareHermesHomeMemoryStoreIsolatesAgents guards the isolation promise+// the store makes: one agent's memory must never be visible to another.+func TestPrepareHermesHomeMemoryStoreIsolatesAgents(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ stateRoot := 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(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 {+ t.Fatalf("prepare agent B: %v", err)+ }+ if _, err := os.Stat(filepath.Join(homeB, "memories", "MEMORY.md")); !os.IsNotExist(err) {+ t.Fatalf("agent B can see agent A's memory (err = %v)", err)+ }+}++// TestPrepareHermesHomeMemoryStoreRollback verifies the operator switch: with no+// store the overlay keeps a plain task-local memories dir, i.e. the old+// behaviour, and never leaves a dangling link behind.+func TestPrepareHermesHomeMemoryStoreRollback(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ t.Fatalf("prepare: %v", err)+ }+ fi, err := os.Lstat(filepath.Join(hermesHome, "memories"))+ if err != nil {+ t.Fatalf("lstat memories: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Fatalf("memories should be a real dir without a store, got a link")+ }+ if !fi.IsDir() {+ t.Fatalf("memories is not a directory (mode %v)", fi.Mode())+ }+}++// TestPrepareHermesHomeRollbackDetachesExistingStoreLink is the regression test+// for the rollback switch on a reused workdir. The overlay still carries the+// link to the persistent store from the previous run, and MkdirAll would follow+// it and silently succeed — leaving the task writing to a store the daemon no+// longer marks active, and the GC free to reclaim it mid-task.+func TestPrepareHermesHomeRollbackDetachesExistingStoreLink(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ store := filepath.Join(t.TempDir(), "hermes-state", "agent-1", "default")+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ // Run once with the store mounted, as a pre-rollback task would.+ 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")++ // Operator flips MULTICA_HERMES_TASK_MEMORY=1; the same overlay is reused.+ if err := prepareHermesHome(hermesHome, sharedHome, false, skills, nil, "", testLogger()); err != nil {+ t.Fatalf("prepare after rollback: %v", err)+ }++ fi, err := os.Lstat(filepath.Join(hermesHome, "memories"))+ if err != nil {+ t.Fatalf("lstat memories: %v", err)+ }+ if fi.Mode()&os.ModeSymlink != 0 {+ t.Fatalf("rollback left the store link in place; the task still writes to the persistent store")+ }+ if _, err := os.Stat(filepath.Join(hermesHome, "memories", "MEMORY.md")); !os.IsNotExist(err) {+ t.Fatalf("rollback should give the task an empty memories dir (err = %v)", err)+ }+ // The store itself must survive, so flipping the switch back restores memory.+ if _, err := os.Stat(filepath.Join(store, "MEMORY.md")); err != nil {+ t.Fatalf("rollback destroyed the persistent store: %v", err)+ }+}++// TestPrepareHermesHomeRollbackKeepsTaskLocalMemories checks the other reuse+// case: with no store, an existing real memories dir is this task's own memory+// and must be preserved across reuse.+func TestPrepareHermesHomeRollbackKeepsTaskLocalMemories(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ 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 {+ t.Fatalf("reuse prepare: %v", err)+ }+ if _, err := os.Stat(filepath.Join(hermesHome, "memories", "MEMORY.md")); err != nil {+ t.Fatalf("reuse dropped the task's own memory: %v", err)+ }+}++// TestMigrateHermesTaskMemoriesFailureKeepsSource is the regression test for+// migration data loss: when an entry cannot be carried over, the source must+// survive and the overlay must fail, because the caller deletes the source+// directory as soon as migration reports success.+func TestMigrateHermesTaskMemoriesFailureKeepsSource(t *testing.T) {+ t.Parallel()+ taskDir := t.TempDir()+ storeDir := t.TempDir()++ mustWrite(t, filepath.Join(taskDir, "MEMORY.md"), "first")+ mustWrite(t, filepath.Join(taskDir, "USER.md"), "second")+ // Make one entry uncopyable the way a cross-filesystem move fails: a+ // directory whose contents cannot be read.+ blocked := filepath.Join(taskDir, "blocked")+ if err := os.MkdirAll(blocked, 0o700); err != nil {+ t.Fatalf("create blocked dir: %v", err)+ }+ mustWrite(t, filepath.Join(blocked, "note.md"), "unreadable")+ if err := os.Chmod(blocked, 0o000); err != nil {+ t.Fatalf("chmod blocked dir: %v", err)+ }+ t.Cleanup(func() { _ = os.Chmod(blocked, 0o700) })++ err := migrateHermesTaskMemories(taskDir, storeDir, testLogger())+ if err == nil {+ t.Fatalf("migration reported success despite an unreadable entry; the caller would delete the source")+ }++ // Source intact.+ for _, name := range []string{"MEMORY.md", "USER.md"} {+ if _, statErr := os.Stat(filepath.Join(taskDir, name)); statErr != nil {+ t.Fatalf("source %s was lost on a failed migration: %v", name, statErr)+ }+ }+ // Store rolled back — a half-populated store would read as accumulated+ // memory on the next run and block the retry.+ left, readErr := os.ReadDir(storeDir)+ if readErr != nil {+ t.Fatalf("read store: %v", readErr)+ }+ if len(left) != 0 {+ t.Fatalf("failed migration left %d entries in the store, want 0", len(left))+ }+}++// TestMountHermesMemoriesUnreadableStoreKeepsSource covers the entry-point I/O+// error: an unreadable store must not read as "nothing to migrate", because the+// caller deletes the source directory the moment migration reports success.+func TestMountHermesMemoriesUnreadableStoreKeepsSource(t *testing.T) {+ t.Parallel()+ if os.Geteuid() == 0 {+ t.Skip("root ignores directory permissions")+ }+ hermesHome := t.TempDir()+ memories := filepath.Join(hermesHome, "memories")+ mustWrite(t, filepath.Join(memories, "MEMORY.md"), "irreplaceable")++ storeDir := filepath.Join(t.TempDir(), "store")+ if err := os.MkdirAll(storeDir, 0o700); err != nil {+ t.Fatalf("create store: %v", err)+ }+ if err := os.Chmod(storeDir, 0o000); err != nil {+ t.Fatalf("chmod store: %v", err)+ }+ t.Cleanup(func() { _ = os.Chmod(storeDir, 0o700) })++ if err := mountHermesMemories(hermesHome, storeDir, testLogger()); err == nil {+ t.Fatalf("mount reported success against an unreadable store; the source would be deleted")+ }+ if _, err := os.Stat(filepath.Join(memories, "MEMORY.md")); err != nil {+ t.Fatalf("source memory was lost after a failed mount: %v", err)+ }+}++// TestMigrateHermesTaskMemoriesRefusesUnsupportedEntries checks that an entry+// the migration will not copy fails closed instead of being skipped — a skip+// plus the caller's source deletion is a silent loss.+func TestMigrateHermesTaskMemoriesRefusesUnsupportedEntries(t *testing.T) {+ t.Parallel()+ taskDir := t.TempDir()+ storeDir := filepath.Join(t.TempDir(), "store")++ mustWrite(t, filepath.Join(taskDir, "MEMORY.md"), "regular")+ if err := os.Symlink(filepath.Join(taskDir, "MEMORY.md"), filepath.Join(taskDir, "LINK.md")); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }++ if err := migrateHermesTaskMemories(taskDir, storeDir, testLogger()); err == nil {+ t.Fatalf("migration skipped a symlink and reported success")+ }+ if _, err := os.Stat(filepath.Join(taskDir, "MEMORY.md")); err != nil {+ t.Fatalf("source was lost on a refused migration: %v", err)+ }+ if _, err := os.Stat(storeDir); !os.IsNotExist(err) {+ t.Fatalf("refused migration left a store behind (err = %v)", err)+ }+ // A nested symlink must be refused too — copyDirTree would have skipped it.+ nested := t.TempDir()+ mustWrite(t, filepath.Join(nested, "notes", "note.md"), "regular")+ if err := os.Symlink(filepath.Join(nested, "notes", "note.md"), filepath.Join(nested, "notes", "link.md")); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ if err := migrateHermesTaskMemories(nested, filepath.Join(t.TempDir(), "store"), testLogger()); err == nil {+ t.Fatalf("migration skipped a nested symlink and reported success")+ }+}++// TestMigrateHermesTaskMemoriesConcurrentFirstWriterWins covers two tasks of the+// same agent migrating at once, which is reachable in the window right after a+// daemon upgrade. Exactly one store must be published, and it must be one task's+// complete tree — never a mix of both.+func TestMigrateHermesTaskMemoriesConcurrentFirstWriterWins(t *testing.T) {+ t.Parallel()+ storeDir := filepath.Join(t.TempDir(), "agent", "default")++ const tasks = 4+ sources := make([]string, tasks)+ for i := range sources {+ sources[i] = t.TempDir()+ // Same filenames, distinct contents: a store that interleaves the two+ // would be detectable as a mixed marker set.+ mustWrite(t, filepath.Join(sources[i], "MEMORY.md"), fmt.Sprintf("task-%d", i))+ mustWrite(t, filepath.Join(sources[i], "USER.md"), fmt.Sprintf("task-%d", i))+ }++ var wg sync.WaitGroup+ errs := make([]error, tasks)+ start := make(chan struct{})+ for i := range sources {+ wg.Add(1)+ go func(i int) {+ defer wg.Done()+ <-start+ errs[i] = migrateHermesTaskMemories(sources[i], storeDir, testLogger())+ }(i)+ }+ close(start)+ wg.Wait()++ for i, err := range errs {+ if err != nil {+ t.Fatalf("concurrent migration %d failed: %v", i, err)+ }+ }++ memory, err := os.ReadFile(filepath.Join(storeDir, "MEMORY.md"))+ if err != nil {+ t.Fatalf("store is missing MEMORY.md after concurrent migration: %v", err)+ }+ user, err := os.ReadFile(filepath.Join(storeDir, "USER.md"))+ if err != nil {+ t.Fatalf("store is missing USER.md after concurrent migration: %v", err)+ }+ if string(memory) != string(user) {+ t.Fatalf("store interleaved two tasks: MEMORY.md=%q USER.md=%q", memory, user)+ }++ // Every source survives: a task that lost the race must not have had its+ // directory reported as migrated.+ for i, src := range sources {+ if _, err := os.Stat(filepath.Join(src, "MEMORY.md")); err != nil {+ t.Fatalf("source %d was consumed by the migration: %v", i, err)+ }+ }+ // No staging directories left behind next to the store.+ siblings, err := os.ReadDir(filepath.Dir(storeDir))+ if err != nil {+ t.Fatalf("read store parent: %v", err)+ }+ if len(siblings) != 1 {+ t.Fatalf("expected only the store next to itself, got %d entries", len(siblings))+ }+}++// TestPromoteHermesMemoryStagingClassifiesRemoveFailures covers the publish+// latch. Losing the race must be positively confirmed, never inferred from any+// os.Remove failure: the caller deletes the task's source directory on+// (false, nil), so a permission or I/O error there is a data-loss path.+func TestPromoteHermesMemoryStagingClassifiesRemoveFailures(t *testing.T) {+ t.Parallel()++ // A genuinely non-empty store means another task published first.+ t.Run("populated store loses the race", func(t *testing.T) {+ t.Parallel()+ parent := t.TempDir()+ storeDir := filepath.Join(parent, "default")+ mustWrite(t, filepath.Join(storeDir, "MEMORY.md"), "winner")+ staging := filepath.Join(parent, ".default.migrating-x")+ mustWrite(t, filepath.Join(staging, "MEMORY.md"), "loser")++ promoted, err := promoteHermesMemoryStaging(staging, storeDir)+ if err != nil {+ t.Fatalf("a populated store should be a lost race, not an error: %v", err)+ }+ if promoted {+ t.Fatalf("promote clobbered a store another task had published")+ }+ got, readErr := os.ReadFile(filepath.Join(storeDir, "MEMORY.md"))+ if readErr != nil || string(got) != "winner" {+ t.Fatalf("winner's store was modified: content=%q err=%v", got, readErr)+ }+ })++ // An empty store that cannot be removed is an I/O failure, not a race.+ t.Run("unremovable empty store fails closed", func(t *testing.T) {+ if os.Geteuid() == 0 {+ t.Skip("root ignores directory permissions")+ }+ parent := t.TempDir()+ storeDir := filepath.Join(parent, "default")+ if err := os.MkdirAll(storeDir, 0o700); err != nil {+ t.Fatalf("create store: %v", err)+ }+ staging := filepath.Join(parent, ".default.migrating-x")+ mustWrite(t, filepath.Join(staging, "MEMORY.md"), "irreplaceable")++ // Removing a directory needs write permission on its parent.+ if err := os.Chmod(parent, 0o500); err != nil {+ t.Fatalf("chmod parent: %v", err)+ }+ t.Cleanup(func() { _ = os.Chmod(parent, 0o700) })++ promoted, err := promoteHermesMemoryStaging(staging, storeDir)+ if promoted {+ t.Fatalf("promote reported success against an unremovable store")+ }+ if err == nil {+ t.Fatalf("a permission error was reported as a lost race; the caller would delete the source")+ }+ })+}++// TestMigrateHermesTaskMemoriesCopiesRatherThanMoves pins the cross-filesystem+// property: migration must not depend on rename, and must carry nested dirs.+func TestMigrateHermesTaskMemoriesCopiesRatherThanMoves(t *testing.T) {+ t.Parallel()+ taskDir := t.TempDir()+ storeDir := t.TempDir()++ mustWrite(t, filepath.Join(taskDir, "MEMORY.md"), "top level")+ mustWrite(t, filepath.Join(taskDir, "notes", "deep", "note.md"), "nested")++ if err := migrateHermesTaskMemories(taskDir, storeDir, testLogger()); err != nil {+ t.Fatalf("migrate: %v", err)+ }+ for _, rel := range []string{"MEMORY.md", filepath.Join("notes", "deep", "note.md")} {+ if _, err := os.Stat(filepath.Join(storeDir, rel)); err != nil {+ t.Fatalf("store is missing %s: %v", rel, err)+ }+ // Copy, not move: the source stays until the caller removes the dir.+ if _, err := os.Stat(filepath.Join(taskDir, rel)); err != nil {+ t.Fatalf("migration moved %s instead of copying it: %v", rel, err)+ }+ }+}++// TestPrepareHermesHomeMigratesTaskLocalMemories covers the upgrade path: a+// workdir reused from a pre-store daemon still holds a real memories/ dir, whose+// contents must move into the (empty) store rather than be dropped.+func TestPrepareHermesHomeMigratesTaskLocalMemories(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ 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 {+ 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 {+ t.Fatalf("prepare with store: %v", err)+ }+ got, err := os.ReadFile(filepath.Join(store, "MEMORY.md"))+ if err != nil {+ t.Fatalf("task-local memory was not migrated into the store: %v", err)+ }+ if string(got) != "carried over" {+ t.Fatalf("migrated content = %q, want %q", got, "carried over")+ }+}++// TestPrepareHermesHomeMigrationKeepsExistingStore is the other half of the+// upgrade path: an agent that already accumulated memory must never have it+// overwritten by a stale task-local dir.+func TestPrepareHermesHomeMigrationKeepsExistingStore(t *testing.T) {+ t.Parallel()+ sharedHome := t.TempDir()+ hermesHome := filepath.Join(t.TempDir(), "hermes-home")+ skills := []SkillContextForEnv{{Name: "deploy", Content: "# Deploy"}}++ 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")++ 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 {+ t.Fatalf("prepare with store: %v", err)+ }+ got, err := os.ReadFile(filepath.Join(store, "MEMORY.md"))+ if err != nil {+ t.Fatalf("read store memory: %v", err)+ }+ if string(got) != "authoritative agent memory" {+ t.Fatalf("store memory was overwritten by the task-local copy: %q", got)+ }+}++// TestPruneHermesMemoryStores covers the GC contract: stores idle past retention+// are reclaimed, recently-used ones are kept, and a store a live task holds is+// never removed.+func TestPruneHermesMemoryStores(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ root := filepath.Join(home, ".multica", hermesMemoryStoreRoot)+ idle := filepath.Join(root, "agent-idle", "default")+ fresh := filepath.Join(root, "agent-fresh", "default")+ held := filepath.Join(root, "agent-held", "default")+ for _, dir := range []string{idle, fresh, held} {+ mustWrite(t, filepath.Join(dir, "MEMORY.md"), "remembered")+ }++ now := time.Now()+ old := now.Add(-30 * 24 * time.Hour)+ for _, dir := range []string{idle, held} {+ if err := os.Chtimes(filepath.Join(dir, "MEMORY.md"), 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 := PruneHermesMemoryStores("", 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 store survived the prune (err = %v)", err)+ }+ if _, err := os.Stat(fresh); err != nil {+ t.Fatalf("recently used store was reclaimed: %v", err)+ }+ if _, err := os.Stat(held); err != nil {+ t.Fatalf("store held by a live task was reclaimed: %v", err)+ }+}++// TestPruneHermesMemoryStoresDisabled documents that retention <= 0 turns the+// pruner off entirely, matching the Codex store knob.+func TestPruneHermesMemoryStoresDisabled(t *testing.T) {+ home := t.TempDir()+ t.Setenv("HOME", home)+ t.Setenv("USERPROFILE", home)++ store := filepath.Join(home, ".multica", hermesMemoryStoreRoot, "agent-1", "default")+ mustWrite(t, filepath.Join(store, "MEMORY.md"), "remembered")+ 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, _ := PruneHermesMemoryStores("", 0, time.Now(), nil, testLogger()); removed != 0 {+ t.Fatalf("removed = %d with pruning disabled, want 0", removed)+ }+ if _, err := os.Stat(store); err != nil {+ t.Fatalf("store was reclaimed with pruning disabled: %v", err)+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 80433851f7..df8689f6c8 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -57,15 +57,19 @@ func (d *Daemon) gcLoop(ctx context.Context) {// gcStats accumulates byte counts and per-pattern hit counts for one GC cycle.type gcStats struct {- cleaned int // whole task dirs removed (issue done/cancelled)- orphaned int // whole task dirs removed (no meta / unreachable issue)- skipped int // task dirs left untouched- artifactDirs int // task dirs that had at least one artifact reclaimed- artifactRemoved int // count of removed artifact subdirs- storesReclaimed int // per-issue Codex 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+ cleaned int // whole task dirs removed (issue done/cancelled)+ orphaned int // whole task dirs removed (no meta / unreachable issue)+ skipped int // task dirs left untouched+ artifactDirs int // task dirs that had at least one artifact reclaimed+ artifactRemoved int // count of removed artifact subdirs+ storesReclaimed int // per-conversation Codex session stores reclaimed past their TTL+ // 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}// runGC performs a single GC scan across all workspace directories.@@ -104,12 +108,21 @@ func (d *Daemon) runGC(ctx context.Context) {// Reclaim per-issue Codex session stores idle past their TTL. These live// under the shared ~/.codex home (outside WorkspacesRoot) so resume survives// the task GC, which means they need their own bounded lifecycle (MUL-4424).- if storesRemoved, storeBytes := execenv.PruneCodexSessionStores(d.cfg.Profile, d.cfg.GCCodexSessionTTL, time.Now(), d.reserveCodexStoreForDeletion, d.logger); storesRemoved > 0 {+ if storesRemoved, storeBytes := execenv.PruneCodexSessionStores(d.cfg.Profile, d.cfg.GCCodexSessionTTL, time.Now(), d.reserveStoreForDeletion, d.logger); storesRemoved > 0 {stats.storesReclaimed += storesRemovedstats.bytesReclaimed += storeBytes}- if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.repoCachesReclaimed > 0 {+ // Same for per-agent Hermes memory stores: they outlive the task by design+ // (that is what fixes #6638), so a deleted agent's memory needs its own+ // bounded lifecycle. Retention is much longer than the Codex one — these are+ // a few markdown files, and reclaiming them is user-visible amnesia.+ if storesRemoved, storeBytes := execenv.PruneHermesMemoryStores(d.cfg.Profile, d.cfg.GCHermesMemoryTTL, time.Now(), d.reserveStoreForDeletion, d.logger); storesRemoved > 0 {+ stats.hermesMemoryStoresReclaimed += storesRemoved+ stats.bytesReclaimed += storeBytes+ }++ if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 {d.logger.Info("gc: cycle complete","cleaned", stats.cleaned,"orphaned", stats.orphaned,@@ -117,6 +130,7 @@ func (d *Daemon) runGC(ctx context.Context) {"artifact_dirs", stats.artifactDirs,"artifact_removed", stats.artifactRemoved,"codex_session_stores_reclaimed", stats.storesReclaimed,+ "hermes_memory_stores_reclaimed", stats.hermesMemoryStoresReclaimed,"repo_caches_reclaimed", stats.repoCachesReclaimed,"bytes_reclaimed", stats.bytesReclaimed,"by_pattern", stats.byPattern,