Consolidate Hermes fleet checks and verified TTS repair

This commit is contained in:
Mikei386 committed 2026-10-26 21:12:16 +01:00
commit 879d8681a3
6 files changed
+3022

No files matched your search

+18
View File
@@ -39,3 +39,21 @@ Aktueller Betrieb: [Systemübersicht](docs/CURRENT_SYSTEM.md).
Der heutige `install.sh` ist weiterhin ein Docker-Testinstaller und erfüllt
noch keine native Komplettinstallation. Diese Regel ist kein Auftrag, die
laufende Installation ohne neues Wartungsfenster umzuschalten.
## Hermes: profilübergreifende Abnahme
Bei Hermes-Profil-, Integrations- oder Updatearbeiten zuerst den
[dokumentierten Gesamtstand](docs/maintenance/hermes-fleet-audit-2026-10-26/README.md)
und die dort festgehaltenen Rollenunterschiede prüfen. Gemeinsame Anbieter und
Sprachanschlüsse gehören in den persistenten Managed Scope; Werkzeuge, MCP-
Freigaben, Arbeitsordner und Benachrichtigungsabsicht bleiben rollenbezogen.
Nicht vom Vorhandensein einer Einstellung auf funktionierende Ausführung schließen.
Nach Änderungen alle betroffenen Profile mit dem vorhandenen lesenden Audit prüfen;
neue Profile brauchen vor der Abnahme eine ausdrücklich festgehaltene Rolle.
Konfigurations-/Resolverprüfung, Funktionstest, native Clientprüfung und echte
Neustart-/Restore-Abnahme getrennt berichten. Keine ungefragten Dienste, Test-
Benachrichtigungen, Modelltests oder Neustarts und keine Mac-App-Patches.
NAS/Hermes-Operatorzugang: vorhandener SSH-Schlüssel `~/.ssh/ha_agent` für
`root@192.168.1.2`; Athena-Hostzugang verwendet den separaten `~/.ssh/athena_key`.
Geheimnisse niemals ausgeben oder in Git übernehmen. Das dauerhafte VPN-Verbot
bleibt uneingeschränkt verbindlich.
@@ -0,0 +1,208 @@
# Hermes fleet acceptance — 26 October 2026
Michael requested a whole-system comparison and correction, covering every
profile rather than repairing only the profile that happened to log a warning.
The current system is the NAS `Hermes-Agent-Desktop` gateway and its connected
unmodified Mac clients. This action installed no service or dependency and
restarted no host, model, container, gateway, browser, or active agent session.
## Shared infrastructure and intentional differences
| Profiles | Work environment | Intended enabled MCP scope | HA lifecycle hooks |
|---|---|---|---|
| Athena / `default` | Own local workspace/home/screen/browser | Existing general-assistant selection | Three approved hooks |
| B’Elanna / `belanna-storres` | Own local workspace/home/screen/browser | HomeServer, syncthing | None configured |
| HORIZON Dev | Own local HORIZON checkout/home/screen/browser | None | None configured |
| Jean-Luc Picode | Own local coding workspace/home/screen/browser | Gitea, REA | None configured |
| Prüfungs VDI Dev | Own local VDI checkout/home/screen/browser | None | None configured |
| Seven of Heim | Own local workspace/home/screen/browser | HA: 31 explicitly included tools; HomeServer: 6 | None configured |
| Solid Crafter | Own local workspace/home/screen/browser | solidcraft | None configured |
| William T. Timer | Own local workspace/home/screen/browser | HomeAssistant, HomeServer | Three approved hooks |
| HORIZON server bot | Existing SSH target | None | None configured |
| INFvHost 1 server bot | Existing SSH target | None | None configured |
| INFvHost 2 server bot | Existing SSH target | None | None configured |
| Prüfungs VDI server bot | Existing SSH target | None | None configured |
| GG3653-01 server bot | Existing SSH target | None | None configured |
Shared configuration is `/opt/data/managed` (persistent host path:
`/mnt/nvme-storage/appdata/Hermes-Agent-Desktop/managed`). It now owns:
- The existing Athena and KIT-LiteLLM named model providers and their protected
managed dotenv credentials. No bot's selected default model was changed.
- STT provider/route/model: OpenAI-compatible Athena,
`parakeet-redux-cpu`, German, existing timeout/retry/streaming settings.
- TTS provider/route/model: OpenAI-compatible Athena,
`qwen-06b-q4-anna-cpu`, voice `default` (Anna), existing streaming selection.
- `voice.client_direct: false`, keeping the existing NAS audio-relay design
consistent for remote clients. LAN-only provider access is not shifted to Macs.
The managed speech credential is an environment reference to the existing
Athena variable, resolved by the official profile secret/config pipeline; no
new key or additional plaintext secret store was created.
Per-profile default models, tools, MCP permissions, SSH targets, workspaces,
personality, memories, scheduled jobs, notification choices and voice preferences
remain per-profile. In particular `voice.auto_tts` was not globally enabled.
The two Dev bots now have the shared app speech backend without receiving the
model's `tts` tool or any additional coding/MCP/production-server authority.
Seven still excludes `ha_auth` and the writing Unraid shell.
OpenAI Codex authentication is centrally inherited through the existing root
credential pool. No OAuth token was copied, moved, renewed or disclosed.
## Gaps found and corrected across all affected profiles
1. **Repeated speech connection configuration.** Eleven profiles carried copies
of the same endpoint, models and credentials; two Dev profiles had no explicit
speech route. The existing backend settings now live once in managed scope.
The local STT/TTS sections and redundant `voice.client_direct` values were
removed from all profiles. Other voice preferences were preserved.
2. **Noncanonical platform pins in both Dev profiles.** Their keys were named
`hermes-cli`, `hermes-desktop` and `hermes-api-server`. Those are toolset names,
not the canonical platform keys. Existing disabled-toolset lists already
prevented broader access, but exact selection depended on default expansion.
Both profiles now explicitly pin the intended eleven coding toolsets using
`platform_toolsets.cli` (also consumed by Desktop/TUI) and `.api_server`.
Existing disabled-toolset lists and empty MCP lists remain intact.
3. **Loose configuration-file permissions.** All thirteen `config.yaml` files
are now `0600`, owned by the existing `99:100`. Eight previously had broader
modes (`0640`, `0644`, or `0666`). Existing `.env`/auth/consent files already
checked as `0600`. Existing-mode preservation in Hermes' atomic writer was
inspected; no global umask or file-writer source patch was introduced.
4. **Three copies of the same Pulse packaging gap.** The enabled custom
`athena-pulse` packages in default, Picode and William had a dashboard API
module but no root `__init__.py`, which Hermes' Python plugin loader requires.
All three now include the standard `register(ctx)` entry point. It deliberately
registers no model tools, hooks or workers: the existing HTTP API is mounted
separately by Hermes' dashboard-extension loader. Existing plugin sources,
permissions, routes and Mac files were otherwise untouched. This is not a
claim that the native status-bar feature has passed a fresh end-to-end test.
5. **Recovery-cache ownership in every profile.** An additional test as the
data owner (UID 99) exposed root-owned `backups/config` metadata and private
recovery files. Such copies can be created by operator checks that call
Hermes' config loader as root. The live Hermes processes run as UID 99.
[`repair-cache-ownership.py`](repair-cache-ownership.py) corrected 75 owner/mode
entries across all thirteen profiles without reading, copying or deleting
file contents. Cache directories are `0700`, recovery files `0600`, owned
by the corresponding profile-data owner. The audit now drops root privileges
to that owner before loading configuration and checks cache ownership/access.
William's three specific notification consents were already corrected in the
[preceding maintenance action](../hermes-hooks-kit-litellm-2026-10-26.md). The
fleet check now verifies **every configured hook** against its profile's actual
allowlist. It does not turn missing hooks into newly authorized notifications.
## Independent acceptance
[`acceptance.json`](acceptance.json) contains 280 passed checks, zero failures,
across all thirteen profiles: eight local and five SSH. These are configuration
and runtime-resolution assertions, not 280 end-to-end feature tests.
The check uses installed Hermes code, including the manufacturer validator,
named-provider resolver, STT/TTS credential resolvers, root credential-pool
fallback, terminal-home resolver, initialized GUI toolset namespace, CLI/API
toolset resolver and per-profile hook-consent reader. No model-generated
command was executed.
Additional probes passed:
- All three repaired Pulse packages loaded enabled and error-free through the
actual Hermes plugin manager, with zero tools and zero hooks registered.
- A fresh isolated process removed the inherited Athena key, loaded the official
dotenv/bootstrap sequence using the persistent `HERMES_MANAGED_DIR`, and
correctly resolved both speech credentials from managed scope.
- The **running**, authenticated gateway returned `ok:true`, relay STT/TTS and
streaming STT for `GET /api/audio/voice-config?profile=horizon-dev`; no restart
was needed for it to see the common configuration.
- All eight local CWDs, terminal homes, browser roots and preferred-browser
mappings were independently checked. The five SSH destinations were unchanged.
- Existing per-role MCP selections remain distinct; Seven's 31/6 positive lists
and the two project Dev bots' exact CLI/API coding selections passed.
The initial repair verification compared raw MCP secret references with expanded
values and correctly aborted, restoring every changed file and deleting its own
new files. The comparison was corrected to compare persisted values with
persisted values. Rollback was independently confirmed before the successful
retry. Original private configuration bytes were held in memory only; no separate
operator rollback copies were written. Hermes' official config reader can refresh
its normal bounded last-known-good recovery cache; this is distinct from an
operator backup.
The plugin loader's messages refusing profile-local ownership of dashboard basic
authentication are expected isolation guards in this diagnostic process. They
are different from the former missing-Pulse-entry-point failure. Authentication
was not globally disabled, replaced or reconfigured to hide those messages.
## Repeatable operating procedure
The configuration acceptance [`audit.py`](audit.py) is also installed at
`/opt/data/maintenance/fleet-audit-20261026/audit.py`. It needs the existing
Hermes Python/modules, not additional packages. From an operator terminal:
```sh
docker exec -e PYTHONPATH=/opt/hermes -e PYTHONDONTWRITEBYTECODE=1 \
Hermes-Agent-Desktop /opt/hermes/.venv/bin/python \
/opt/data/maintenance/fleet-audit-20261026/audit.py --runtime
```
For native Hermes, run the same script with that installation's Python and
module path; use the configured Hermes data root rather than assuming `/opt/data`.
This edition intentionally targets the audited NAS data root. It is not a new
native Athena dependency or installer. The audit outputs only names, counts and
pass/fail and does not mutate bot settings. The upstream loader may maintain its
bounded recovery cache; this is not a strictly read-only filesystem operation.
When invoked as root the audit drops to the data owner before those reads.
`--runtime` loads existing configuration/plugin registries in its own
process; it does not start a gateway or execute tools. Gateway import logging may
appear on stderr; JSON is on stdout. No background monitor or scheduled job was
created.
For **every new bot**:
1. Record its intended role and exceptions; update the audit's explicit roster
and expectations. An unclassified extra profile fails acceptance.
2. Inherit shared model/speech providers; do not copy credentials or whole default
profiles. Select role-specific tools, MCPs, skills and notification intent.
3. Give a local bot its own CWD/home/screen/browser. Configure its preferred
browser with the existing documented installer. SSH bots retain explicit
remote execution and do not inherit a local desktop accidentally.
4. Approve only the configured, reviewed hooks for that profile. No blanket
`hooks_auto_accept` to make a warning disappear.
5. Run this audit and a scoped functional test appropriate to the role. Mark
acoustic, native UI, remote-service and restart/restore checks separately.
For updates, record the installed artifact/version, audit before/after, preserve
per-role settings and wait for active work before any authorized restart. A
changed source/image or copied plugin package requires revalidation. The
one-time [`repair.py`](repair.py) is guarded and refuses a changed starting
policy; it is not an automatic updater or a command to rerun on this repaired
installation.
## Limits and remaining operational risks
- No actual reboot, gateway restart, container recreation or full protected
backup/restore was performed. The fresh-process bootstrap check is narrower.
- No inference, audio generation, notification delivery, external SSH login,
MCP tool execution, device switching or production-service restart was tested.
- No native Mac-app patch was made. The previously documented blank native Git
diff area is not declared fixed by configuration acceptance.
- The current inspected artifact is `nousresearch/hermes-agent:latest-desktop`,
image ID `sha256:82d34f3d57e7ba2d3b3f3f857562816d8758aa69a261489edf5446d59860637c`.
It has `unless-stopped`, a 4-GiB/2-CPU limit and restart counter 0. `latest`
remains a mutable tag; an external image update is not covered by this audit.
- Automatic approval review rejected reading the global Unraid Docker-update
settings because the shared file can include forbidden VPN-container data.
That inspection was not performed or retried through another access path.
Its per-container automatic-update policy therefore remains unverified.
- Private VPN files and containers were not inspected, modified, restarted,
copied, hashed or included in any report. No broader host/network maintenance
was performed under the label of this Hermes audit.
Official references:
[profiles](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/profiles.md),
[managed scope](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/managed-scope.md),
[Bot Screen](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/bot-screen.md),
[voice](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/voice-mode.md),
[MCP filtering](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/mcp.md),
[toolset resolver](https://github.com/NousResearch/hermes-agent/blob/main/hermes_cli/tools_config.py),
[plugin loader](https://github.com/NousResearch/hermes-agent/blob/main/hermes_cli/plugins_loader.py).
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,194 @@
#!/usr/bin/env python3
"""Hermes fleet configuration acceptance; no bot settings are changed.
Outputs names, counts and pass/fail only: no prompts, chat text, keys or auth tokens.
The upstream reader may maintain its bounded known-good recovery cache.
--runtime additionally loads the existing plugin/config registries in this process;
it starts no server, agent turn, notification, browser, SSH workspace or MCP tool.
"""
import argparse
import json
import os
from pathlib import Path
import stat
import hermes_yaml as yaml
from agent.secret_scope import build_profile_secret_scope, set_secret_scope, reset_secret_scope
from hermes_constants import set_hermes_home_override, reset_hermes_home_override, get_subprocess_home
from hermes_cli.config import load_config, validate_config_structure
from hermes_cli.config_effective import load_user_config_effective
from hermes_cli.config_providers import get_compatible_custom_providers
from hermes_cli.runtime_provider import resolve_runtime_provider
from hermes_cli.auth import read_credential_pool
from agent.shell_hooks import allowlisted_pairs
ROOT = Path('/opt/data')
ATHENA = 'http://192.168.1.212:8120/v1'
LITELLM = 'https://litellm.scc.kit.edu/v1'
KEY = 'HERMES_CUSTOM_192_168_1_212_8120_API_KEY'
CODE = {'terminal', 'file', 'web', 'browser', 'vision', 'skills', 'todo', 'memory',
'session_search', 'clarify', 'code_execution'}
ROLES = {
'default': ('general', None),
'belanna-storres': ('nas', {'HomeServer', 'syncthing'}),
'horizon-dev': ('coding', set()),
'jean-luc-picode': ('coding', {'gitea', 'rea'}),
'pruefungs-vdi-dev': ('coding', set()),
'seven-of-heim': ('smart-home', {'HomeAssistant', 'HomeServer'}),
'solid-crafter': ('cad', {'solidcraft'}),
'william-t-time': ('scheduled', {'HomeAssistant', 'HomeServer'}),
'ssh-horizon-ecc7d706': ('ssh-server', set()),
'ssh-infvhost-1-5b1589d3': ('ssh-server', set()),
'ssh-infvhost-2-731791df': ('ssh-server', set()),
'ssh-pool-vdi-ff978f02': ('ssh-server', set()),
'ssh-scc-gg3653-01-76dcf38d': ('ssh-server', set()),
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--runtime', action='store_true')
args = parser.parse_args()
# Upstream's config reader refreshes its bounded last-known-good cache.
# Run as the data owner so an operator's root invocation cannot create
# root-owned recovery copies the service user later cannot read.
owner = (ROOT / 'config.yaml').stat()
if os.geteuid() == 0 and owner.st_uid != 0:
os.setgroups([])
os.setgid(owner.st_gid)
os.setuid(owner.st_uid)
if args.runtime:
from tui_gateway import server
from hermes_cli.tools_config import _get_platform_tools
checks, profiles, cwd_seen, browser_seen = [], [], {}, {}
def check(name, ok, profile=None):
checks.append(dict(check=name, passed=bool(ok), **({'profile': profile} if profile else {})))
managed = ROOT / 'managed'
shared = yaml.safe_load((managed / 'config.yaml').read_text()) or {}
check('shared_config_keys', set(shared) == {'providers', 'stt', 'tts', 'voice'})
check('shared_provider_names', set(shared.get('providers') or {}) == {'athena', 'litellm'})
check('managed_credentials_private', stat.S_IMODE((managed / '.env').stat().st_mode) == 0o600)
check('managed_startup_env', (ROOT / 'container.env').read_text().splitlines().count(
'HERMES_MANAGED_DIR=/opt/data/managed') == 1)
for name in ('config.yaml', '.env'):
check('running_bootstrap_' + name, (Path('/etc/hermes') / name).resolve() == managed / name)
homes = [ROOT] + sorted(p for p in (ROOT / 'profiles').iterdir() if (p / 'config.yaml').is_file())
ids = {'default' if h == ROOT else h.name for h in homes}
check('classified_roster', ids == set(ROLES))
for home in homes:
name = 'default' if home == ROOT else home.name
role, expected_mcp = ROLES.get(name, ('unclassified', None))
raw = yaml.safe_load((home / 'config.yaml').read_text()) or {}
scope = build_profile_secret_scope(home)
ht = set_hermes_home_override(home)
st = set_secret_scope(scope, profile_home=str(home))
try:
cfg = load_config()
check('manufacturer_config_validator', not validate_config_structure(cfg), name)
for file in ('config.yaml', '.env', 'auth.json', 'shell-hooks-allowlist.json'):
path = home / file
if path.is_file():
check('private_mode_' + file, stat.S_IMODE(path.stat().st_mode) == 0o600, name)
cache = home / 'backups/config'
if cache.is_dir():
copies = [p for p in cache.glob('config.yaml.*') if p.is_file() and not p.is_symlink()]
check('recovery_cache_owner_and_access', cache.stat().st_uid == owner.st_uid
and all(p.stat().st_uid == owner.st_uid and os.access(p, os.R_OK) for p in copies), name)
check('profile_identity', (home / 'SOUL.md').is_file() and (home / 'workspace').is_dir(), name)
check('central_speech_not_copied', 'stt' not in raw and 'tts' not in raw, name)
check('central_provider_not_copied', not any(r.get('name', '').lower() in ('athena', 'kit-litellm')
for r in get_compatible_custom_providers(raw)), name)
for provider, url, key, model in (
('athena', ATHENA, KEY, (cfg.get('model') or {}).get('default')),
('litellm', LITELLM, 'LITELLM_API_KEY', 'alias.medium-local'),
):
route = resolve_runtime_provider(requested='custom:' + provider, target_model=model)
check(provider + '_runtime_route', route.get('base_url') == url
and bool(scope.get(key)) and route.get('api_key') == scope.get(key), name)
check('openai_global_login_available', bool(read_credential_pool('openai-codex')), name)
from tools.transcription_cloud import _resolve_openai_audio_client_config as stt_route
from tools.tts_tool_openai import _resolve_openai_audio_client_config as tts_route
sk, su = stt_route()
tk, tu, managed_tts = tts_route()
check('stt_runtime_route', su == ATHENA and sk == scope.get(KEY)
and cfg['stt']['openai']['model'] == 'parakeet-redux-cpu', name)
check('tts_runtime_route', tu == ATHENA and tk == scope.get(KEY) and not managed_tts
and cfg['tts']['openai']['model'] == 'qwen-06b-q4-anna-cpu', name)
check('remote_audio_relay', cfg['voice'].get('client_direct') is False, name)
mcp = cfg.get('mcp_servers') or {}
enabled_mcp = {k for k, v in mcp.items() if isinstance(v, dict) and v.get('enabled', True)}
if expected_mcp is not None:
check('role_mcp_scope', enabled_mcp == expected_mcp, name)
if role == 'smart-home':
ha = mcp['HomeAssistant']['tools']['include']
mua = mcp['HomeServer']['tools']['include']
check('smart_home_positive_lists', len(ha) == 31 and len(mua) == 6
and 'ha_auth' not in ha and 'unraid_system_shell' not in mua, name)
terminal = cfg.get('terminal') or {}
backend = terminal.get('backend', 'local')
if role == 'ssh-server':
check('ssh_backend_preserved', backend == 'ssh' and bool(terminal.get('ssh_host')), name)
else:
cwd = terminal.get('cwd')
check('local_workspace', backend == 'local' and cwd and Path(cwd).is_dir()
and Path(cwd).is_relative_to(home) and cwd not in cwd_seen, name)
cwd_seen[cwd] = name
local_home = get_subprocess_home({'HERMES_HOME': str(home), 'HOME': '/opt/data/home',
'TERMINAL_HOME_MODE': terminal.get('home_mode', 'auto')})
check('isolated_terminal_home', local_home == str(home / 'home'), name)
browser = str((home / 'bot-desktop/browser-profile').resolve())
check('isolated_browser_path', browser not in browser_seen, name)
browser_seen[browser] = name
check('headed_screen_policy', cfg.get('browser', {}).get('headed') is True
and cfg.get('bot_desktop', {}).get('auto_start') is True, name)
rc = home / 'bot-desktop/xdg/xfce4/helpers.rc'
check('browser_launcher_mapping', rc.is_file()
and 'WebBrowser=hermes-screen-browser' in rc.read_text().splitlines(), name)
hooks = cfg.get('hooks') or {}
pairs = {(event, item.get('command')) for event, items in hooks.items()
if isinstance(items, list) for item in items if isinstance(item, dict)}
check('all_configured_hooks_approved', pairs <= allowlisted_pairs(), name)
check('notification_scope_intent', bool(pairs) == (name in ('default', 'william-t-time')), name)
for plugin in (cfg.get('plugins') or {}).get('enabled', []):
if plugin == 'athena-pulse':
check('pulse_directory_entrypoint', (home / 'plugins/athena-pulse/__init__.py').is_file(), name)
record = dict(profile=name, role=role, backend=backend,
enabled_mcp=sorted(enabled_mcp), approved_hook_count=len(pairs),
auto_tts=cfg.get('voice', {}).get('auto_tts'),
memory_files={n: (home / 'memories' / n).is_file() for n in ('MEMORY.md', 'USER.md')})
if args.runtime:
gui = set(server._load_enabled_toolsets('desktop') or [])
cli = set(_get_platform_tools(cfg, 'cli'))
api = set(_get_platform_tools(cfg, 'api_server'))
record.update(gui_toolsets=sorted(gui), cli_toolsets=sorted(cli), api_toolsets=sorted(api))
if name in ('horizon-dev', 'pruefungs-vdi-dev'):
check('coding_canonical_platform_keys', set(cfg['platform_toolsets']) == {'cli', 'api_server'}, name)
check('coding_exact_cli_api_toolsets', cli == CODE and api == CODE, name)
check('coding_gui_toolsets', gui <= CODE | {'catalog', 'project', 'desktop_ui'} and CODE <= gui, name)
if name == 'jean-luc-picode':
check('picode_tool_scope', cli == CODE | {'gitea', 'rea'}, name)
if name == 'seven-of-heim':
check('seven_tool_scope', cli == CODE | {'HomeAssistant', 'HomeServer'}, name)
profiles.append(record)
finally:
reset_secret_scope(st)
reset_hermes_home_override(ht)
result = dict(schema=1, profiles=profiles, checks=checks, total_checks=len(checks),
passed=sum(c['passed'] for c in checks), failed=[c for c in checks if not c['passed']],
runtime_registries_checked=args.runtime,
limitations=['No inference or audio generation.', 'No notification sent.',
'No SSH target host contacted.', 'No MCP tool executed.',
'No Mac GUI or full restart/restore acceptance.',
'No active session or production transcript was read.'])
# Importing the gateway redirects Python's sys.stdout to its log stream.
# Keep the explicitly documented JSON stdout contract usable by operators.
output = (json.dumps(result, ensure_ascii=False, indent=2) + '\n').encode()
with os.fdopen(os.dup(1), 'wb') as stream:
stream.write(output)
raise SystemExit(bool(result['failed']))
if __name__ == '__main__':
main()
@@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Fix only owner/mode metadata for Hermes' existing bounded config recovery cache.
No file contents are read, copied, hashed, removed or backed up. Dry-run by default.
"""
import argparse
import json
import os
from pathlib import Path
import stat
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
root = Path('/opt/data')
changes = []
homes = [root] + sorted(p for p in (root / 'profiles').iterdir()
if (p / 'config.yaml').is_file())
affected = set()
for home in homes:
owner = (home / 'config.yaml').stat()
cache = home / 'backups/config'
if not cache.is_dir() or cache.is_symlink():
continue
paths = [home / 'backups', cache]
paths += [p for p in cache.glob('config.yaml.*') if p.is_file() and not p.is_symlink()]
for path in paths:
assert path.name != 'vpn.auth' and path.is_relative_to(home / 'backups')
old = path.stat()
mode = 0o700 if path.is_dir() else 0o600
if (old.st_uid, old.st_gid, stat.S_IMODE(old.st_mode)) == (owner.st_uid, owner.st_gid, mode):
continue
changes.append((path, old, owner.st_uid, owner.st_gid, mode))
affected.add('default' if home == root else home.name)
done = []
try:
if args.apply:
for path, old, uid, gid, mode in changes:
now = path.stat()
assert (now.st_dev, now.st_ino) == (old.st_dev, old.st_ino), 'Concurrent replacement'
os.chown(path, uid, gid)
os.chmod(path, mode)
done.append((path, old))
print(json.dumps({'dry_run': not args.apply, 'profiles': sorted(affected),
'metadata_entries': len(changes), 'contents_read': 0,
'copies_created': 0, 'files_deleted': 0, 'services_restarted': 0}))
except BaseException:
for path, old in reversed(done):
os.chown(path, old.st_uid, old.st_gid)
os.chmod(path, stat.S_IMODE(old.st_mode))
raise
if __name__ == '__main__':
main()
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""One-time fleet repair, dry-run by default. Uses installed Hermes APIs.
No agent turns, services, MCP actions, external HTTP requests or notification sends.
Original private bytes exist only in memory for rollback; never printed/saved as backups.
"""
import argparse
import copy
import json
import os
from pathlib import Path
import tempfile
import hermes_yaml as yaml
from agent.secret_scope import build_profile_secret_scope, set_secret_scope, reset_secret_scope
from hermes_constants import set_hermes_home_override, reset_hermes_home_override
from hermes_cli.config_effective import load_user_config_effective
from hermes_cli import managed_scope
ROOT = Path('/opt/data')
KEY = 'HERMES_CUSTOM_192_168_1_212_8120_API_KEY'
CODE = ['terminal', 'file', 'web', 'browser', 'vision', 'skills', 'todo', 'memory',
'session_search', 'clarify', 'code_execution']
DEVS = {'horizon-dev', 'pruefungs-vdi-dev'}
PULSE_ENTRY = b'''"""Hermes directory-plugin entry point for Athena Pulse.
The authenticated HTTP API is mounted from dashboard/plugin_api.py by Hermes'
dashboard extension loader. Desktop code has its own existing entry point.
This plugin intentionally registers no model tools, hooks or background workers.
"""
def register(ctx):
"""Satisfy Hermes' directory-plugin contract; HTTP mounting is host-owned."""
return None
'''
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
homes = [ROOT] + sorted(p for p in (ROOT / 'profiles').iterdir()
if (p / 'config.yaml').is_file())
assert len(homes) == 13, 'Reassess the fleet before applying to a different roster.'
snapshots, writes, modes, created = {}, {}, {}, []
originals = {home: yaml.safe_load((home / 'config.yaml').read_text()) for home in homes}
managed_path = ROOT / 'managed/config.yaml'
managed_before = yaml.safe_load(managed_path.read_text())
assert set(managed_before) == {'providers'}, 'Existing shared speech policy needs review.'
shared = copy.deepcopy(managed_before)
for section in ('stt', 'tts'):
shared[section] = copy.deepcopy(originals[ROOT][section])
assert shared[section]['provider'] == 'openai'
assert shared[section]['openai']['base_url'] == 'http://192.168.1.212:8120/v1'
shared[section]['openai']['api_key'] = '${' + KEY + '}'
# The current NAS design relays audio; do not expose LAN-only endpoints to remote clients.
# auto_tts, barge-in, stop phrases and other user preferences remain profile-owned.
shared['voice'] = {'client_direct': False}
assert shared['providers'] == managed_before['providers']
def stage(path, value):
snapshots[path] = (path.read_bytes(), path.stat())
raw = yaml.safe_dump(value, sort_keys=False, allow_unicode=True).encode()
assert yaml.safe_load(raw.decode()) == value
writes[path] = raw
stage(managed_path, shared)
for home, cfg in originals.items():
ht = set_hermes_home_override(home)
st = set_secret_scope(build_profile_secret_scope(home), profile_home=str(home))
try:
effective = load_user_config_effective(home / 'config.yaml')
for section in ('stt', 'tts'):
if section in cfg:
assert effective[section]['provider'] == 'openai'
assert effective[section]['openai']['api_key'] == build_profile_secret_scope(home)[KEY]
assert effective[section]['openai']['base_url'] == shared[section]['openai']['base_url']
finally:
reset_secret_scope(st)
reset_hermes_home_override(ht)
new = copy.deepcopy(cfg)
new.pop('stt', None)
new.pop('tts', None)
if 'voice' in new:
assert new['voice'].get('client_direct', False) is False
new['voice'].pop('client_direct', None)
if home.name in DEVS:
pins = new.get('platform_toolsets') or {}
assert set(pins) == {'hermes-cli', 'hermes-desktop', 'hermes-api-server'}
assert all(v == CODE for v in pins.values())
new['platform_toolsets'] = {'cli': CODE[:], 'api_server': CODE[:]}
# Every unrelated section, including MCP grants, SSH settings and defaults, is invariant.
exceptions = {'stt', 'tts', 'voice', 'platform_toolsets'}
assert {k: v for k, v in cfg.items() if k not in exceptions} == {
k: v for k, v in new.items() if k not in exceptions}
assert {k: v for k, v in cfg.get('voice', {}).items() if k != 'client_direct'} == new.get('voice', {})
if home.name not in DEVS:
assert new.get('platform_toolsets') == cfg.get('platform_toolsets')
stage(home / 'config.yaml', new)
modes[home / 'config.yaml'] = 0o600
pulse = home / 'plugins/athena-pulse'
if pulse.is_dir() and 'athena-pulse' in (cfg.get('plugins') or {}).get('enabled', []):
assert not (pulse / '__init__.py').exists(), 'Existing plugin code must not be overwritten.'
assert (pulse / 'dashboard/plugin_api.py').is_file()
manifest = yaml.safe_load((pulse / 'plugin.yaml').read_text())
assert manifest['name'] == 'athena-pulse' and manifest['version'] == '0.1.0'
created.append(pulse / '__init__.py')
report = dict(profiles=len(homes), shared_speech=True, coding_platform_pins=len(DEVS),
config_modes='0600', pulse_packages_repaired=len(created),
model_defaults_preserved=True, mcp_grants_preserved=True,
ssh_targets_preserved=True, notifications_unchanged=True,
dry_run=not args.apply)
if not args.apply:
print(json.dumps(report))
return
def atomic(path, data, st, mode=None):
fd, tmp = tempfile.mkstemp(prefix='.' + path.name + '.fleet-', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as f:
os.fchown(f.fileno(), st.st_uid, st.st_gid)
os.fchmod(f.fileno(), mode if mode is not None else st.st_mode & 0o777)
f.write(data)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
done, added = [], []
try:
# Make the common backend available first, then remove the local copies.
for path, raw in writes.items():
old, stat = snapshots[path]
assert path.read_bytes() == old, 'Concurrent configuration change: ' + str(path)
atomic(path, raw, stat, modes.get(path))
done.append(path)
for path in created:
with path.open('xb') as stream:
added.append(path)
stream.write(PULSE_ENTRY)
os.fchown(stream.fileno(), path.parent.stat().st_uid, path.parent.stat().st_gid)
os.fchmod(stream.fileno(), 0o644)
managed_scope.invalidate_managed_cache()
for home in homes:
ht = set_hermes_home_override(home)
st = set_secret_scope(build_profile_secret_scope(home), profile_home=str(home))
try:
cfg = load_user_config_effective(home / 'config.yaml')
assert cfg['model'] == originals[home]['model']
raw_after = yaml.safe_load((home / 'config.yaml').read_text()) or {}
# Compare like with like: persisted references are intentionally
# expanded by the effective loader inside a secret scope.
assert raw_after.get('mcp_servers') == originals[home].get('mcp_servers')
assert cfg['stt']['openai']['api_key'] == build_profile_secret_scope(home)[KEY]
assert cfg['tts']['openai']['api_key'] == build_profile_secret_scope(home)[KEY]
assert cfg['voice']['client_direct'] is False
assert ((home / 'config.yaml').stat().st_mode & 0o777) == 0o600
finally:
reset_secret_scope(st)
reset_hermes_home_override(ht)
report.update(dry_run=False, applied=True, restarts=0, inference_calls=0)
print(json.dumps(report))
except BaseException:
for path in reversed(added):
if path.read_bytes() == PULSE_ENTRY:
path.unlink()
for path in reversed(done):
assert path.read_bytes() == writes[path], 'Concurrent change prevents rollback: ' + str(path)
old, stat = snapshots[path]
atomic(path, old, stat)
managed_scope.invalidate_managed_cache()
raise
if __name__ == '__main__':
main()