#!/bin/bash
# Harness wrapper for Hermes Agent (Nous Research), in both isolation modes.
#
# Every wolt gets its own Hermes home, <wolt>/.hermes (HERMES_HOME), natively
# too. Hermes keeps a persona file, its own memory, sessions and settings in
# that home, so a shared ~/.hermes would hand every wolt the same "You are
# Hermes Agent" persona and one memory across wolts. Provider credentials are
# NOT copied in: sessions get provider keys (OPENROUTER_API_KEY, ...) from the
# lodge environment, the same way opencode and Pi do.
#
# Benched against hermes-agent 0.19.0.

WOLTSPACE_HOME_DIR="${WOLTSPACE_WOLT_HOME:-$(echo "$PWD" | sed -n 's|\(/workspace/wolts/[^/]*\).*|\1|p')}"
if [ -n "$WOLTSPACE_HOME_DIR" ] && [ -d "$WOLTSPACE_HOME_DIR" ]; then
    if [ "${WOLTSPACE_ISOLATION:-external}" != "host" ]; then
        # Container mode: the whole HOME is per wolt, like every other harness.
        export HOME="$WOLTSPACE_HOME_DIR"
    fi
    export HERMES_HOME="$WOLTSPACE_HOME_DIR/.hermes"
    mkdir -p "$HERMES_HOME"

    # The lodge owns this file and rewrites it every start, so the skills path
    # follows the wolt if its folder moves. (For now: per-wolt overrides merged
    # on top would be the next step.) Settings:
    #   skills.external_dirs   - the wolt's synced skills (woltspace + its own)
    #   memory.*               - off: a wolt's memory lives in wolt/memory/
    #   display.busy_input_mode - queue: a message that arrives while Hermes is
    #                             working waits for the turn to end instead of
    #                             interrupting it (Hermes' default)
    # YAML single quotes: only a ' needs escaping (doubled), so any path is safe.
    SKILLS_DIR="$WOLTSPACE_HOME_DIR/.claude/skills"
    Q="'"
    SKILLS_YAML="$Q${SKILLS_DIR//$Q/$Q$Q}$Q"
    # rm first: never write through a link planted at either path.
    rm -f "$HERMES_HOME/config.yaml"
    cat > "$HERMES_HOME/config.yaml" <<EOF
# Written by woltspace (whermes) on every session start. Edits are replaced.
skills:
  external_dirs: [$SKILLS_YAML]
memory:
  memory_enabled: false
  user_profile_enabled: false
display:
  busy_input_mode: queue
EOF

    # Hermes seeds a default SOUL.md ("You are Hermes Agent ...") as the
    # primary identity when the file is missing. Write the wolt's own first;
    # Hermes never overwrites a SOUL.md it did not write.
    if [ -L "$HERMES_HOME/SOUL.md" ]; then
        rm -f "$HERMES_HOME/SOUL.md"
    fi
    if [ ! -e "$HERMES_HOME/SOUL.md" ]; then
        cat > "$HERMES_HOME/SOUL.md" <<'EOF'
You are a wolt living in a Woltspace lodge. Your name, identity and rules are in
the project files of your working directory (CLAUDE.md / AGENTS.md) and your
memory is in wolt/memory/. Follow them; they come before any default persona.
EOF
    fi
fi

exec hermes "$@"
