Skip to content

The agent that grows with you

refactor: remove Skill Sync (`hermes sync`) and the org skill mirror from core

teknium164ad33e32dad
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py
index 08bfd995e58..25693028824 100644
--- a/agent/prompt_builder.py
+++ b/agent/prompt_builder.py
@@ -22,9 +22,9 @@ from hermes_constants import (
from agent.model_metadata import CHARS_PER_TOKEN
from agent.runtime_cwd import resolve_agent_cwd
from agent.skill_utils import (
- EXCLUDED_SKILL_DIRS, ORG_ACTIVE_MARKER, ORG_MIRROR_DIR_NAME, ORG_PROVENANCE_FILE, SKILL_SUPPORT_DIRS,
+ EXCLUDED_SKILL_DIRS, SKILL_SUPPORT_DIRS,
TIER_LOCAL, extract_skill_conditions, extract_skill_description, get_disabled_skill_names, get_skill_search_roots,
- iter_skill_index_files, parse_frontmatter, read_active_org_id, skill_matches_apps, skill_matches_environment,
+ iter_skill_index_files, parse_frontmatter, skill_matches_apps, skill_matches_environment,
skill_matches_platform, skill_matches_platform_list,
)
from tools.threat_patterns import scan_for_threats as _scan_for_threats
@@ -1227,24 +1227,12 @@ def clear_skills_system_prompt_cache(*, clear_snapshot: bool = False) -> None:
def _build_skills_manifest(skills_dir: Path) -> dict[str, list[int]]:
- """File-signature manifest of every SKILL.md and DESCRIPTION.md; only the ACTIVE org mirror participates, and
- the ``.active_org`` marker is included so switching/leaving an org invalidates the snapshot by itself."""
+ """File-signature manifest of every SKILL.md and DESCRIPTION.md."""
manifest: dict[str, list[int]] = {}
skills_dir_str = str(skills_dir)
prefix_len = len(os.path.join(skills_dir_str, ""))
- active_org = read_active_org_id(skills_dir)
- org_root = os.path.join(skills_dir_str, ORG_MIRROR_DIR_NAME)
- try:
- st = os.stat(os.path.join(org_root, ORG_ACTIVE_MARKER))
- manifest[ORG_MIRROR_DIR_NAME + "/" + ORG_ACTIVE_MARKER] = list(file_signature(st))
- except OSError:
- pass
for root, dirs, files in os.walk(skills_dir_str, followlinks=True):
has_skill_md = "SKILL.md" in files
- if root == skills_dir_str and ORG_MIRROR_DIR_NAME in dirs and active_org is None:
- dirs.remove(ORG_MIRROR_DIR_NAME)
- elif root == org_root:
- dirs[:] = [d for d in dirs if d == active_org]
dirs[:] = [d for d in dirs if d not in EXCLUDED_SKILL_DIRS and not (has_skill_md and d in SKILL_SUPPORT_DIRS)]
for filename in ("SKILL.md", "DESCRIPTION.md"):
path = os.path.join(root, filename)
@@ -1278,10 +1266,6 @@ def _requires_apps_list(frontmatter: dict) -> list[str]:
def _build_snapshot_entry(skill_file: Path, skills_dir: Path, frontmatter: dict, description: str) -> dict:
"""Serialisable metadata dict for one skill."""
parts = skill_file.relative_to(skills_dir).parts
- # Org mirror: category/name derive from the path WITHIN `_org/<org_id>/`; org_id drives labeling + collisions.
- org_id: str | None = None
- if len(parts) >= 3 and parts[0] == ORG_MIRROR_DIR_NAME:
- org_id, parts = parts[1], parts[2:]
skill_name = skill_file.parent.name # == parts[-2] whenever a parent component exists
category = "general" if len(parts) < 2 else "/".join(parts[:-2]) if len(parts) > 2 else parts[0]
platforms = frontmatter.get("platforms") or []
@@ -1293,21 +1277,6 @@ def _build_snapshot_entry(skill_file: Path, skills_dir: Path, frontmatter: dict,
"conditions": extract_skill_conditions(frontmatter),
"requires_apps": _requires_apps_list(frontmatter),
}
- if org_id:
- entry["org_id"] = org_id
- # Author from the pull-time provenance sidecar (token-verified at
- # push by the plane's author_mismatch guard). Best-effort.
- try:
- import json as _json
-
- prov_path = (
- skills_dir / ORG_MIRROR_DIR_NAME / org_id / ORG_PROVENANCE_FILE
- )
- prov = _json.loads(prov_path.read_text(encoding="utf-8-sig"))
- device = str(prov.get("author_device") or "")
- entry["org_author"] = device or str(prov.get("author_user_id") or "")
- except Exception:
- entry["org_author"] = ""
return entry
@@ -1420,22 +1389,13 @@ def _scan_extra_root(root: Path, skill_files, tier: int, log_fmt: str) -> list[t
def _label_visible_entries(visible_entries: list[dict], skills_by_category: dict[str, list[tuple[str, str]]]) -> None:
- """Index rows under each entry's ``load_name`` (what skill_view accepts); org labeling + FAIL-LOUD
- collisions: a personal/org name clash flags every loadable side with the exact path to load."""
+ """Index rows under each entry's ``load_name`` (what skill_view accepts)."""
from agent.skill_utils import TIER_PROJECT
- name_owners: dict[str, set[str]] = {}
- for entry in visible_entries:
- name_owners.setdefault(entry["name"], set()).add("org" if entry.get("org_id") else "personal")
for entry in (e for e in visible_entries if e["load_name"]):
- desc, org_id = entry.get("description", ""), entry.get("org_id")
- if org_id:
- author = entry.get("org_author") or ""
- desc = f"[org-shared{': by ' + author if author else ''}] {desc}".strip()
- elif entry["tier"] == TIER_PROJECT:
+ desc = entry.get("description", "")
+ if entry["tier"] == TIER_PROJECT:
desc = f"[project] {desc}".strip()
- category = f"org:{org_id}" if org_id else (entry.get("category") or "general")
- if len(name_owners[entry["name"]]) > 1:
- desc = f"[name collision β€” also exists {'personally' if org_id else 'in your org'}; load by this exact path] {desc}".strip()
+ category = entry.get("category") or "general"
skills_by_category.setdefault(category, []).append((entry["load_name"], desc))
diff --git a/agent/skill_utils.py b/agent/skill_utils.py
index bb6658d2c46..8f8b115bc0e 100644
--- a/agent/skill_utils.py
+++ b/agent/skill_utils.py
@@ -30,44 +30,6 @@ EXCLUDED_SKILL_DIRS = frozenset((
# via skill_view(skill, file_path=...), never scanned as standalone skills.
SKILL_SUPPORT_DIRS = frozenset(("references", "templates", "assets", "scripts"))
-# Org mirrors live under skills/_org/<org_id>/ and are TOKEN-GATED: the sync
-# client writes the marker after verifying the token; no marker => no org skills
-# load. The marker persists offline so already-pulled org skills keep working.
-ORG_MIRROR_DIR_NAME = "_org"
-ORG_ACTIVE_MARKER = ".active_org"
-ORG_PROVENANCE_FILE = ".org-provenance.json"
-ORG_BASELINE_FILE = ".org-baseline.json" # upstream fingerprint; detects local edits
-
-
-def read_active_org_id(skills_dir: Path) -> Optional[str]:
- """The org id whose mirror may resolve, or None (no org skills load)."""
- marker = skills_dir / ORG_MIRROR_DIR_NAME / ORG_ACTIVE_MARKER
- try:
- return (marker.read_text(encoding="utf-8-sig").strip() or None) if marker.exists() else None
- except OSError:
- return None
-
-
-def _org_rel_parts(path, skills_dir: Path) -> Tuple[str, ...]:
- """Path parts of *path* relative to *skills_dir* if it is under ``_org/``, else ``()``."""
- try:
- parts = Path(path).resolve().relative_to(Path(skills_dir).resolve()).parts
- except (OSError, ValueError):
- return ()
- return parts if parts and parts[0] == ORG_MIRROR_DIR_NAME else ()
-
-
-def is_org_mirror_path(path, skills_dir: Path) -> bool:
- """True when *path* is inside the org mirror (``_org/``)."""
- return bool(_org_rel_parts(path, skills_dir))
-
-
-def org_id_of_path(path, skills_dir: Path) -> Optional[str]:
- """The ``<org_id>`` segment for a path under ``_org/<org_id>/...``."""
- parts = _org_rel_parts(path, skills_dir)
- return parts[1] if len(parts) >= 2 else None
-
-
def is_excluded_skill_path(path, *, root: Optional[Path] = None) -> bool:
"""True if *path* should be skipped by skill scanners (VCS/dependency/cache
dirs + support packages). Apply to every SKILL.md from a direct ``rglob``."""
@@ -879,19 +841,10 @@ def is_skill_description_truncated_for_prompt(frontmatter: Dict[str, Any]) -> bo
def iter_skill_index_files(skills_dir: Path, filename: str):
"""Walk skills_dir yielding sorted paths matching *filename*; prunes
- EXCLUDED_SKILL_DIRS and support dirs of skill roots. Org mirrors are
- TOKEN-GATED: only the active org's subdir is walked, so leaving an org
- stops its skills resolving without manual cleanup."""
- skills_dir_str = str(skills_dir)
- active_org = read_active_org_id(skills_dir)
- org_root = os.path.join(skills_dir_str, ORG_MIRROR_DIR_NAME)
+ EXCLUDED_SKILL_DIRS and support dirs of skill roots."""
matches: list[str] = []
- for root, dirs, files in os.walk(skills_dir_str, followlinks=True):
+ for root, dirs, files in os.walk(str(skills_dir), followlinks=True):
has_skill_md = "SKILL.md" in files
- if root == skills_dir_str and ORG_MIRROR_DIR_NAME in dirs and active_org is None:
- dirs.remove(ORG_MIRROR_DIR_NAME)
- elif root == org_root:
- dirs[:] = [d for d in dirs if d == active_org]
dirs[:] = [d for d in dirs if d not in EXCLUDED_SKILL_DIRS and not (has_skill_md and d in SKILL_SUPPORT_DIRS)]
if filename in files:
matches.append(os.path.join(root, filename))
diff --git a/gateway/run.py b/gateway/run.py
index 1f439863fc3..58eb1d5b797 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -4685,18 +4685,6 @@ def _housekeeping_curator() -> None:
maybe_run_curator(idle_for_seconds=float("inf"), on_summary=lambda msg: logger.info("curator: %s", msg))
-def _housekeeping_skill_sync() -> None:
- """Inert unless the access gate is open and a sync base URL is configured."""
- from tools.skills_sync_client import maybe_pull_skills
- maybe_pull_skills()
-
-
-def _housekeeping_org_skill_sync() -> None:
- """Gated on real org membership (the token must carry an org role): solo accounts never reach the network."""
- from tools.skills_sync_client_org import maybe_pull_org_skills
- maybe_pull_org_skills()
-
-
def _housekeeping_plugin_update_check() -> None:
"""Plugin update-check cadence (plugins_cadence): due-gated by
plugins.auto_update_check_hours, read-only, receipt-surfaced; the
@@ -4854,8 +4842,6 @@ def _start_gateway_housekeeping(
# Per served profile: each profile has its own skills tree, curator state, Nous login
# and state.db.
(60, "Curator tick", profile_scoped_chore(runner, _housekeeping_curator)),
- (60, "Sync pull tick", profile_scoped_chore(runner, _housekeeping_skill_sync)),
- (60, "Org sync pull tick", profile_scoped_chore(runner, _housekeeping_org_skill_sync)),
(60, "state.db maintenance tick", profile_scoped_chore(
runner,
# Default-bound now, i.e. OUTSIDE any profile scope: this is the launch home's override.
diff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.py
index 43539057dff..aef89deb00b 100644
--- a/hermes_cli/cli_tui_runtime_mixin.py
+++ b/hermes_cli/cli_tui_runtime_mixin.py
@@ -355,19 +355,6 @@ class CLITuiRuntimeMixin:
on_summary=lambda msg: self._console_print(f"[dim #6b7684]πŸ’Ύ {msg}[/]"),
)
- # Skill sync (personal, then org-shared): inert unless the access gate is open
- # and a sync base URL is configured. The org pull is gated on a real org role on
- # the token (only issued for multi-member orgs), so a solo account never hits
- # the network here. Both fail-quiet.
- try:
- from tools.skills_sync_client import maybe_pull_skills
- from tools.skills_sync_client_org import maybe_pull_org_skills
- except Exception:
- return
- for pull in (maybe_pull_skills, maybe_pull_org_skills):
- with suppress(Exception):
- pull()
-
def _tui_build_application(self, layout, kb, style):
"""Construct the prompt_toolkit Application for the REPL."""
from cli import CLI_CONFIG, EditingMode, _STEADY_CURSOR, _select_classic_cli_pt_output
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index d51ce652993..8d1dc1172a5 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -346,7 +346,6 @@ from typing import Optional
from hermes_cli.subcommands.cron import build_cron_parser
-from hermes_cli.subcommands.sync import build_sync_parser
from hermes_cli.subcommands.gateway import build_gateway_parser
from hermes_cli.subcommands.profile import build_profile_parser
from hermes_cli.subcommands.model import build_model_parser
@@ -804,7 +803,6 @@ from hermes_cli.main_agent_cmds import (
)
from hermes_cli.main_platform_setup import (
cmd_slack,
- cmd_sync,
cmd_whatsapp,
cmd_whatsapp_cloud,
)
@@ -2907,7 +2905,7 @@ _BUILTIN_SUBCOMMANDS = frozenset(
"prompt-size",
"resume",
"send", "sessions", "setup",
- "skin", "skills", "slack", "status", "sync", "tools", "uninstall", "update",
+ "skin", "skills", "slack", "status", "tools", "uninstall", "update",
"usage", "vault",
"webhook", "whatsapp", "whatsapp-cloud", "worktree", "chat", "secrets", "security",
"browser",
@@ -3495,7 +3493,6 @@ def _build_cli_parser():
build_status_parser(subparsers, cmd_status=cmd_status)
build_pause_parser(subparsers)
build_cron_parser(subparsers, cmd_cron=cmd_cron)
- build_sync_parser(subparsers, cmd_sync=cmd_sync)
build_webhook_parser(subparsers, cmd_webhook=cmd_webhook)
from hermes_cli.subcommands.peer import build_peer_parser
diff --git a/hermes_cli/main_platform_setup.py b/hermes_cli/main_platform_setup.py
index f72db22199c..bb82d2e19ba 100644
--- a/hermes_cli/main_platform_setup.py
+++ b/hermes_cli/main_platform_setup.py
@@ -1,5 +1,4 @@
-"""Interactive messaging-platform setup wizards: WhatsApp (bridge + Cloud API), Slack manifest,
-Skill Sync.
+"""Interactive messaging-platform setup wizards: WhatsApp (bridge + Cloud API), Slack manifest.
Split out of ``hermes_cli/main.py``. Names that still live in main are imported lazily at call time.
"""
@@ -233,173 +232,6 @@ def cmd_whatsapp_cloud(args):
return run_whatsapp_cloud_setup()
-_SYNC_USAGE = (
- "usage: hermes sync "
- "<status|pull|push|now|enable|disable|device|propose>\n"
- "\n"
- "Your skills, across your devices:\n"
- " status Show what is synced, and from where\n"
- " pull Pull your synced skills\n"
- " push Push your opted-in skills\n"
- " now Reconcile now: pull then push\n"
- " enable <skill> Include a skill in your sync\n"
- " disable <skill> Exclude a skill from your sync\n"
- " device [--name N] Show or set this device's label\n"
- "\n"
- "Shared with your team:\n"
- " propose <skill> Share a skill with your organisation")
-
-
-def _sync_device(args, ssc) -> int:
- name = getattr(args, "device_name", None)
- if name is not None:
- try:
- stored = ssc.set_device_name(name)
- except ValueError as e:
- _err(f"error: {e}")
- return 1
- print(f"device label set to '{stored}'.")
- _err("New commits from this device will use this label; existing commits keep their previous one.")
- return 0
- # No --name: print the current (creating a default on first use).
- print(ssc.stable_device_id())
- return 0
-
-
-def _sync_propose(args, ssc) -> int:
- from tools.skills_sync_client_org import propose_skill
- name = args.name
- try:
- result = propose_skill(name, message=args.message)
- except ssc.SyncInertError as e:
- _err(f"cannot share this skill: {e}")
- return 1
- except ssc.SyncError as e:
- _err(f"could not share '{name}': {e}")
- return 1
- if result.get("proposal_pending"):
- print(f"Shared '{name}' with your organisation β€” an admin needs to "
- f"approve it (proposal #{result.get('proposal_id')}). It is "
- f"not live for the team until then.")
- else:
- print(f"Added '{name}' to your organisation's shared skills.")
- return 0
-
-
-def _sync_toggle(args, sub: str) -> int:
- from tools.skill_usage import set_sync, is_curation_eligible
- skill = args.skill
- if not is_curation_eligible(skill):
- _err(f"'{skill}' is not sync-eligible (bundled, hub-installed, "
- f"external, or not found). Only agent-created / user-authored "
- f"skills under ~/.hermes/skills/ can sync.")
- return 1
- set_sync(skill, sub == "enable")
- print(f"sync {'enabled' if sub == 'enable' else 'disabled'} for '{skill}'.")
- return 0
-
-
-def _sync_status(ssc) -> int:
- import json as _json
- status = ssc.sync_status()
- print(_json.dumps(status, indent=2, ensure_ascii=False))
- if status.get("org_available"):
- n = len(status.get("org_skills") or [])
- modified = status.get("org_skills_modified") or []
- _err(f"\nOrg skills: {n} shared skill(s) from your organisation "
- f"(your role: {status.get('org_role')}). They load alongside "
- f"your own, labeled by origin, and you can edit them.")
- if modified:
- _err(f" {len(modified)} with local edits not yet shared: "
- f"{', '.join(modified)}\n"
- f" Share them back with `hermes sync propose <skill>`. "
- f"Org updates will not overwrite them.")
- elif status.get("logged_in"):
- _err("\nOrg skills: not applicable β€” this account isn't a member of a shared organisation.")
- if not status.get("logged_in"):
- _err("\nNot logged into Nous Portal β€” sync is inert.")
- elif not status.get("nous_admin"):
- _err("\nSync is not enabled for your account yet.")
- elif not status.get("feature_enabled"):
- _err("\nSync feature is off for this instance (set HERMES_SYNC_ENABLED=1 "
- "or config.yaml sync.enabled: true). Sync is inert.")
- elif not status.get("base_url"):
- _err("\nNo sync base URL configured (config.yaml sync.base_url or HERMES_SYNC_BASE_URL). Sync is inert.")
- return 0
-
-
-def _sync_pull(ssc, identity):
- result = ssc.pull_skills(identity=identity)
- # Refresh the org mirror too when this account belongs to an organisation (no-op
- # otherwise), so one pull covers both.
- from tools.skills_sync_client_org import maybe_pull_org_skills
- org_result = maybe_pull_org_skills()
- if org_result:
- n = len(org_result.get("updated") or [])
- _err(f"org: refreshed {n} shared skill(s) from your organisation.")
- clashes = org_result.get("conflicted") or []
- if clashes:
- _err(f"org: {len(clashes)} skill(s) have BOTH local edits "
- f"and org updates, so they were left as-is: "
- f"{', '.join(clashes)}\n"
- f" Your local version is intact. Review it, then "
- f"either propose it or delete the local copy and pull "
- f"again to take the org version.")
- return result
-
-
-# gated (identity-checked) sync subcommands: name -> (ssc, identity) -> result
-_SYNC_GATED = {
- "pull": _sync_pull,
- "push": lambda ssc, identity: ssc.push_skills(identity=identity, message="hermes sync push"),
- "now": lambda ssc, identity: {"pull": ssc.pull_skills(identity=identity),
- "push": ssc.push_skills(identity=identity, message="hermes sync now")}}
-
-
-def cmd_sync(args):
- """Skill Sync β€” personal sync across devices, plus sharing with your org."""
- import json as _json
- sub = getattr(args, "sync_command", None)
- if sub in {None, ""}:
- _err(_SYNC_USAGE)
- return 1
- if sub in {"enable", "disable"}:
- return _sync_toggle(args, sub)
-
- from tools import skills_sync_client as ssc
- if sub == "device":
- return _sync_device(args, ssc)
- if sub == "propose":
- return _sync_propose(args, ssc)
- if sub == "status":
- return _sync_status(ssc)
-
- # pull / push / now β€” enforce the gate up front with a clear message.
- try:
- identity = ssc.resolve_identity()
- except ssc.SyncInertError as e:
- _err(f"sync inert: {e}")
- return 1
- if not identity.get("nous_admin"):
- _err("sync unavailable: not enabled for your account yet.")
- return 1
- if not ssc.resolve_sync_base_url():
- _err("sync inert: no sync base URL configured (config.yaml sync.base_url or HERMES_SYNC_BASE_URL).")
- return 1
-
- action = _SYNC_GATED.get(sub)
- if action is None:
- _err(f"Unknown sync subcommand: {sub}")
- return 1
- try:
- result = action(ssc, identity)
- except ssc.SyncError as e:
- _err(f"sync failed: {e}")
- return 1
- print(_json.dumps(result, indent=2, ensure_ascii=False))
- return 0
-
-
def cmd_slack(args):
"""``hermes slack <subcommand>``; ``manifest`` prints or writes a Slack app manifest with
every gateway command registered as a first-class slash."""
diff --git a/hermes_cli/subcommands/sync.py b/hermes_cli/subcommands/sync.py
deleted file mode 100644
index 69d4200086e..00000000000
--- a/hermes_cli/subcommands/sync.py
+++ /dev/null
@@ -1,62 +0,0 @@
-"""``hermes sync`` subcommand parser β€” Skill Sync.
-
-Personal sync (status/pull/push/now/enable/disable/device) moves your own skills across
-your devices; ``propose`` shares a skill with your organisation. Sync is INERT unless the
-resolved Nous token carries the access-gate claim AND a sync base URL is configured β€” the
-commands report that state rather than failing opaquely.
-"""
-
-from __future__ import annotations
-
-import argparse
-from typing import Callable
-
-
-def build_sync_parser(subparsers, *, cmd_sync: Callable) -> None:
- """Attach the ``sync`` subcommand (and its sub-actions) to ``subparsers``."""
- sync_parser = subparsers.add_parser(
- "sync", help="Skill Sync β€” sync your skills across devices and with your team",
- description="Skill Sync keeps your skills with you. Personal sync moves your "
- "own skills between your devices; if you belong to an "
- "organisation, you also get its shared skills and can propose "
- "your own back to the team.",
- epilog="Examples:\n"
- " hermes sync status what is synced, and from where\n"
- " hermes sync enable my-skill include a skill in your sync\n"
- " hermes sync now pull, then push\n"
- " hermes sync propose my-skill share a skill with your team\n",
- formatter_class=argparse.RawDescriptionHelpFormatter)
- sync_sub = sync_parser.add_subparsers(dest="sync_command")
-
- sync_sub.add_parser("status", help="Show what is synced, and from where")
- sync_sub.add_parser("pull", help="Pull your synced skills (and your organisation's)")
- sync_sub.add_parser("push", help="Push your opted-in skills")
- sync_sub.add_parser("now", help="Reconcile now: pull then push")
-
- enable = sync_sub.add_parser("enable", help="Include a skill in your sync")
- enable.add_argument("skill", help="Skill name (frontmatter name / directory name)")
-
- disable = sync_sub.add_parser("disable", help="Exclude a skill from your sync")
- disable.add_argument("skill", help="Skill name (frontmatter name / directory name)")
-
- device = sync_sub.add_parser(
- "device", help="Show or set this device's label (shown in the sync console)")
- device.add_argument(
- "--name", dest="device_name", default=None,
- help="Set a human-friendly label for this device (e.g. \"Ben's Laptop\"). "
- "Omit to print the current label.")
-
- # Org-shared skills. A member's submission becomes a proposal an admin
- # reviews; an admin's merges straight into the shared set. Accounts that
- # aren't in a shared organisation are told so plainly.
- propose = sync_sub.add_parser(
- "propose", help="Share a skill with your organisation",
- description="Submit one of your skills to your organisation's shared set. If "
- "you are an admin it is added directly; otherwise it becomes a "
- "proposal for an admin to review. Accounts that aren't part of a "
- "shared organisation don't have this workflow.")
- propose.add_argument("name", help="Skill name to share")
- propose.add_argument(
- "-m", "--message", default=None, help="Optional message describing the change")
-
- sync_parser.set_defaults(func=cmd_sync)
diff --git a/hermes_cli/web_server_sessions.py b/hermes_cli/web_server_sessions.py
index e7ca183d5b7..28142ea7f95 100644
--- a/hermes_cli/web_server_sessions.py
+++ b/hermes_cli/web_server_sessions.py
@@ -292,8 +292,6 @@ def _maybe_run_skill_maintenance(started_at: float) -> None:
return
from agent.curator import maybe_run_curator
- from tools.skills_sync_client import maybe_pull_skills
- from tools.skills_sync_client_org import maybe_pull_org_skills
try:
idle_for = _skill_maintenance_idle_for(started_at)
@@ -301,11 +299,6 @@ def _maybe_run_skill_maintenance(started_at: float) -> None:
maybe_run_curator(idle_for_seconds=idle_for)
except Exception as exc:
_log.debug("serve curator tick skipped: %s", exc)
- for pull in (maybe_pull_skills, maybe_pull_org_skills):
- try:
- pull()
- except Exception as exc:
- _log.debug("serve skill sync tick skipped: %s", exc)
async def _auto_archive_ticker_loop(
diff --git a/tests/agent/test_org_skill_namespace.py b/tests/agent/test_org_skill_namespace.py
deleted file mode 100644
index 9efaef3421a..00000000000
--- a/tests/agent/test_org_skill_namespace.py
+++ /dev/null
@@ -1,305 +0,0 @@
-"""M2 org-skill namespace: token-gated resolution, provenance, collisions.
-
-Covers the design agreed 2026-07-23 (bare-name first-class org skills):
- 1. TOKEN-GATED discovery β€” only the `.active_org`-marked mirror resolves;
- stale mirrors and marker-less trees never load.
- 2. Fail-loud collisions β€” a personal/org name clash lists BOTH sides flagged;
- skill_view's existing multi-candidate guard refuses the bare name.
- 3. Load-time provenance header β€” org skill content announces org + author.
- 4. Org mirrors are read-only (skill_manage guards) and curation-exempt.
-"""
-
-import json
-
-
-from agent import skill_utils as sku
-from agent.prompt_builder import _build_snapshot_entry
-
-
-def _mk_skill(root, rel, name=None, body="# body\n"):
- d = root
- for part in rel.split("/"):
- d = d / part
- d.mkdir(parents=True, exist_ok=True)
- (d / "SKILL.md").write_text(
- f"---\nname: {name or rel.split('/')[-1]}\ndescription: d\n---\n{body}",
- encoding="utf-8",
- )
- return d
-
-
-def _mark_active(skills, org_id):
- org_root = skills / sku.ORG_MIRROR_DIR_NAME
- org_root.mkdir(parents=True, exist_ok=True)
- (org_root / sku.ORG_ACTIVE_MARKER).write_text(org_id, encoding="utf-8")
-
-
-class TestTokenGatedDiscovery:
- def test_no_marker_no_org_skills(self, tmp_path):
- skills = tmp_path / "skills"
- _mk_skill(skills, "personal-a")
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x")
- found = [p.parent.name for p in sku.iter_skill_index_files(skills, "SKILL.md")]
- assert "personal-a" in found
- assert "shared-x" not in found # unmarked mirror never resolves
-
- def test_marker_gates_to_active_org_only(self, tmp_path):
- skills = tmp_path / "skills"
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x")
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-OLD/stale-y", name="stale-y")
- _mark_active(skills, "org-1")
- found = [p.parent.name for p in sku.iter_skill_index_files(skills, "SKILL.md")]
- assert "shared-x" in found
- assert "stale-y" not in found # stale mirror pruned at resolution
-
- def test_switching_org_flips_resolution(self, tmp_path):
- skills = tmp_path / "skills"
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x")
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-2/other-z", name="other-z")
- _mark_active(skills, "org-2")
- found = [p.parent.name for p in sku.iter_skill_index_files(skills, "SKILL.md")]
- assert found and "other-z" in found and "shared-x" not in found
-
- def test_helpers(self, tmp_path):
- skills = tmp_path / "skills"
- d = _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-9/cat/sk", name="sk")
- assert sku.is_org_mirror_path(d, skills) is True
- assert sku.org_id_of_path(d, skills) == "org-9"
- p = _mk_skill(skills, "plain")
- assert sku.is_org_mirror_path(p, skills) is False
- assert sku.read_active_org_id(skills) is None
- _mark_active(skills, "org-9")
- assert sku.read_active_org_id(skills) == "org-9"
-
-
-class TestSnapshotEntryProvenance:
- def test_org_entry_strips_prefix_and_carries_provenance(self, tmp_path):
- skills = tmp_path / "skills"
- d = _mk_skill(
- skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/devops/beta", name="beta"
- )
- (skills / sku.ORG_MIRROR_DIR_NAME / "org-1" / sku.ORG_PROVENANCE_FILE).write_text(
- json.dumps(
- {"author_device": "bens-macbook-a1b2c3", "author_user_id": "u1"}
- ),
- encoding="utf-8",
- )
- entry = _build_snapshot_entry(d / "SKILL.md", skills, {"name": "beta"}, "d")
- assert entry["org_id"] == "org-1"
- assert entry["org_author"] == "bens-macbook-a1b2c3"
- # Category derives from the path WITHIN the mirror, not _org/org-1/...
- assert entry["category"] == "devops"
- assert entry["skill_name"] == "beta"
-
- def test_personal_entry_unchanged(self, tmp_path):
- skills = tmp_path / "skills"
- d = _mk_skill(skills, "devops/beta", name="beta")
- entry = _build_snapshot_entry(d / "SKILL.md", skills, {"name": "beta"}, "d")
- assert "org_id" not in entry
- assert entry["category"] == "devops"
-
-
-class TestListingCollisionsAndLabels:
- def _render(self, tmp_path, monkeypatch):
- from agent import prompt_builder as pb
-
- skills = tmp_path / "skills"
- skills.mkdir(parents=True, exist_ok=True)
- monkeypatch.setattr(pb, "get_skills_dir", lambda: skills, raising=True)
- monkeypatch.setattr(pb, "get_skill_search_roots", lambda *a, **k: [], raising=True)
- monkeypatch.setattr(pb, "get_disabled_skill_names", lambda *a, **k: set())
- monkeypatch.setattr(
- pb, "_skills_prompt_snapshot_path", lambda: tmp_path / "snap.json"
- )
- pb.clear_skills_system_prompt_cache()
- return skills, pb
-
- def test_org_skill_listed_with_provenance_tag(self, tmp_path, monkeypatch):
- skills, pb = self._render(tmp_path, monkeypatch)
- _mk_skill(skills, "personal-a")
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x")
- (skills / sku.ORG_MIRROR_DIR_NAME / "org-1" / sku.ORG_PROVENANCE_FILE).write_text(
- json.dumps({"author_device": "bens-macbook"}), encoding="utf-8"
- )
- _mark_active(skills, "org-1")
- out = pb.build_skills_system_prompt()
- assert "org:org-1" in out
- assert "[org-shared: by bens-macbook]" in out
- assert "personal-a" in out
-
- def test_collision_flags_both_sides(self, tmp_path, monkeypatch):
- skills, pb = self._render(tmp_path, monkeypatch)
- _mk_skill(skills, "k8s-debug", body="personal version\n")
- _mk_skill(
- skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/k8s-debug", name="k8s-debug"
- )
- _mark_active(skills, "org-1")
- out = pb.build_skills_system_prompt()
- # Neither silently wins: the org copy is flagged under the exact path skill_view loads, and the
- # root-level personal copy (whose only path IS the bare name, so nothing can load it) is called out.
- assert "- _org/org-1/k8s-debug: [name collision" in out
- assert "- k8s-debug:" not in out
- assert "A copy of k8s-debug is not listed" in out and "same skills directory tier" in out
-
- def test_no_collision_flag_when_unique(self, tmp_path, monkeypatch):
- skills, pb = self._render(tmp_path, monkeypatch)
- _mk_skill(skills, "personal-a")
- _mk_skill(skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x")
- _mark_active(skills, "org-1")
- out = pb.build_skills_system_prompt()
- assert "[name collision" not in out
-
-
-class TestOrgSkillsAreEditableInPlace:
- """The learning loop must work ON shared skills, not around them.
-
- Refusing edits to `_org/` froze exactly the skills the most people use:
- the agent is instructed to patch a skill the moment it finds a gap, and
- "fork it to a personal skill first" is not something an agent does
- mid-task. So edits land in place; org updates never clobber them; the
- user (or auto-propose) shares them back.
- """
-
- def _org_skill(self, tmp_path, monkeypatch):
- from tools import skill_manager_tool as smt
- from agent import skill_utils as _sku
-
- skills = tmp_path / "skills"
- d = _mk_skill(
- skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x"
- )
- _mark_active(skills, "org-1")
- monkeypatch.setattr(smt, "_skills_dir", lambda: skills)
- monkeypatch.setattr(
- _sku, "get_all_skills_dirs", lambda: [skills], raising=True
- )
- return smt, skills, d
-
- def test_patch_is_allowed_and_applied(self, tmp_path, monkeypatch):
- smt, _skills, d = self._org_skill(tmp_path, monkeypatch)
- result = smt._patch_skill("shared-x", "body", "improved")
- assert result["success"] is True, result.get("error")
- assert "improved" in (d / "SKILL.md").read_text(encoding="utf-8")
-
-
- def test_delete_is_still_refused(self, tmp_path, monkeypatch):
- smt, _skills, d = self._org_skill(tmp_path, monkeypatch)
- guard = smt._org_mirror_write_guard("shared-x", d, "delete")
- assert guard is not None and guard["success"] is False
- assert "admin" in guard["error"]
-
- def test_curation_is_allowed(self, tmp_path, monkeypatch):
- from tools import skill_usage as su
-
- skills = tmp_path / "skills"
- d = _mk_skill(
- skills, f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x", name="shared-x"
- )
- monkeypatch.setattr(su, "_skills_dir", lambda: skills)
- # The curator must be able to improve shared skills β€” they are the
- # highest-leverage ones in the system.
- assert su.is_curation_eligible("shared-x", d) is True
-
-
-class TestOrgPullIsWiredIn:
- """Guards the integration gap that unit tests structurally cannot catch.
-
- The org pull functions were fully implemented and unit-tested while having
- ZERO runtime callers, so org skills never loaded for anyone. Testing the
- functions directly could never surface that. These tests assert the CALL
- SITES exist, so the feature can't silently become dead code again.
- """
-
-
-
- def test_sync_status_exposes_org_state(self):
- from tools import skills_sync_client as ssc
-
- status = ssc.sync_status()
- # These keys must always be present so a user can tell whether the org
- # workflow applies to them, rather than it being invisible.
- for key in ("org_available", "org_id", "org_role", "org_skills"):
- assert key in status, f"sync status must expose {key!r}"
-
-
-
-
-
-class TestLocalEditsSurviveOrgUpdates:
- """Ben's requirement: local edits are never silently overwritten.
-
- An org pull materializes the shared set. Before this, it `rmtree`'d each
- skill dir and re-wrote it, so any local improvement vanished on the next
- session start with no warning. Now a locally-modified skill is skipped
- and reported as a conflict for the user to resolve deliberately.
- """
-
- def _mirror(self, tmp_path, monkeypatch, body="original\n"):
- from tools import skills_sync_client as ssc
-
- skills = tmp_path / "skills"
- d = _mk_skill(
- skills,
- f"{sku.ORG_MIRROR_DIR_NAME}/org-1/shared-x",
- name="shared-x",
- body=body,
- )
- _mark_active(skills, "org-1")
- monkeypatch.setattr(ssc, "_skills_dir", lambda: skills)
- monkeypatch.setattr(
- ssc, "_org_dir", lambda: skills / sku.ORG_MIRROR_DIR_NAME
- )
- from tools import skills_sync_client_org as org
- return org, skills, d
-
- def test_unmodified_skill_is_not_flagged(self, tmp_path, monkeypatch):
- org, _skills, d = self._mirror(tmp_path, monkeypatch)
- org._write_org_baseline(
- "org-1",
- {"shared-x": {"fingerprint": org._skill_dir_fingerprint(d), "tree": "t1"}},
- )
- assert org.org_skill_is_locally_modified("shared-x", "org-1") is False
- assert org.list_locally_modified_org_skills("org-1") == []
-
- def test_edited_skill_is_detected(self, tmp_path, monkeypatch):
- org, _skills, d = self._mirror(tmp_path, monkeypatch)
- org._write_org_baseline(
- "org-1",
- {"shared-x": {"fingerprint": org._skill_dir_fingerprint(d), "tree": "t1"}},
- )
- (d / "SKILL.md").write_text("---\nname: shared-x\n---\nEDITED\n", encoding="utf-8")
- assert org.org_skill_is_locally_modified("shared-x", "org-1") is True
- assert org.list_locally_modified_org_skills("org-1") == ["shared-x"]
-
- def test_missing_baseline_does_not_cry_wolf(self, tmp_path, monkeypatch):
- org, _skills, _d = self._mirror(tmp_path, monkeypatch)
- # Mirror pulled before baselines existed β€” must not be reported as
- # modified (that would block every update with a phantom conflict).
- assert org.org_skill_is_locally_modified("shared-x", "org-1") is False
-
- def test_fingerprint_is_content_based_not_mtime(self, tmp_path, monkeypatch):
- import os
- import time
-
- org, _skills, d = self._mirror(tmp_path, monkeypatch)
- before = org._skill_dir_fingerprint(d)
- time.sleep(0.01)
- os.utime(d / "SKILL.md", None) # touch: mtime changes, content doesn't
- assert org._skill_dir_fingerprint(d) == before
-
- def test_auto_propose_defaults_off(self, monkeypatch):
- from tools import skills_sync_client as ssc
-
- monkeypatch.delenv("HERMES_SYNC_ORG_AUTO_PROPOSE", raising=False)
- monkeypatch.setattr(
- "hermes_cli.config.load_config", lambda: {}, raising=False
- )
- # Default must be OFF: silently pushing every agent edit to the whole
- # organisation is not a safe default.
- assert ssc.sync_org_auto_propose() is False
-
- def test_auto_propose_can_be_enabled_by_env(self, monkeypatch):
- from tools import skills_sync_client as ssc
-
- monkeypatch.setenv("HERMES_SYNC_ORG_AUTO_PROPOSE", "1")
- assert ssc.sync_org_auto_propose() is True
diff --git a/tests/gateway/test_housekeeping_profile_scope.py b/tests/gateway/test_housekeeping_profile_scope.py
index b6aec86dd5c..c4252085231 100644
--- a/tests/gateway/test_housekeeping_profile_scope.py
+++ b/tests/gateway/test_housekeeping_profile_scope.py
@@ -2,11 +2,11 @@
profile's runtime scope on a multiplexed gateway.
The housekeeping thread has no turn on the stack, so nothing bound a profile for it: under
-``gateway.multiplex_profiles`` the skills-sync pulls resolved Nous credentials through the
-fail-closed reader and logged ``no profile secret scope on a multiplexed call`` four times per
-hourly tick, per chore, while the launch profile's home/credentials leaked into every served
-profile's pull. The MCP config reconciler already iterated the served profiles under
-``_profile_runtime_scope``; the sync/curator ticks now ride the same iteration.
+``gateway.multiplex_profiles`` credential-reading chores resolved Nous credentials through the
+fail-closed reader and logged ``no profile secret scope on a multiplexed call`` on every hourly
+tick, while the launch profile's home/credentials leaked into every served profile's chore. The
+MCP config reconciler already iterated the served profiles under ``_profile_runtime_scope``; the
+curator tick now rides the same iteration.
"""
import json
@@ -67,20 +67,16 @@ def two_homes(tmp_path, monkeypatch):
def _record_credential_chores(monkeypatch):
- """Replace the three credential-reading chores with recorders of (home, Nous override) they see."""
+ """Replace the credential-reading chores with recorders of (home, Nous override) they see."""
import agent.curator as curator
- import tools.skills_sync_client as ssc
- import tools.skills_sync_client_org as sso
from hermes_cli.auth_nous import _nous_inference_env_override
from hermes_constants import get_hermes_home
- seen: dict = {"sync": [], "org": [], "curator": []}
+ seen: dict = {"curator": []}
def _rec(key):
return lambda *a, **k: seen[key].append((get_hermes_home().name, _nous_inference_env_override()))
- monkeypatch.setattr(ssc, "maybe_pull_skills", _rec("sync"))
- monkeypatch.setattr(sso, "maybe_pull_org_skills", _rec("org"))
monkeypatch.setattr(curator, "maybe_run_curator", _rec("curator"))
return seen
@@ -89,7 +85,7 @@ def _run_60_ticks(runner):
gateway_run._start_gateway_housekeeping(_Ticks(60), interval=0, runner=runner)
-def test_multiplexed_sync_ticks_run_once_per_profile_in_its_own_scope(two_homes, monkeypatch, caplog):
+def test_multiplexed_credential_chores_run_once_per_profile_in_its_own_scope(two_homes, monkeypatch, caplog):
"""Under multiplex every credential-reading chore visits each served profile inside ITS scope:
A's tick reads A's override, B's reads B's (B never sees A's), and no fail-closed credential
read fires the ``no profile secret scope`` warning. The ambient home is untouched afterwards."""
@@ -106,7 +102,7 @@ def test_multiplexed_sync_ticks_run_once_per_profile_in_its_own_scope(two_homes,
set_multiplex_active(False)
expected = [(a.name, "https://a.example/v1"), (b.name, "https://b.example/v1")]
- assert seen == {"sync": expected, "org": expected, "curator": expected}
+ assert seen == {"curator": expected}
assert not [r for r in caplog.records if "no profile secret scope" in r.getMessage()]
assert get_hermes_home() == a
@@ -282,7 +278,7 @@ def test_prune_unlinks_transcripts_under_the_configured_sessions_dir(two_homes,
assert not (b / "sessions" / "old.jsonl").exists(), "profile b's transcript survived"
-def test_single_profile_sync_ticks_run_once_against_the_process_home(two_homes, monkeypatch):
+def test_single_profile_credential_chores_run_once_against_the_process_home(two_homes, monkeypatch):
"""Control: a single-profile gateway (multiplex off) still runs each chore exactly once against
the process home β€” the named profile directory on disk is not visited."""
a, _b = two_homes
@@ -290,8 +286,7 @@ def test_single_profile_sync_ticks_run_once_against_the_process_home(two_homes,
_run_60_ticks(SimpleNamespace(config=SimpleNamespace(multiplex_profiles=False)))
- assert {k: [h for h, _ in v] for k, v in seen.items()} == {
- "sync": [a.name], "org": [a.name], "curator": [a.name]}
+ assert {k: [h for h, _ in v] for k, v in seen.items()} == {"curator": [a.name]}
def test_multiplexed_plugin_update_check_visits_every_served_profiles_plugins(two_homes, monkeypatch):
diff --git a/tests/tools/test_multiplex_tool_cache_scope.py b/tests/tools/test_multiplex_tool_cache_scope.py
index 8ad94b4fc87..7130c1f4c09 100644
--- a/tests/tools/test_multiplex_tool_cache_scope.py
+++ b/tests/tools/test_multiplex_tool_cache_scope.py
@@ -5,7 +5,6 @@ only HTTP transports are stubbed.
from __future__ import annotations
import json
-import threading
from pathlib import Path
import pytest
@@ -122,35 +121,6 @@ def test_home_keyed_caches_serve_each_profile_its_own_config(tmp_path, monkeypat
sem_a.release()
-def test_debounced_sync_push_fires_in_the_scheduling_profiles_context(two_homes, monkeypatch):
- """Timer threads start with empty ContextVars: the push must run under the writing profile's
- home, and B's write must not cancel A's pending push."""
- import tools.skill_manager_tool as smt
- import tools.skill_usage as su
- import tools.skills_sync_client as ssc
- from hermes_constants import get_hermes_home
-
- a, b = two_homes
- fired: dict[str, str] = {}
- both = threading.Event()
-
- def fake_push(*, message=""):
- fired[message] = str(get_hermes_home())
- if len(fired) == 2:
- both.set()
-
- monkeypatch.setattr(su, "is_sync_enabled", lambda name: True)
- monkeypatch.setattr(ssc, "maybe_push_skills", fake_push)
- monkeypatch.setattr(smt, "_SYNC_PUSH_DEBOUNCE_S", 0.05)
- monkeypatch.setattr(smt, "_sync_push_timers", {})
- with _scoped(a):
- smt._maybe_debounced_sync_push("skill-a")
- with _scoped(b):
- smt._maybe_debounced_sync_push("skill-b")
- assert both.wait(5), fired
- assert fired == {"sync: skill-a": str(a), "sync: skill-b": str(b)}
-
-
def test_endpoint_model_catalog_memo_is_keyed_by_credential(two_homes, monkeypatch):
"""Two profiles, same base_url, different api_key: a per-key gateway's catalog fetched with A's
key must not be served to B from the in-memory memo (the disk memo already lives per home)."""
diff --git a/tests/tools/test_skills_sync_client.py b/tests/tools/test_skills_sync_client.py
deleted file mode 100644
index 225a6bda3ab..00000000000
--- a/tests/tools/test_skills_sync_client.py
+++ /dev/null
@@ -1,1087 +0,0 @@
-"""Tests for tools/skills_sync_client.py β€” the Skill Sync client.
-
-Covers, against the frozen contract (~/src/specs/collective-wisdom/
-the sync wire contract):
- * content addressing (full 64-hex) + canonical JSON (Β§2.1, Β§2.5)
- * the access gate (Nous admin) making sync inert
- * the M1-D opt-in default (nothing syncs without the sync flag)
- * object building (blob/tree/commit, exec mode, size limit)
- * push (upload + CAS), pull (materialize), and the three-way merge / 409
- conflict paths β€” all against an in-process mock sync server.
-
-The mock server implements the contract Β§3/Β§4 endpoint shapes with an
-in-memory object store + ref table. No live server, no network.
-"""
-
-import hashlib
-import json
-import threading
-from http.server import BaseHTTPRequestHandler, HTTPServer
-from pathlib import Path
-
-import pytest
-
-import tools.skills_sync_client as ssc
-import tools.skills_sync_client_org as org
-import tools.skills_sync_client_wire as wire
-
-
-# ---------------------------------------------------------------------------
-# In-process mock sync server (read + write endpoints)
-# ---------------------------------------------------------------------------
-
-class _MockState:
- def __init__(self):
- self.objects = {} # hash -> (kind, bytes)
- self.refs = {} # name -> commit hash
- self.hsp_version = "1"
- self.max_object_bytes = 26214400
- self.force_conflict_once = False # inject a 409 on the next CAS
- # M2 org behavior (contract Β§11): advertise the "org" feature and,
- # when org_role_admin is False, convert org-HEAD CAS to 202 proposals.
- self.org_feature = True
- self.org_role_admin = True
- self.org_role_present = True
- # Org objects live in a SEPARATE scope from personal ones, mirroring
- # production's `org:<org_id>` scope key. Keeping them in a distinct
- # dict is what makes a personal-route read of org content 404 in tests
- # exactly as it does against the real plane.
- self.org_objects = {}
- self.proposals = [] # [{n, to, base}]
-
-
-def _make_handler(state: _MockState):
- class Handler(BaseHTTPRequestHandler):
- def log_message(self, format, *args): # silence
- pass
-
- def _json(self, code, obj, extra_headers=None):
- body = json.dumps(obj).encode("utf-8")
- self.send_response(code)
- self.send_header("Content-Type", "application/json")
- for k, v in (extra_headers or {}).items():
- self.send_header(k, v)
- self.send_header("Content-Length", str(len(body)))
- self.end_headers()
- self.wfile.write(body)
-
- def do_GET(self):
- path = self.path.split("?", 1)[0]
- query = ""
- if "?" in self.path:
- query = self.path.split("?", 1)[1]
-
- if path == "/v1/sync/capabilities":
- features = ["personal"] + (["org"] if state.org_feature else [])
- return self._json(200, {
- "hsp_version": state.hsp_version,
- "features": features,
- "max_object_bytes": state.max_object_bytes,
- "hash_alg": "sha256",
- "auth": "bearer",
- })
-
- if path == "/v1/sync/refs":
- prefix = ""
- for part in query.split("&"):
- if part.startswith("prefix="):
- from urllib.parse import unquote
- prefix = unquote(part[len("prefix="):])
- # FAITHFUL TO PRODUCTION: the personal refs route is scoped to
- # the caller's own owner and does NOT serve org refs. Asking it
- # for an `refs/org/...` prefix yields the caller's personal
- # refs, not an error β€” the exact trap that let a broken client
- # look healthy against an over-permissive mock.
- refs = [
- {"name": n, "hash": h}
- for n, h in state.refs.items()
- if n.startswith(prefix) and not n.startswith("refs/org/")
- ]
- return self._json(200, {"refs": refs})
-
- if path == "/v1/sync/org/refs":
- if not state.org_feature:
- return self._json(404, {"error": "unknown"})
- if not state.org_role_present:
- return self._json(403, {"error": "org_workflow_unavailable"})
- refs = [
- {"name": n, "hash": h}
- for n, h in state.refs.items()
- if n.startswith("refs/org/")
- ]
- return self._json(200, {"refs": refs})
-
- if path.startswith("/v1/sync/org/objects/"):
- if not state.org_role_present:
- return self._json(403, {"error": "org_workflow_unavailable"})
- obj_hash = path[len("/v1/sync/org/objects/"):]
- if obj_hash not in state.org_objects:
- return self._json(404, {"error": "not_found"})
- return self._send_object(*state.org_objects[obj_hash])
-
- if path.startswith("/v1/sync/objects/"):
- obj_hash = path[len("/v1/sync/objects/"):]
- # Org-scoped objects are NOT readable through the personal
- # route (production scopes it to the token owner).
- if obj_hash not in state.objects:
- return self._json(404, {"error": "not_found"})
- return self._send_object(*state.objects[obj_hash])
-
- self._json(404, {"error": "unknown"})
-
- def _send_object(self, kind, data):
- self.send_response(200)
- self.send_header(
- "Content-Type",
- "application/octet-stream" if kind == ssc.KIND_BLOB else "application/json",
- )
- self.send_header("X-HSP-Object-Type", kind)
- self.send_header("Content-Length", str(len(data)))
- self.end_headers()
- self.wfile.write(data)
- return
-
- def do_POST(self):
- length = int(self.headers.get("Content-Length", 0))
- raw = self.rfile.read(length) if length else b""
- path = self.path.split("?", 1)[0] # e.g. /v1/sync/objects?scope=org
-
- if path == "/v1/sync/objects":
- return self._handle_put_objects(raw, org="scope=org" in self.path)
-
- if path.startswith("/v1/sync/refs/"):
- return self._handle_cas(raw)
-
- self._json(404, {"error": "unknown"})
-
- def _handle_put_objects(self, raw, org=False):
- # multipart/form-data: parse parts (field=hash, filename=type,
- # body=raw bytes). The server recomputes each hash and 422s on
- # mismatch (contract Β§4.2).
- ctype = self.headers.get("Content-Type", "")
- if "multipart/form-data" not in ctype:
- return self._json(400, {"error": "expected multipart"})
- boundary = ctype.split("boundary=", 1)[1].encode("ascii")
- accepted, already = [], []
- parts = raw.split(b"--" + boundary)
- for part in parts:
- # Only trim the delimiter framing: a leading CRLF and a
- # trailing CRLF. Do NOT strip() the whole part -- that would
- # also eat legitimate trailing newlines from the object bytes.
- if part.startswith(b"\r\n"):
- part = part[2:]
- if part.endswith(b"\r\n"):
- part = part[:-2]
- if not part or part == b"--":
- continue
- if b"\r\n\r\n" not in part:
- continue
- headers_blob, body = part.split(b"\r\n\r\n", 1)
- hdr_text = headers_blob.decode("utf-8", "replace")
- claimed_hash = None
- kind = None
- for line in hdr_text.split("\r\n"):
- if line.lower().startswith("content-disposition"):
- for token in line.split(";"):
- token = token.strip()
- if token.startswith('name="'):
- claimed_hash = token[len('name="'):-1]
- elif token.startswith('filename="'):
- kind = token[len('filename="'):-1]
- if claimed_hash is None:
- continue
- real = "sha256:" + hashlib.sha256(body).hexdigest()
- if real != claimed_hash:
- return self._json(422, {
- "error": "hash_mismatch", "claimed": claimed_hash,
- })
- store = state.org_objects if org else state.objects
- if claimed_hash in store:
- already.append(claimed_hash)
- else:
- store[claimed_hash] = (kind, body)
- accepted.append(claimed_hash)
- return self._json(200, {"accepted": accepted, "already_present": already})
-
- def _handle_cas(self, raw):
- from urllib.parse import unquote
- name = unquote(self.path[len("/v1/sync/refs/"):])
- body = json.loads(raw.decode("utf-8")) if raw else {}
- frm = body.get("from")
- to = body.get("to")
- # M2 (contract Β§11.5): a non-admin member's CAS on an org HEAD is
- # accept-always converted to a proposal β†’ 202.
- if name.startswith("refs/org/") and not state.org_role_admin:
- n = len(state.proposals) + 1
- state.proposals.append({"n": n, "to": to, "base": frm})
- org = name.split("/")[2]
- prop_ref = f"refs/org/{org}/proposals/{n}"
- state.refs[prop_ref] = to
- return self._json(202, {"proposal_id": n, "ref": prop_ref})
- if state.force_conflict_once:
- state.force_conflict_once = False
- return self._json(409, {"actual": state.refs.get(name, "")})
- current = state.refs.get(name)
- if current != frm:
- return self._json(409, {"actual": current or ""})
- state.refs[name] = to
- return self._json(200, {"ref": name, "hash": to})
-
- return Handler
-
-
-def mock_server():
- state = _MockState()
- server = HTTPServer(("127.0.0.1", 0), _make_handler(state))
- thread = threading.Thread(target=server.serve_forever, daemon=True)
- thread.start()
- base = f"http://127.0.0.1:{server.server_address[1]}"
- try:
- yield base, state
- finally:
- server.shutdown()
- server.server_close()
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-
-def _write_skill(skills_dir: Path, name: str, body: str = "# skill\n", *, category=None):
- """Create a minimal skill dir under skills_dir; return its path."""
- parent = skills_dir / category if category else skills_dir
- d = parent / name
- d.mkdir(parents=True, exist_ok=True)
- (d / "SKILL.md").write_text(
- f"---\nname: {name}\ndescription: test\n---\n{body}", encoding="utf-8"
- )
- return d
-
-
-def _jwt(claims: dict) -> str:
- import jwt as _pyjwt
- return _pyjwt.encode(claims, "x" * 32, algorithm="HS256")
-
-
-# ---------------------------------------------------------------------------
-# Content addressing & canonicalization (contract Β§2.1, Β§2.5, OI-5)
-# ---------------------------------------------------------------------------
-
-class TestAddressing:
- def test_full_64_hex_address(self):
- addr = wire.wire_address(b"")
- # sha256 of empty is the well-known e3b0... digest, full 64 hex.
- assert addr == (
- "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
- )
- assert len(addr.split(":", 1)[1]) == 64
-
-
- def test_canonical_json_sorted_no_whitespace(self):
- out = wire.canonical_json_bytes({"b": 1, "a": 2})
- assert out == b'{"a":2,"b":1}'
- assert b" " not in out
- assert not out.endswith(b"\n")
-
-
-
-# ---------------------------------------------------------------------------
-# Access gate (Nous admin) + per-skill opt-in
-# ---------------------------------------------------------------------------
-
-class TestDevGate:
- def test_gate_open_with_claim(self, monkeypatch):
- token = _jwt({"sub": "user1", "tool_gateway_admin": True})
- monkeypatch.setattr(
- ssc, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"}, raising=False,
- )
- # patch the lazily-imported symbol used inside resolve_identity
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- ident = ssc.resolve_identity()
- assert ident["nous_admin"] is True
- assert ident["owner"] == "user1"
-
- def test_gate_closed_without_claim(self, monkeypatch):
- token = _jwt({"sub": "user1"}) # no tool_gateway_admin
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- ident = ssc.resolve_identity()
- assert ident["nous_admin"] is False
-
- def test_gate_closed_when_claim_false(self, monkeypatch):
- token = _jwt({"sub": "u", "tool_gateway_admin": False})
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- assert ssc.resolve_identity()["nous_admin"] is False
-
- def test_maybe_push_inert_when_gate_closed(self, monkeypatch):
- token = _jwt({"sub": "u"})
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token})
- monkeypatch.setattr(ssc, "resolve_sync_base_url", lambda: "http://x")
- # gate closed -> None (inert), never attempts a push
- assert ssc.maybe_push_skills() is None
-
- def test_maybe_pull_inert_when_not_logged_in(self, monkeypatch):
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
-
- def _raise(**kw):
- raise RuntimeError("not logged in")
-
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials", _raise)
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials", _raise)
- assert ssc.maybe_pull_skills() is None
-
-
-# ---------------------------------------------------------------------------
-# Object building (contract Β§2.2-Β§2.4)
-# ---------------------------------------------------------------------------
-
-class TestObjectBuilding:
- @pytest.mark.platforms("linux")
- def test_build_tree_blob_and_exec(self, tmp_path):
- d = tmp_path / "skill"
- d.mkdir()
- (d / "SKILL.md").write_text("hello", encoding="utf-8")
- script = d / "run.sh"
- script.write_text("#!/bin/sh\necho hi\n", encoding="utf-8")
- script.chmod(0o755)
-
- objects = ssc.ObjectSet()
- tree_hash = ssc.build_tree(d, objects, max_object_bytes=ssc.DEFAULT_MAX_OBJECT_BYTES)
- assert tree_hash.startswith("sha256:")
- # tree object present and canonical
- kind, data = objects.objects[tree_hash]
- assert kind == wire.KIND_TREE
- tree = json.loads(data)
- entries = {e["name"]: e for e in tree["entries"]}
- assert entries["SKILL.md"]["mode"] == wire.MODE_FILE
- assert entries["run.sh"]["mode"] == wire.MODE_EXEC
- # entries sorted by name (byte order)
- names = [e["name"] for e in tree["entries"]]
- assert names == sorted(names)
-
- def test_build_tree_dedups_identical_blobs(self, tmp_path):
- d = tmp_path / "skill"
- (d / "a").mkdir(parents=True)
- (d / "b").mkdir(parents=True)
- (d / "a" / "f.txt").write_text("same", encoding="utf-8")
- (d / "b" / "f.txt").write_text("same", encoding="utf-8")
- objects = ssc.ObjectSet()
- ssc.build_tree(d, objects, max_object_bytes=ssc.DEFAULT_MAX_OBJECT_BYTES)
- blob_hashes = [h for h, (k, _) in objects.objects.items() if k == ssc.KIND_BLOB]
- # only one unique blob for the identical "same" content
- assert len(set(blob_hashes)) == 1
-
- def test_build_tree_skips_symlink(self, tmp_path):
- d = tmp_path / "skill"
- d.mkdir()
- (d / "real.txt").write_text("x", encoding="utf-8")
- try:
- (d / "link.txt").symlink_to(d / "real.txt")
- except (OSError, NotImplementedError):
- pytest.skip("symlinks unsupported here")
- objects = ssc.ObjectSet()
- tree_hash = ssc.build_tree(d, objects, max_object_bytes=ssc.DEFAULT_MAX_OBJECT_BYTES)
- tree = json.loads(objects.objects[tree_hash][1])
- names = [e["name"] for e in tree["entries"]]
- assert "link.txt" not in names
- assert "real.txt" in names
-
- def test_build_tree_rejects_oversize_blob(self, tmp_path):
- d = tmp_path / "skill"
- d.mkdir()
- (d / "big").write_bytes(b"x" * 100)
- objects = ssc.ObjectSet()
- with pytest.raises(ValueError):
- ssc.build_tree(d, objects, max_object_bytes=10)
-
- def test_build_commit_shape(self):
- objects = ssc.ObjectSet()
- c = ssc.build_commit(
- "sha256:tree", ["sha256:p"], owner="o", device="dev",
- message="m", objects=objects, ts="2026-07-18T00:00:00Z",
- )
- commit = json.loads(objects.objects[c][1])
- assert commit["type"] == "commit"
- assert commit["tree"] == "sha256:tree"
- assert commit["parents"] == ["sha256:p"]
- assert commit["author"] == {"owner": "o", "device": "dev"}
- assert commit["artifact_type"] == "skill"
-
-
-# ---------------------------------------------------------------------------
-# Three-way merge decision (contract Β§4.4, M1-C; mirrors skills_sync.py:619)
-# ---------------------------------------------------------------------------
-
-class TestMergeDecision:
- def test_no_change(self):
- assert ssc.merge_skill("b", "b", "b") == "either"
-
- def test_ours_only_changed(self):
- assert ssc.merge_skill("b", "o", "b") == "ours"
-
- def test_theirs_only_changed(self):
- assert ssc.merge_skill("b", "b", "t") == "theirs"
-
- def test_both_converged(self):
- assert ssc.merge_skill("b", "x", "x") == "either"
-
- def test_true_overlap(self):
- assert ssc.merge_skill("b", "o", "t") == "overlap"
-
- def test_deleted_both(self):
- assert ssc.merge_skill(None, None, None) == "none"
-
-
-# ---------------------------------------------------------------------------
-# End-to-end push / pull / conflict against the mock server
-# ---------------------------------------------------------------------------
-
-def synced_env(tmp_path, monkeypatch):
- """A HERMES_HOME with two opted-in skills + a token-carrying identity."""
- import hermes_constants
- home = tmp_path / "hermes"
- skills = home / "skills"
- skills.mkdir(parents=True)
- monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: home)
- monkeypatch.setattr(ssc, "_skills_dir", lambda: skills)
-
- _write_skill(skills, "alpha", body="alpha v1\n")
- _write_skill(skills, "beta", body="beta v1\n", category="devops")
-
- # Opt both into sync + treat them as eligible (bypass bundled/hub checks).
- monkeypatch.setattr(ssc, "list_synced_skill_names", lambda: ["alpha", "beta"])
-
- def _rel(name):
- from pathlib import PurePosixPath
- return {"alpha": PurePosixPath("alpha"),
- "beta": PurePosixPath("devops/beta")}.get(name)
-
- monkeypatch.setattr(ssc, "_skill_rel_path", _rel)
-
- def _find(name):
- return {"alpha": skills / "alpha",
- "beta": skills / "devops" / "beta"}.get(name)
-
- import tools.skill_usage as su
- monkeypatch.setattr(su, "_find_skill_dir", _find)
-
- token = _jwt({"sub": "owner1", "tool_gateway_admin": True})
- identity = {"api_key": token, "base_url": "http://x", "owner": "owner1",
- "nous_admin": True, "claims": {}}
- return home, skills, identity
-
-
-class TestEndToEnd:
-
- def test_version_mismatch_raises(self, mock_server):
- base, state = mock_server
- state.hsp_version = "2"
- client = ssc.SyncClient(base, "tok")
- with pytest.raises(ssc.SyncError):
- wire._check_version(client.capabilities())
-
- def test_push_uploads_and_cas(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
- result = ssc.push_skills(client, identity=identity)
- assert result["ok"] is True
- # HEAD ref advanced to our commit
- head = state.refs["refs/user/owner1/HEAD"]
- assert head == result["head"]
- # commit object is present and well-formed
- kind, data = state.objects[head]
- assert kind == wire.KIND_COMMIT
- commit = json.loads(data)
- assert commit["author"]["owner"] == "owner1"
- assert commit["parents"] == [] # first commit
-
- def test_push_then_pull_materializes(self, mock_server, synced_env, tmp_path, monkeypatch):
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
- ssc.push_skills(client, identity=identity)
-
- # Simulate a fresh device: new skills dir, same server, same opt-in.
- dev2 = tmp_path / "hermes2" / "skills"
- dev2.mkdir(parents=True)
- monkeypatch.setattr(ssc, "_skills_dir", lambda: dev2)
- monkeypatch.setattr(ssc, "read_sync_state", lambda: {"head": None, "skills": {}})
- saved = {}
- monkeypatch.setattr(ssc, "write_sync_state", lambda d: saved.update(d))
-
- result = ssc.pull_skills(client, identity=identity)
- assert result["ok"] is True
- assert "alpha" in result["updated"]
- assert "devops/beta" in result["updated"]
- # content materialized to disk
- assert (dev2 / "alpha" / "SKILL.md").read_text().endswith("alpha v1\n")
- assert (dev2 / "devops" / "beta" / "SKILL.md").read_text().endswith("beta v1\n")
-
- def test_push_idempotent_reupload(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
- r1 = ssc.push_skills(client, identity=identity)
- n_objects = len(state.objects)
- # push again with no local change -> same head, objects already_present
- r2 = ssc.push_skills(client, identity=identity)
- assert r2["ok"] is True
- assert r2["head"] == r1["head"]
- assert len(state.objects) == n_objects # nothing new stored
-
- def test_conflict_nonoverlap_merges(self, mock_server, synced_env, monkeypatch):
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
- # First push establishes a base head we record locally.
- first = ssc.push_skills(client, identity=identity)
- # Inject a divergent server head: change beta server-side so the next
- # CAS loses. We simulate by forcing one 409 whose actual == current head
- # (the server keeps the same tree, so no overlap on alpha which we edit).
- (skills / "alpha" / "SKILL.md").write_text(
- "---\nname: alpha\ndescription: test\n---\nalpha v2\n", encoding="utf-8"
- )
- state.force_conflict_once = True
- result = ssc.push_skills(client, identity=identity)
- # actual == our own head -> both-sides identical -> merge commit succeeds
- assert result.get("ok") is True
- assert result.get("merged") is True
-
- def test_conflict_true_overlap_writes_conflict_ref(self, mock_server, synced_env, monkeypatch):
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
- ssc.push_skills(client, identity=identity)
-
- # Build a DIFFERENT server-side head for the SAME skill (alpha) so the
- # three-way merge sees a true overlap. We construct it via a second
- # snapshot after editing alpha differently, push it directly, then make
- # our local head stale and edit alpha a third way.
- (skills / "alpha" / "SKILL.md").write_text(
- "---\nname: alpha\ndescription: test\n---\nSERVER edit\n", encoding="utf-8"
- )
- objs, root, _ = ssc.snapshot_profile(["alpha", "beta"])
- their_commit = ssc.build_commit(
- root, [], owner="owner1", device="other", message="theirs", objects=objs
- )
- client.put_objects(objs.objects)
- state.refs["refs/user/owner1/HEAD"] = their_commit
-
- # Our local edit to the same skill, from the OLD base -> true overlap.
- (skills / "alpha" / "SKILL.md").write_text(
- "---\nname: alpha\ndescription: test\n---\nLOCAL edit\n", encoding="utf-8"
- )
- result = ssc.push_skills(client, identity=identity)
- assert result.get("conflict") is True
- assert result["conflict_ref"].startswith("refs/user/owner1/conflict/")
- assert "alpha" in result["overlapping_skills"]
- # a conflict ref head was written server-side
- assert result["conflict_ref"] in state.refs
-
-
-# ---------------------------------------------------------------------------
-# M1-D opt-in sidecar flag (tools/skill_usage.set_sync / is_sync_enabled)
-# ---------------------------------------------------------------------------
-
-class TestOptInFlag:
- def test_set_and_read_sync_flag(self, tmp_path, monkeypatch):
- import tools.skill_usage as su
- monkeypatch.setattr(su, "_skills_dir", lambda: tmp_path)
- # Make the skill curation-eligible so the gated mutator writes.
- monkeypatch.setattr(su, "is_curation_eligible", lambda name, *a, **k: True)
-
- assert su.is_sync_enabled("foo") is False
- su.set_sync("foo", True)
- assert su.is_sync_enabled("foo") is True
- su.set_sync("foo", False)
- assert su.is_sync_enabled("foo") is False
-
- def test_sync_flag_ignored_for_ineligible(self, tmp_path, monkeypatch):
- import tools.skill_usage as su
- monkeypatch.setattr(su, "_skills_dir", lambda: tmp_path)
- # Bundled/hub/external skills are not curation-eligible -> mutator no-ops.
- monkeypatch.setattr(su, "is_curation_eligible", lambda name, *a, **k: False)
- su.set_sync("bundled-skill", True)
- assert su.is_sync_enabled("bundled-skill") is False
-
-
-# ---------------------------------------------------------------------------
-# Β§2.8 sync-manifest β€” opt-in as content in the sync plane (cross-device)
-# ---------------------------------------------------------------------------
-
-class TestSyncManifest:
- def test_build_parse_roundtrip(self):
- data = ssc.build_sync_manifest_bytes({"beta": True, "alpha": False})
- parsed = wire.parse_sync_manifest(data)
- assert parsed == {"alpha": False, "beta": True}
-
- def test_manifest_wire_shape(self):
- # Must match gateway-gateway src/sync/manifest.ts: type + version:1 +
- # skills:[{name,enabled}]. Skills sorted by name for a stable address.
- import json
- data = ssc.build_sync_manifest_bytes({"z": True, "a": True})
- obj = json.loads(data.decode("utf-8"))
- assert obj["type"] == "sync-manifest"
- assert obj["version"] == 1
- assert obj["skills"] == [
- {"name": "a", "enabled": True},
- {"name": "z", "enabled": True},
- ]
-
- def test_parse_rejects_malformed(self):
- # Strict: unknown type, bad version, non-array skills, malformed entry.
- assert wire.parse_sync_manifest(b"not json") is None
- assert wire.parse_sync_manifest(b'{"type":"nope","version":1,"skills":[]}') is None
- assert wire.parse_sync_manifest(b'{"type":"sync-manifest","version":2,"skills":[]}') is None
- assert wire.parse_sync_manifest(b'{"type":"sync-manifest","version":1,"skills":{}}') is None
- assert (
- wire.parse_sync_manifest(
- b'{"type":"sync-manifest","version":1,"skills":[{"name":"x"}]}'
- )
- is None
- )
- # A malformed manifest must NOT be mistaken for "no skills opted in".
- assert wire.parse_sync_manifest(b'{"type":"sync-manifest","version":1,"skills":[]}') == {}
-
- def test_snapshot_embeds_manifest_root_blob(self, mock_server, synced_env):
- # snapshot_profile must add a root-level `sync-manifest` blob recording
- # the opted-in set, alongside the skill subtrees, so opt-in is durable
- # plane content. Read it back via read_manifest_of_root.
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
-
- objs, root_hash, skill_map = ssc.snapshot_profile(["alpha", "beta"])
- client.put_objects(objs.objects)
-
- manifest = ssc.read_manifest_of_root(client, root_hash)
- assert manifest == {"alpha": True, "beta": True}
-
- # The manifest is a root-level BLOB, not a skill subtree, so the skill
- # walk must not surface it as a skill.
- trees = ssc.skill_trees_of_root(client, root_hash)
- assert "sync-manifest" not in trees
- assert set(trees) == {"alpha", "devops/beta"}
-
- def test_pull_adopts_opt_in_from_manifest(self, mock_server, synced_env, monkeypatch):
- # A skill opted in on device A (present + enabled in the plane manifest)
- # becomes opted in locally on pull, even if this device had it disabled.
- base, state = mock_server
- home, skills, identity = synced_env
- client = ssc.SyncClient(base, identity["api_key"])
-
- # Device A pushes alpha+beta (manifest enables both).
- ssc.push_skills(client, identity=identity)
-
- # Simulate device B: local opt-in intent is EMPTY, but eligibility passes.
- adopted = {}
- import tools.skill_usage as su
- monkeypatch.setattr(su, "is_curation_eligible", lambda name, *a, **k: True)
- monkeypatch.setattr(su, "is_sync_enabled", lambda name: False)
- monkeypatch.setattr(su, "set_sync", lambda name, val: adopted.__setitem__(name, val))
- # Local head unknown so the pull actually runs.
- monkeypatch.setattr(ssc, "read_sync_state", lambda: {"head": None, "skills": {}})
- monkeypatch.setattr(ssc, "write_sync_state", lambda d: None)
- # No local opt-in gate (so materialize isn't the thing under test).
- monkeypatch.setattr(ssc, "_opted_in_rel_paths", lambda: [])
-
- result = ssc.pull_skills(client, identity=identity)
- assert result["ok"] is True
- # Both skills from the plane manifest were adopted into local opt-in.
- assert adopted == {"alpha": True, "beta": True}
- assert set(result["opt_in_adopted"]) == {"alpha", "beta"}
-
-
-# ---------------------------------------------------------------------------
-# Env-var configuration (Hermes Cloud "on by default" via environment)
-# ---------------------------------------------------------------------------
-
-class TestEnvConfig:
- def test_base_url_env_wins(self, monkeypatch):
- monkeypatch.setenv("HERMES_SYNC_BASE_URL", "https://plane.example/")
- assert ssc.resolve_sync_base_url() == "https://plane.example"
-
- def test_base_url_defaults_to_production(self, monkeypatch):
- # With nothing configured a user must still reach the real plane β€”
- # otherwise every sync command fails with "no base URL configured".
- monkeypatch.delenv("HERMES_SYNC_BASE_URL", raising=False)
- monkeypatch.setattr("hermes_cli.config.load_config", lambda: {}, raising=False)
- assert ssc.resolve_sync_base_url() == ssc.DEFAULT_SYNC_BASE_URL
-
- def test_default_is_a_bare_https_origin(self):
- # The client appends /v1/sync/, so the default must be a scheme+host
- # origin with no trailing slash and no path.
- from urllib.parse import urlparse
-
- parsed = urlparse(ssc.DEFAULT_SYNC_BASE_URL)
- assert parsed.scheme == "https"
- assert parsed.netloc
- assert parsed.path == ""
- assert not ssc.DEFAULT_SYNC_BASE_URL.endswith("/")
-
- def test_config_overrides_default(self, monkeypatch):
- monkeypatch.delenv("HERMES_SYNC_BASE_URL", raising=False)
- monkeypatch.setattr(
- "hermes_cli.config.load_config",
- lambda: {"sync": {"base_url": "https://cfg.example/"}},
- raising=False,
- )
- assert ssc.resolve_sync_base_url() == "https://cfg.example"
-
- def test_feature_enabled_env(self, monkeypatch):
- # Default off.
- monkeypatch.delenv("HERMES_SYNC_ENABLED", raising=False)
- monkeypatch.setattr("hermes_cli.config.load_config", lambda: {}, raising=False)
- assert ssc.sync_feature_enabled() is False
- for truthy in ("1", "true", "YES", "on"):
- monkeypatch.setenv("HERMES_SYNC_ENABLED", truthy)
- assert ssc.sync_feature_enabled() is True
- for falsy in ("0", "false", "off"):
- monkeypatch.setenv("HERMES_SYNC_ENABLED", falsy)
- assert ssc.sync_feature_enabled() is False
-
- def test_default_opt_in_env(self, monkeypatch):
- monkeypatch.delenv("HERMES_SYNC_DEFAULT_OPT_IN", raising=False)
- monkeypatch.setattr("hermes_cli.config.load_config", lambda: {}, raising=False)
- assert ssc.sync_default_opt_in() is False
- monkeypatch.setenv("HERMES_SYNC_DEFAULT_OPT_IN", "true")
- assert ssc.sync_default_opt_in() is True
-
- def test_config_yaml_fallback_when_no_env(self, monkeypatch):
- monkeypatch.delenv("HERMES_SYNC_ENABLED", raising=False)
- monkeypatch.setattr(
- "hermes_cli.config.load_config",
- lambda: {"sync": {"enabled": True}},
- raising=False,
- )
- assert ssc.sync_feature_enabled() is True
-
- def test_env_overrides_config_yaml(self, monkeypatch):
- # Env wins over config.yaml (operator override precedence).
- monkeypatch.setenv("HERMES_SYNC_ENABLED", "false")
- monkeypatch.setattr(
- "hermes_cli.config.load_config",
- lambda: {"sync": {"enabled": True}},
- raising=False,
- )
- assert ssc.sync_feature_enabled() is False
-
- def test_opt_out_policy_syncs_all_eligible(self, monkeypatch):
- # With opt-out on, every eligible skill syncs even with no `sync:true`
- # flag; an explicit `sync:false` still excludes.
- monkeypatch.setattr(ssc, "sync_default_opt_in", lambda: True)
- monkeypatch.setattr(ssc, "_all_local_skill_names", lambda: ["alpha", "beta", "gamma"])
- monkeypatch.setattr(ssc, "is_sync_eligible", lambda n: n in {"alpha", "beta", "gamma"})
- import tools.skill_usage as su
- # gamma explicitly opted out; alpha/beta have no flag.
- monkeypatch.setattr(su, "load_usage", lambda: {"gamma": {"sync": False}})
- assert ssc.list_synced_skill_names() == ["alpha", "beta"]
-
- def test_opt_in_policy_requires_flag(self, monkeypatch):
- # With opt-out OFF (default opt-in), only explicitly-enabled skills sync.
- monkeypatch.setattr(ssc, "sync_default_opt_in", lambda: False)
- monkeypatch.setattr(ssc, "is_sync_eligible", lambda n: True)
- import tools.skill_usage as su
- monkeypatch.setattr(
- su, "load_usage",
- lambda: {"alpha": {"sync": True}, "beta": {}, "gamma": {"sync": False}},
- )
- assert ssc.list_synced_skill_names() == ["alpha"]
-
-
-class TestDeviceName:
- def test_default_is_hostname_seeded(self, tmp_path, monkeypatch):
- monkeypatch.setattr(ssc, "_skills_dir", lambda: tmp_path)
- monkeypatch.delenv("HERMES_SYNC_DEVICE_NAME", raising=False)
- monkeypatch.setattr(
- "socket.gethostname", lambda: "bens-macbook.local", raising=False
- )
- val = ssc.stable_device_id()
- # short hostname + short suffix, NOT a bare 32-char hash
- assert val.startswith("bens-macbook-")
- assert val != "bens-macbook-"
- # persisted + stable across calls
- assert (tmp_path / ".sync_device_id").read_text() == val
- assert ssc.stable_device_id() == val
-
- def test_existing_file_wins_over_default_and_env(self, tmp_path, monkeypatch):
- monkeypatch.setattr(ssc, "_skills_dir", lambda: tmp_path)
- (tmp_path / ".sync_device_id").write_text("Explicit Name", encoding="utf-8")
- monkeypatch.setenv("HERMES_SYNC_DEVICE_NAME", "cloud-seed")
- assert ssc.stable_device_id() == "Explicit Name"
-
- def test_env_seeds_first_use(self, tmp_path, monkeypatch):
- # Hermes Cloud path: HERMES_SYNC_DEVICE_NAME seeds the first-use label.
- monkeypatch.setattr(ssc, "_skills_dir", lambda: tmp_path)
- monkeypatch.setenv("HERMES_SYNC_DEVICE_NAME", "hermes-cloud-ben-1")
- assert ssc.stable_device_id() == "hermes-cloud-ben-1"
- # persisted so it stays stable even if the env later changes
- assert (tmp_path / ".sync_device_id").read_text() == "hermes-cloud-ben-1"
- monkeypatch.setenv("HERMES_SYNC_DEVICE_NAME", "changed")
- assert ssc.stable_device_id() == "hermes-cloud-ben-1"
-
- def test_set_device_name_overwrites(self, tmp_path, monkeypatch):
- monkeypatch.setattr(ssc, "_skills_dir", lambda: tmp_path)
- (tmp_path / ".sync_device_id").write_text("old", encoding="utf-8")
- stored = ssc.set_device_name(" Ben's Laptop ")
- assert stored == "Ben's Laptop" # trimmed
- assert ssc.stable_device_id() == "Ben's Laptop"
-
- def test_set_device_name_rejects_empty(self, tmp_path, monkeypatch):
- monkeypatch.setattr(ssc, "_skills_dir", lambda: tmp_path)
- import pytest
-
- with pytest.raises(ValueError):
- ssc.set_device_name(" ")
-
-
-# ---------------------------------------------------------------------------
-# M2 org-shared skills (contract Β§11): identity gate, pull, propose (202/merge)
-# ---------------------------------------------------------------------------
-
-def _org_identity(role=None, org_id="org-1", owner="owner1"):
- claims = {"sub": owner, "org_id": org_id, "tool_gateway_admin": True}
- if role is not None:
- claims["org_role"] = role
- token = _jwt(claims)
- return {"api_key": token, "base_url": "http://x", "owner": owner,
- "nous_admin": True, "claims": claims,
- **({"org_id": org_id, "org_role": role} if role else {})}
-
-
-class TestOrgIdentityGate:
- def test_org_identity_requires_role_claim(self, monkeypatch):
- # Personal org: NAS stamps NO org_role -> inert, not an error path.
- token = _jwt({"sub": "u", "org_id": "org-1"})
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- with pytest.raises(ssc.SyncInertError):
- ssc.resolve_org_identity()
-
- def test_org_identity_with_role(self, monkeypatch):
- token = _jwt({"sub": "u", "org_id": "org-9", "org_role": "MEMBER"})
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token, "base_url": "https://x"})
- ident = ssc.resolve_org_identity()
- assert ident["org_id"] == "org-9"
- assert ident["org_role"] == "MEMBER"
-
- def test_org_mirror_excluded_from_personal_sync(self, tmp_path, monkeypatch):
- # A skill under _org/<id>/ must never be personal-sync eligible.
- skills = tmp_path / "skills"
- org_skill = skills / "_org" / "org-1" / "shared-x"
- org_skill.mkdir(parents=True)
- (org_skill / "SKILL.md").write_text("---\nname: shared-x\n---\n")
- monkeypatch.setattr(ssc, "_skills_dir", lambda: skills)
- import tools.skill_usage as su
- monkeypatch.setattr(su, "is_bundled", lambda n: False)
- monkeypatch.setattr(su, "is_hub_installed", lambda n: False)
- monkeypatch.setattr(su, "_find_skill_dir", lambda n: org_skill)
- import agent.skill_utils as sku
- monkeypatch.setattr(sku, "is_external_skill_path", lambda p: False)
- assert ssc.is_sync_eligible("shared-x") is False
-
-
-class TestOrgEndToEnd:
- def test_admin_propose_merges_directly(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- identity = {**identity, "org_id": "org-1", "org_role": "ADMIN"}
- client = ssc.SyncClient(base, identity["api_key"])
- result = org.propose_skill("alpha", client, identity=identity)
- assert result["ok"] is True
- assert result.get("merged") is True
- head = state.refs["refs/org/org-1/HEAD"]
- assert head == result["head"]
- # Org content lands in the ORG object scope, not the personal one.
- assert head not in state.objects, "org commit must not be personal-scoped"
- commit = json.loads(state.org_objects[head][1])
- assert commit["parents"] == [] # first org commit
-
- def test_member_propose_becomes_202_proposal(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- # Seed an org HEAD as admin first.
- admin_ident = {**identity, "org_id": "org-1", "org_role": "ADMIN"}
- client = ssc.SyncClient(base, identity["api_key"])
- seeded = org.propose_skill("alpha", client, identity=admin_ident)
-
- # Member edits beta and proposes: server converts to 202.
- state.org_role_admin = False
- (skills / "devops" / "beta" / "SKILL.md").write_text(
- "---\nname: beta\n---\nbeta v2 member edit\n", encoding="utf-8"
- )
- member_ident = {**identity, "org_id": "org-1", "org_role": "MEMBER"}
- result = org.propose_skill("beta", client, identity=member_ident)
- assert result["ok"] is True
- assert result.get("proposal_pending") is True
- assert result["proposal_id"] == 1
- # HEAD untouched; proposal ref parked at the member's commit.
- assert state.refs["refs/org/org-1/HEAD"] == seeded["head"]
- assert state.refs["refs/org/org-1/proposals/1"] == result["commit"]
- # NEVER reported as merged.
- assert "merged" not in result
-
- def test_member_proposal_splices_not_replaces(self, mock_server, synced_env):
- # The proposed root must keep the OTHER skills from HEAD (per-skill
- # delta, not a wholesale replace).
- base, state = mock_server
- home, skills, identity = synced_env
- admin_ident = {**identity, "org_id": "org-1", "org_role": "ADMIN"}
- client = ssc.SyncClient(base, identity["api_key"])
- org.propose_skill("alpha", client, identity=admin_ident)
- org.propose_skill("beta", client, identity=admin_ident)
-
- state.org_role_admin = False
- member_ident = {**identity, "org_id": "org-1", "org_role": "MEMBER"}
- result = org.propose_skill("alpha", client, identity=member_ident)
- # Walk the proposed commit's root: both skills present.
- commit = json.loads(state.org_objects[result["commit"]][1])
- root = json.loads(state.org_objects[commit["tree"]][1])
- names = {e["name"] for e in root["entries"]}
- assert "alpha" in names and "devops" in names
-
- def test_pull_org_skills_materializes_mirror(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- admin_ident = {**identity, "org_id": "org-1", "org_role": "ADMIN"}
- client = ssc.SyncClient(base, identity["api_key"])
- org.propose_skill("alpha", client, identity=admin_ident)
-
- result = org.pull_org_skills(client, identity=admin_ident)
- assert result["ok"] is True
- assert "alpha" in result["updated"]
- mirrored = skills / "_org" / "org-1" / "alpha" / "SKILL.md"
- assert mirrored.exists()
- assert mirrored.read_text().endswith("alpha v1\n")
-
- def test_pull_org_noop_when_no_head(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- ident = {**identity, "org_id": "org-1", "org_role": "MEMBER"}
- client = ssc.SyncClient(base, identity["api_key"])
- result = org.pull_org_skills(client, identity=ident)
- assert result["ok"] is True
- assert result["head"] is None
- assert result["updated"] == []
-
- def test_propose_requires_org_feature(self, mock_server, synced_env):
- base, state = mock_server
- home, skills, identity = synced_env
- state.org_feature = False
- ident = {**identity, "org_id": "org-1", "org_role": "ADMIN"}
- client = ssc.SyncClient(base, identity["api_key"])
- with pytest.raises(ssc.SyncInertError):
- org.propose_skill("alpha", client, identity=ident)
-
- def test_maybe_pull_org_inert_without_role(self, monkeypatch):
- # Personal org: no org_role claim -> None, never raises.
- token = _jwt({"sub": "u", "org_id": "org-1"})
- import hermes_cli.auth as auth_mod
- import hermes_cli.auth_nous as auth_nous
- monkeypatch.setattr(auth_mod, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token})
- monkeypatch.setattr(auth_nous, "resolve_nous_runtime_credentials",
- lambda **kw: {"api_key": token})
- assert org.maybe_pull_org_skills() is None
-
-
-class TestOrgEndpointScoping:
- """Org reads must use the ORG endpoints, not the personal ones.
-
- The personal refs route is scoped to the caller's own owner: asked for an
- ``refs/org/...`` prefix it returns the caller's PERSONAL refs rather than
- erroring. A client reading org state through it therefore concludes "this
- org has no content" and every subsequent CAS races a head it never saw β€”
- which is exactly how a second propose used to die on a raw SyncConflict.
- """
-
- def _admin(self, identity):
- return {**identity, "org_id": "org-1", "org_role": "ADMIN"}
-
-
- def test_second_propose_splices_onto_the_existing_org_head(
- self, mock_server, synced_env
- ):
- """The regression: propose #1 works, propose #2 used to raise."""
- base, state = mock_server
- home, skills, identity = synced_env
- admin = self._admin(identity)
- client = ssc.SyncClient(base, identity["api_key"])
-
- # `synced_env` already seeds alpha and beta (beta under devops/).
- first = org.propose_skill("alpha", client, identity=admin)
- assert first["ok"] is True
-
- # Previously: base_head read as None -> CAS from None -> 409 ->
- # SyncConflict escaped to the caller.
- second = org.propose_skill("beta", client, identity=admin)
- assert second["ok"] is True
-
- # And the splice preserved the first skill rather than replacing it.
- head = state.refs["refs/org/org-1/HEAD"]
- commit = json.loads(state.org_objects[head][1])
- root = json.loads(state.org_objects[commit["tree"]][1])
- names = {e["name"] for e in root["entries"]}
- # beta is seeded under the devops/ category, so it appears as that
- # category tree at the root.
- assert "alpha" in names and "devops" in names
- assert commit["parents"], "second commit must descend from the first"
-
-
-
-class TestEmptyActualConflict:
- """A 409 with an empty ``actual`` means the ref does not exist."""
-
-
- def test_push_recovers_from_a_stale_local_head(self, mock_server, synced_env):
- """Switching sync planes leaves a foreign head in local state.
-
- The CAS then fails against a ref that does not exist, and the server
- answers 409 with an empty ``actual``. The client must redo the CAS as
- a create rather than trying to fetch "" as a commit (which surfaced as
- the bizarre `object not found`, with a doubled space).
- """
- base, state = mock_server
- home, skills, identity = synced_env
- st = ssc.read_sync_state()
- st["head"] = "sha256:" + "f" * 64 # head from another plane
- ssc.write_sync_state(st)
-
- client = ssc.SyncClient(base, identity["api_key"])
- result = ssc.push_skills(client=client, identity=identity)
- assert result["ok"] is True
- assert result.get("recovered_stale_head") is True
- assert state.refs[ssc.user_head_ref(identity["owner"])] == result["head"]
diff --git a/tools/skill_manager_batch.py b/tools/skill_manager_batch.py
index fab23c532b9..d312994cd32 100644
--- a/tools/skill_manager_batch.py
+++ b/tools/skill_manager_batch.py
@@ -213,7 +213,7 @@ def _rollback(snapshots, find_skill, results):
return ("; ".join(notes) if notes else "all touched skills rolled back"), bool(notes)
-_ADVISORY_KEYS = ("lint_warnings", "lint_hint", "org_sharing")
+_ADVISORY_KEYS = ("lint_warnings", "lint_hint")
def _skill_manage_batch(operations, default_name: str = None, task_id: str = None,
diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.py
index 06df3cd6955..e8240f88d5c 100644
--- a/tools/skill_manager_guards.py
+++ b/tools/skill_manager_guards.py
@@ -259,54 +259,3 @@ def _curator_consolidation_delete_guard(
f"forwarding target is not permitted here β€” the deterministic inactivity prune handles "
f"staleness archival separately. Keeping '{name}' active.",
_fail_closed=True)
-
-
-def _is_org_mirror(skill_path: Path) -> bool:
- from agent.skill_utils import is_org_mirror_path
- from tools import skill_manager_tool as _smt
- return is_org_mirror_path(skill_path, _smt._skills_dir())
-
-
-def _maybe_auto_propose_org_edit(name: str, skill_path: Path) -> Optional[str]:
- """Submit an org-skill edit upstream when `sync.org_auto_propose` is on. Returns a note for
- the tool result or None; never raises (the edit is saved locally and can be proposed later)."""
- try:
- from tools import skills_sync_client as ssc
- if not _is_org_mirror(skill_path):
- return None
- if not ssc.sync_org_auto_propose():
- return (
- f"This skill is shared by your organisation. Your edit is "
- f"saved locally and will not be overwritten by org updates. "
- f"Run `hermes sync propose {name}` to share it back.")
- from tools.skills_sync_client_org import propose_skill
- result = propose_skill(name)
- if result.get("proposal_pending"):
- return (
- f"Auto-proposed to your organisation as proposal "
- f"#{result.get('proposal_id')} (pending admin review).")
- return "Auto-proposed to your organisation (merged into the shared set)."
- except Exception as e:
- logger.debug("auto-propose skipped for %s: %s", name, e)
- return (
- f"Edit saved locally. Could not submit it to your organisation "
- f"right now β€” run `hermes sync propose {name}` to retry.")
-
-
-def _org_mirror_write_guard(name: str, skill_path: Path, action: str) -> Optional[Dict[str, Any]]:
- """Org-shared skills are EDITABLE IN PLACE β€” this only blocks deletion. Edits land in the
- mirror, survive the next org pull (baseline sidecar in skills_sync_client) and reach the org
- via `hermes sync propose`. Deletion stays refused: the mirror is a view of org HEAD, so a
- local delete just comes back, and removing for everyone is an admin action."""
- if action not in {"delete", "remove_file"}:
- return None
- try:
- if _is_org_mirror(skill_path):
- return _refusal(
- f"Cannot {action} '{name}' locally: it is shared by your organisation, so a local "
- f"delete would just come back on the next sync. Ask an org admin to remove it for "
- f"everyone. (Editing it IS allowed β€” your changes are kept and can be proposed "
- f"back with `hermes sync propose {name}`.)")
- except Exception:
- logger.debug("org mirror guard lookup failed for %s", name, exc_info=True)
- return None
diff --git a/tools/skill_manager_tool.py b/tools/skill_manager_tool.py
index ce8cb5dab94..1dc0f1db4ff 100644
--- a/tools/skill_manager_tool.py
+++ b/tools/skill_manager_tool.py
@@ -14,7 +14,6 @@ from contextlib import ExitStack, suppress
import logging
import re
import shutil
-import threading
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
@@ -30,8 +29,8 @@ from agent.skill_utils import (
SKILL_PROMPT_DESC_LIMIT)
from tools.skill_manager_guards import (
_background_review_preflight, _background_review_read_before_write_guard, _background_review_write_guard,
- _containing_skills_root, _curator_consolidation_delete_guard, _is_path_redirect, _maybe_auto_propose_org_edit,
- _org_mirror_write_guard, _pinned_guard, _validate_delete_target, _is_background_review, _refusal as _err)
+ _containing_skills_root, _curator_consolidation_delete_guard, _is_path_redirect, _pinned_guard,
+ _validate_delete_target, _is_background_review, _refusal as _err)
from tools.skill_manager_batch import (
_PATCH_EITHER_OR, _PATCH_NEEDS_NEW_STRING, _PATCH_NEEDS_OLD_STRING, _op_shape_error, _skill_manage_batch)
from tools.skills_guard import scan_skill, should_allow_install, format_scan_report
@@ -334,16 +333,13 @@ def _resolve_supporting_file(skill_dir: Path, file_path: str):
return (None, _err(err)) if err else (target, None)
-def _locate_for_write(name: str, action: str, not_found_suffix: str = "", *,
- org_guard: bool = True):
- """Find the skill; run the org-mirror (unless ``org_guard=False``) and background-review
- write guards -> ``(skill_dir, None)`` | ``(None, error_dict)``."""
+def _locate_for_write(name: str, action: str, not_found_suffix: str = ""):
+ """Find the skill; run the background-review write guard -> ``(skill_dir, None)`` | ``(None, error_dict)``."""
existing = _find_skill(name)
if not existing:
return None, _err(_skill_not_found_error(name, not_found_suffix))
skill_dir = existing["path"]
- guard = ((org_guard and _org_mirror_write_guard(name, skill_dir, action))
- or _background_review_write_guard(name, skill_dir, action))
+ guard = _background_review_write_guard(name, skill_dir, action)
return (None, guard) if guard else (skill_dir, None)
@@ -369,13 +365,6 @@ def _guarded_write(name: str, skill_dir: Path, target: Path, action: str, label:
return _err(scan_error)
-def _attach_org_note(result: Dict[str, Any], name: str, skill_dir: Path) -> Dict[str, Any]:
- if org_note := _maybe_auto_propose_org_edit(name, skill_dir):
- result["org_sharing"] = org_note
- result["message"] = f"{result['message']} {org_note}"
- return result
-
-
def _add_description_prompt_preview(result: Dict[str, Any], content: str) -> Dict[str, Any]:
fm, _ = _parse_frontmatter(content)
if is_skill_description_truncated_for_prompt(fm):
@@ -464,7 +453,7 @@ def _edit_skill(name: str, content: str) -> Dict[str, Any]:
result = {
"success": True, "message": f"Skill '{name}' updated (full rewrite).",
"path": str(skill_dir), "_change": {"description": _description_preview(content)}}
- return _add_description_prompt_preview(_attach_org_note(result, name, skill_dir), content)
+ return _add_description_prompt_preview(result, content)
def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = None,
@@ -511,7 +500,6 @@ def _patch_skill(name: str, old_string: str, new_string: str, file_path: str = N
"success": True,
"message": f"Patched {target_label} in skill '{name}' ({match_count} replacement{'s' if match_count > 1 else ''}).",
"_change": {"old": _clip(old_string, 200, "…"), "new": _clip(new_string, 200, "…")}}
- result = _attach_org_note(result, name, skill_dir)
# SKILL.md grows by patches, not by creates: surface findings on the patch that crosses a line
# (oversized-body, incident-log-shape) β€” a clean patch attaches nothing and stays quiet.
if not file_path:
@@ -578,8 +566,7 @@ def _write_file(name: str, file_path: str, file_content: str) -> Dict[str, Any]:
target, err = _resolve_supporting_file(skill_dir, file_path)
if guard := err or _guarded_write(name, skill_dir, target, "write_file", file_path, file_content):
return guard
- result = _attach_org_note({"success": True, "message": f"File '{file_path}' written to skill '{name}'.",
- "path": str(target)}, name, skill_dir)
+ result = {"success": True, "message": f"File '{file_path}' written to skill '{name}'.", "path": str(target)}
# references/ is where per-session hoarding shows up; surface the sprawl finding on the write
# that crosses the line so the review fork sees it in the same turn.
if file_path.startswith("references/") and (skill_dir / "SKILL.md").exists():
@@ -591,7 +578,7 @@ def _remove_file(name: str, file_path: str) -> Dict[str, Any]:
"""Remove a supporting file from any skill directory."""
if err := _validate_file_path(file_path):
return _err(err)
- skill_dir, guard = _locate_for_write(name, "remove_file", org_guard=False)
+ skill_dir, guard = _locate_for_write(name, "remove_file")
if guard:
return guard
target, err = _resolve_supporting_file(skill_dir, file_path)
@@ -668,41 +655,6 @@ def apply_skill_pending(payload: Dict[str, Any]) -> str:
_skill_gate_bypass.reset(token)
-# Sync push debounce: a burst of skill_manage writes collapses into one push on a daemon timer.
-# One timer per profile home: in a multiplexed process B's write must not cancel A's pending push.
-_sync_push_timers: Dict[str, threading.Timer] = {}
-_sync_push_lock = threading.Lock()
-_SYNC_PUSH_DEBOUNCE_S = 5.0
-
-
-def _maybe_debounced_sync_push(skill_name: str) -> None:
- """Debounced best-effort sync push after a skill write; never blocks the caller. Skills not
- opted into sync do nothing (no auth/network); ``maybe_push_skills`` enforces the access gate."""
- try:
- from tools.skill_usage import is_sync_enabled
- if not is_sync_enabled(skill_name):
- return
- except Exception:
- return
- from hermes_constants import hermes_home_key
- home_key = hermes_home_key()
- # Timer threads start with empty ContextVars; without the scheduling turn's context the push would
- # resolve the launch profile's home and credentials instead of the writing profile's.
- ctx = _ctxvars.copy_context()
- def _fire():
- with suppress(Exception):
- from tools.skills_sync_client import maybe_push_skills
- maybe_push_skills(message=f"sync: {skill_name}")
- with _sync_push_lock:
- pending = _sync_push_timers.get(home_key)
- if pending is not None:
- pending.cancel() # only sets an Event; never raises
- timer = threading.Timer(_SYNC_PUSH_DEBOUNCE_S, ctx.run, args=(_fire,))
- timer.daemon = True
- _sync_push_timers[home_key] = timer
- timer.start()
-
-
def _act_patch(a):
"""Two shapes: old_string/new_string = targeted replacement (validated in _patch_skill so the
tool and the helper give the same guidance); content alone = full rewrite (the old 'edit')."""
@@ -727,7 +679,7 @@ _ACTION_HANDLERS = {
def _record_success(action, name, result, *, file_path, absorbed_into, task_id,
session_id, ledger_before) -> None:
"""Best-effort post-mutation side effects (never break the tool): ledger, prompt-cache
- clear, curator telemetry, debounced sync push."""
+ clear, curator telemetry (which fires ``on_skill_lifecycle`` for plugins)."""
with suppress(Exception):
from tools import skill_ledger as _ledger
_post = _find_skill(name)
@@ -759,9 +711,6 @@ def _record_success(action, name, result, *, file_path, absorbed_into, task_id,
bump_patch(name, action=action, task_id=task_id, session_id=session_id)
elif action == "delete" and not result.get("_archived"):
forget(name)
- # Only AFTER the write gate passed (staged writes returned early): never push un-reviewed content.
- with suppress(Exception):
- _maybe_debounced_sync_push(name)
def skill_manage(
diff --git a/tools/skill_usage.py b/tools/skill_usage.py
index ee202c35a89..f5ce2379451 100644
--- a/tools/skill_usage.py
+++ b/tools/skill_usage.py
@@ -277,7 +277,7 @@ def _external_read_only_message(skill_name: str) -> str:
def is_curation_eligible(skill_name: str, skill_path: Optional[Path] = None) -> bool:
"""Agent-created: yes. Bundled: only with ``curator.prune_builtins``. Hub / external-dir / protected built-ins:
- never (external owner). Org-shared skills are eligible here but protected from ARCHIVE/DELETE elsewhere."""
+ never (external owner)."""
if ((skill_path is not None and is_external_skill_path(skill_path)) or is_protected_builtin(skill_name)
or is_hub_installed(skill_name)):
return False
@@ -577,15 +577,6 @@ def set_pinned(skill_name: str, pinned: bool) -> bool:
return _set_field(skill_name, "pinned", bool(pinned))
-def set_sync(skill_name: str, sync: bool) -> None:
- """Opt-in ``sync`` flag (read by ``skills_sync_client``); curation-gated so bundled/hub/external can't be marked."""
- _set_field(skill_name, "sync", bool(sync))
-
-
-def is_sync_enabled(skill_name: str) -> bool:
- return get_record(skill_name).get("sync") is True
-
-
def forget(skill_name: str) -> None:
if skill_name:
_locked_update(skill_name, lambda d: (None, d.pop(skill_name, None) is not None), "skill_usage.forget(%s) failed: %s")
@@ -685,7 +676,7 @@ def _match_skill_dir(skill_mds: Iterable[Path], skill_name: str) -> Optional[Pat
def _find_skill_dir(skill_name: str) -> Optional[Path]:
- """Skill dir by frontmatter ``name`` (flat or nested); the gated index iterator sees only the active org mirror."""
+ """Skill dir by frontmatter ``name`` (flat or nested)."""
from agent.skill_utils import iter_skill_index_files
base = _skills_dir()
return _match_skill_dir((p for p in iter_skill_index_files(base, "SKILL.md") if not is_external_skill_path(p)),
diff --git a/tools/skills_sync_client.py b/tools/skills_sync_client.py
deleted file mode 100644
index d494ca0b308..00000000000
--- a/tools/skills_sync_client.py
+++ /dev/null
@@ -1,498 +0,0 @@
-#!/usr/bin/env python3
-"""Skill Sync client -- the low-level sync layer (push objects + CAS a ref, pull the owner's
-HEAD, three-way merge on a 409). Driven by the debounced ``skill_manage`` push hook, the curator
-tick ``maybe_pull_skills`` and ``hermes sync``. Lives under tools/ so it never imports the CLI at
-module load; ``skills_sync_client_wire`` / ``skills_sync_client_org`` are re-exported here.
-ACCESS GATE (pre-launch): INERT unless the user is a Nous admin per the ``tool_gateway_admin``
-JWT claim (NAS's misleading name for the global portal-admin permission; replace before shipping).
-OPT-IN DEFAULT (provisional): local intent is the ``sync`` flag in ``.usage.json``; the DURABLE
-cross-device state is the ``sync-manifest`` blob in the plane. Only ~/.hermes/skills/ skills qualify."""
-
-from __future__ import annotations
-
-import json
-import logging
-import os
-from contextlib import suppress
-from pathlib import Path, PurePosixPath
-from typing import Any, Callable, Dict, List, Optional, Tuple
-
-from tools.skills_sync_client_wire import (
- DEFAULT_MAX_OBJECT_BYTES, KIND_BLOB, ObjectSet, SyncClient, SyncConflict, SyncError,
- assemble_root_from_skill_trees, build_commit, build_root_tree, build_sync_manifest_bytes, build_tree,
- checked_capabilities, materialize_tree, merge_skill, nest_skill_tree, read_manifest_of_root,
- read_ref_hash, root_tree_of_commit, skill_trees_of_root)
-from tools.skills_sync_client_org import (
- ORG_DIR_NAME, list_locally_modified_org_skills, list_org_skill_names, resolve_org_identity)
-
-logger = logging.getLogger(__name__)
-# Gate claim (NAS's wire name; means "Nous admin" / Permissions.ADMIN_ACCESS). The bearer comes
-# from resolve_nous_runtime_credentials(); its payload is decoded unverified to read this.
-NOUS_ADMIN_CLAIM = "tool_gateway_admin"
-
-
-class SyncInertError(RuntimeError):
- """Sync must no-op: not logged in, no bearer, or not a Nous admin. Caught by the gate-and-swallow hooks."""
-
-
-def resolve_identity() -> Dict[str, Any]:
- """``{api_key, base_url, owner, nous_admin, claims}``; SyncInertError if not logged in / no bearer.
- ``owner`` is advisory (local ref naming; the server derives the real one). The JWT is decoded
- WITHOUT verification: safe, the claims only decide whether to attempt sync, never authz."""
- try:
- from hermes_cli.auth import resolve_nous_runtime_credentials
- creds = resolve_nous_runtime_credentials() or {}
- except Exception as e:
- raise SyncInertError(f"no Nous credentials: {e}") from e
- if not (api_key := creds.get("api_key")):
- raise SyncInertError("no bearer token available")
- try:
- import jwt # PyJWT, a core dependency
- claims = jwt.decode(api_key, options={"verify_signature": False, "verify_exp": False}) or {}
- except Exception as e:
- logger.debug("skills_sync_client: JWT payload decode failed: %s", e)
- claims = {}
- owner = claims.get("sub") or claims.get("privy_did") or claims.get("tid") or "unknown"
- return {"api_key": api_key, "base_url": creds.get("base_url"), "owner": str(owner),
- "nous_admin": claims.get(NOUS_ADMIN_CLAIM) is True, "claims": claims}
-
-
-# Configuration -- env-first so Hermes Cloud can enable sync via environment alone. Every knob:
-# HERMES_SYNC_<KEY> env -> config.yaml ``sync.<key>`` -> default (base_url = the sync plane, NOT
-# the inference URL; enabled; default_opt_in; org_auto_propose).
-DEFAULT_SYNC_BASE_URL = "https://gateway-gateway.nousresearch.com"
-
-_TRUE, _FALSE = {"1", "true", "yes", "on"}, {"0", "false", "no", "off", ""}
-
-
-def _sync_config(key: str) -> Any:
- """``sync.<key>`` from config.yaml, or None. Lazy import: must not import the CLI at module load."""
- try:
- from hermes_cli.config import load_config
- return ((load_config() or {}).get("sync") or {}).get(key)
- except Exception as e:
- logger.debug("skills_sync_client: config sync.%s read failed: %s", key, e)
- return None
-
-
-def resolve_sync_base_url() -> Optional[str]:
- """HERMES_SYNC_BASE_URL -> ``sync.base_url`` -> production plane, without trailing slash
- (``/v1/sync/`` is appended by the client). None only if the default is blanked out."""
- env = os.getenv("HERMES_SYNC_BASE_URL")
- if env and env.strip():
- return env.strip().rstrip("/")
- base = _sync_config("base_url")
- if isinstance(base, str) and base.strip():
- return base.strip().rstrip("/")
- return DEFAULT_SYNC_BASE_URL or None
-
-
-def _parse_bool(value: Any) -> Optional[bool]:
- """Parse a config/env bool; None if unrecognized so callers fall through to the next layer."""
- if isinstance(value, bool) or value is None:
- return value
- s = str(value).strip().lower()
- return True if s in _TRUE else False if s in _FALSE else None
-
-
-def _sync_config_bool(env_var: str, config_key: str, *, default: bool) -> bool:
- """``env_var`` -> ``sync.<config_key>`` -> default."""
- if (val := _parse_bool(os.getenv(env_var))) is not None:
- return val
- return default if (val := _parse_bool(_sync_config(config_key))) is None else val
-
-
-def sync_feature_enabled() -> bool:
- """Master switch; the gate-and-swallow entrypoints ALSO require the Nous-admin gate and a base URL."""
- return _sync_config_bool("HERMES_SYNC_ENABLED", "enabled", default=False)
-
-
-def sync_org_auto_propose() -> bool:
- """False (default): edits to an org skill stay LOCAL until ``hermes sync propose``. True: every
- edit is proposed right away (an admin still approves unless the editor is one)."""
- return _sync_config_bool("HERMES_SYNC_ORG_AUTO_PROPOSE", "org_auto_propose", default=False)
-
-
-def sync_default_opt_in() -> bool:
- """False (default): opt-IN -- a skill syncs only after ``hermes sync enable`` or a plane manifest
- opting it in. True: opt-OUT -- every eligible skill syncs unless disabled (Hermes Cloud default)."""
- return _sync_config_bool("HERMES_SYNC_DEFAULT_OPT_IN", "default_opt_in", default=False)
-
-
-# Local skill eligibility + the personal opt-in flag
-def _skills_dir() -> Path:
- from hermes_constants import get_hermes_home
- return get_hermes_home() / "skills"
-
-
-def _org_dir() -> Path: # local mirror root for org skills (read-only by convention)
- return _skills_dir() / ORG_DIR_NAME
-
-
-def _rel_to_skills_dir(skill_dir: Path) -> Optional[Path]:
- """*skill_dir* relative to ~/.hermes/skills/, or None if outside/unresolvable."""
- try:
- return skill_dir.resolve().relative_to(_skills_dir().resolve())
- except (OSError, ValueError):
- return None
-
-
-def _skill_rel_path(skill_name: str) -> Optional[PurePosixPath]:
- """The skill's path relative to ~/.hermes/skills/ (posix), or None."""
- from tools.skill_usage import _find_skill_dir
- skill_dir = _find_skill_dir(skill_name)
- rel = _rel_to_skills_dir(skill_dir) if skill_dir is not None else None
- return PurePosixPath(rel.as_posix()) if rel is not None else None
-
-
-def is_sync_eligible(skill_name: str) -> bool:
- """Sync candidate (before opt-in): local, NOT bundled/hub-installed/external, NOT under ``_org/``
- (enterprise content never rides a personal push). Mirrors the curator's exclusions."""
- from tools.skill_usage import is_bundled, is_hub_installed, _find_skill_dir
- from agent.skill_utils import is_external_skill_path
- skill_dir = None if is_bundled(skill_name) or is_hub_installed(skill_name) else _find_skill_dir(skill_name)
- if skill_dir is None or is_external_skill_path(skill_dir):
- return False
- rel = _rel_to_skills_dir(skill_dir)
- return not (rel is not None and rel.parts and rel.parts[0] == ORG_DIR_NAME)
-
-
-def list_synced_skill_names() -> List[str]:
- """Sorted skill names that should sync: opt-in -> eligible skills with ``sync: true``;
- opt-out (``sync_default_opt_in()``) -> every eligible skill unless ``sync: false``."""
- from tools.skill_usage import load_usage
- flags = {n: rec.get("sync") for n, rec in (load_usage() or {}).items() if isinstance(rec, dict)}
- if sync_default_opt_in():
- return sorted({n for n in _all_local_skill_names() if flags.get(n) is not False and is_sync_eligible(n)})
- return sorted({n for n, f in flags.items() if f is True and is_sync_eligible(n)})
-
-
-def _all_local_skill_names() -> List[str]:
- """Every local skill name (dir under ~/.hermes/skills/ with SKILL.md; frontmatter ``name`` or dir name)."""
- names: List[str] = []
- root = _skills_dir()
- try:
- for skill_md in root.rglob("SKILL.md") if root.exists() else ():
- if skill_md.is_symlink():
- continue
- name = skill_md.parent.name
- with suppress(Exception):
- from tools.skill_usage import _read_skill_name
- name = _read_skill_name(skill_md, name)
- if name:
- names.append(name)
- except OSError as e:
- logger.debug("skills_sync_client: local skill enumeration failed: %s", e)
- return sorted(set(names))
-
-
-def _opted_in_rel_paths() -> List[str]:
- """Relative posix paths of skills the user has opted into sync."""
- rels = (_skill_rel_path(name) for name in list_synced_skill_names())
- return [rel.as_posix() for rel in rels if rel is not None]
-
-
-def _adopt_manifest_opt_ins(remote_manifest: Optional[Dict[str, bool]]) -> List[str]:
- """Enable local sync intent for skills the plane manifest enabled that are locally
- curation-eligible. Enables only -- a pull never silently disables. Returns adopted names."""
- adopted: List[str] = []
- try:
- from tools.skill_usage import set_sync, is_curation_eligible, is_sync_enabled
- for sname, enabled in (remote_manifest or {}).items():
- if enabled and is_curation_eligible(sname) and not is_sync_enabled(sname):
- set_sync(sname, True)
- adopted.append(sname)
- except Exception as e:
- logger.debug("skills_sync_client: manifest opt-in reconcile failed: %s", e)
- return adopted
-
-
-# Device label (commit ``author.device``; advisory, never an auth input)
-def _default_device_label() -> str:
- """Short hostname + random suffix (two machines can share a hostname); bare uuid if unusable."""
- import socket, uuid
- try:
- host = socket.gethostname() or ""
- except OSError:
- host = ""
- short = "".join(c for c in host.split(".")[0].strip() if c.isalnum() or c in "-_")
- return f"{short}-{uuid.uuid4().hex[:6]}" if short else uuid.uuid4().hex
-
-
-def stable_device_id() -> str:
- """Per-device label at ~/.hermes/skills/.sync_device_id. An existing file always wins; else seeded
- from HERMES_SYNC_DEVICE_NAME (first use only, for Hermes Cloud) or a friendly default, then persisted."""
- with suppress(OSError):
- val = _device_id_path().read_text(encoding="utf-8-sig").strip()
- if val:
- return val
- val = (os.environ.get("HERMES_SYNC_DEVICE_NAME") or "").strip() or _default_device_label()
- try:
- _write_device_id(val)
- except OSError as e:
- logger.debug("skills_sync_client: could not persist device id: %s", e)
- return val
-
-
-def _device_id_path() -> Path:
- return _skills_dir() / ".sync_device_id"
-
-
-def _write_device_id(val: str) -> None:
- _skills_dir().mkdir(parents=True, exist_ok=True)
- _device_id_path().write_text(val, encoding="utf-8")
-
-
-def set_device_name(name: str) -> str:
- """Overwrite the device label with the trimmed *name*; returns it. ValueError on empty."""
- if not (cleaned := (name or "").strip()):
- raise ValueError("device name must be a non-empty string")
- _write_device_id(cleaned)
- return cleaned
-
-
-# Local sync STATE: last HEAD pushed/pulled + its root tree (FULL-digest namespace). Distinct from
-# the bundled manifest (skills_sync.py) and the plane's `sync-manifest`. ~/.hermes/skills/.sync_state.
-_EMPTY_STATE: Dict[str, Any] = {"head": None, "skills": {}}
-
-
-def _load_state_file(path: Path, what: str = "sync state read") -> Optional[Dict[str, Any]]:
- """Parse a state file; None if missing / corrupt / not a dict."""
- try:
- data = json.loads(path.read_text(encoding="utf-8-sig"))
- except (OSError, json.JSONDecodeError) as e:
- logger.debug("skills_sync_client: %s failed: %s", what, e)
- return None
- return {**_EMPTY_STATE, **data} if isinstance(data, dict) else None
-
-
-def read_sync_state() -> Dict[str, Any]:
- """``{"head": "sha256:...|null", "skills": {...}}``; a default on missing/corrupt. A legacy
- ``.sync_manifest`` is migrated to ``.sync_state`` on read so no head record is lost."""
- path, legacy = _skills_dir() / ".sync_state", _skills_dir() / ".sync_manifest"
- if path.exists():
- return _load_state_file(path) or dict(_EMPTY_STATE)
- data = _load_state_file(legacy, "legacy sync state migrate") if legacy.exists() else None
- if data is not None:
- write_sync_state(data)
- with suppress(OSError):
- legacy.unlink()
- return data if data is not None else dict(_EMPTY_STATE)
-
-
-def write_sync_state(data: Dict[str, Any]) -> None:
- """Write the local sync state atomically. Best-effort."""
- try:
- from utils import atomic_write_text
- atomic_write_text(_skills_dir() / ".sync_state",
- json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False),
- tmp_prefix=".sync_state_")
- except Exception as e:
- logger.debug("skills_sync_client: sync state write failed: %s", e)
-
-
-# Profile snapshot -- the root tree mirrors each skill's relative path (categories = intermediate trees).
-def snapshot_profile(skill_names: List[str], *, max_object_bytes: int = DEFAULT_MAX_OBJECT_BYTES,
- ) -> Tuple[ObjectSet, str, Dict[str, str]]:
- """All objects for *skill_names* + profile root -> ``(objects, root_hash, {name: tree_hash})``.
- Oversized skills are skipped (logged); the root carries a ``sync-manifest`` blob of included skills."""
- from tools.skill_usage import _find_skill_dir
- objects = ObjectSet()
- skill_tree_map: Dict[str, str] = {}
- root: Dict[str, Any] = {}
- for name in sorted(set(skill_names)):
- rel, skill_dir = _skill_rel_path(name), _find_skill_dir(name)
- if rel is None or skill_dir is None:
- continue
- try:
- tree_hash = build_tree(skill_dir, objects, max_object_bytes=max_object_bytes)
- except ValueError as e:
- logger.warning("skills_sync_client: skipping %s: %s", name, e)
- continue
- skill_tree_map[name] = tree_hash
- nest_skill_tree(root, rel.parts, tree_hash)
- manifest_hash = objects.add(KIND_BLOB, build_sync_manifest_bytes(dict.fromkeys(skill_tree_map, True)))
- return objects, build_root_tree(root, objects, manifest_hash=manifest_hash), skill_tree_map
-
-
-# Personal refs, push, pull
-def user_head_ref(owner: str) -> str:
- return f"refs/user/{owner}/HEAD"
-
-
-def _personal_client(identity: Optional[Dict[str, Any]], client: Optional[SyncClient],
- ) -> Tuple[Dict[str, Any], Optional[SyncClient]]:
- """Identity + client for a personal sync op; ``client`` is None when no base URL is configured."""
- identity = identity if identity is not None else resolve_identity()
- if client is None and (base := resolve_sync_base_url()):
- client = SyncClient(base, identity["api_key"])
- return identity, client
-
-
-_NO_BASE_URL = {"ok": False, "reason": "no sync base url configured", "noop": True}
-
-
-def push_skills(client: Optional[SyncClient] = None, *, skill_names: Optional[List[str]] = None,
- identity: Optional[Dict[str, Any]] = None, message: str = "hermes skill sync") -> Dict[str, Any]:
- """Push opted-in skills to ``refs/user/<owner>/HEAD`` (upload objects, CAS HEAD). 409 with an actual
- head -> three-way merge + one retry; 409 on a NON-EXISTENT ref (stale local head) -> CAS as a create."""
- identity, client = _personal_client(identity, client)
- if client is None:
- return dict(_NO_BASE_URL)
- owner = identity["owner"]
- skill_names = list_synced_skill_names() if skill_names is None else skill_names
- if not skill_names:
- return {"ok": True, "reason": "no skills opted into sync", "noop": True}
- _caps, max_bytes = checked_capabilities(client)
- objects, root_hash, _ = snapshot_profile(skill_names, max_object_bytes=max_bytes)
- state = read_sync_state()
- base_head = state.get("head")
- # Idempotency: objects are immutable, so an unchanged root hash means identical content.
- if base_head and state.get("root") == root_hash:
- return {"ok": True, "head": base_head, "reason": "unchanged", "noop": True}
- commit_hash = build_commit(root_hash, [base_head] if base_head else [], owner=owner,
- device=stable_device_id(), message=message, objects=objects)
- client.put_objects(objects.objects)
- ref = user_head_ref(owner)
- result = {"ok": True, "head": commit_hash, "pushed_objects": len(objects)}
- try:
- client.cas_ref(ref, base_head, commit_hash)
- except SyncConflict as conflict:
- if conflict.actual:
- return _resolve_push_conflict(client, identity, conflict.actual, root_hash, commit_hash,
- objects, message, base_head)
- client.cas_ref(ref, None, commit_hash)
- result["recovered_stale_head"] = True
- write_sync_state({**state, "head": commit_hash, "root": root_hash})
- return result
-
-
-def _resolve_push_conflict(client: SyncClient, identity: Dict[str, Any], actual_head: str, our_root: str,
- our_commit: str, objects: ObjectSet, message: str, base_head: Optional[str],
- ) -> Dict[str, Any]:
- """Per-skill three-way merge against the forked base (merge_skill): different skills changed ->
- merge commit + CAS retry; SAME skill -> OVERLAP -> refs/user/<owner>/conflict/<n> for out-of-band."""
- owner = identity["owner"]
- ours_trees = skill_trees_of_root(client, our_root)
- theirs_trees = skill_trees_of_root(client, root_tree_of_commit(client, actual_head))
- base_trees = skill_trees_of_root(client, root_tree_of_commit(client, base_head)) if base_head else {}
- merged: Dict[str, str] = {}
- overlaps: List[str] = []
- for path in set(ours_trees) | set(theirs_trees) | set(base_trees):
- o, t = ours_trees.get(path), theirs_trees.get(path)
- decision = merge_skill(base_trees.get(path), o, t)
- if decision == "overlap":
- overlaps.append(path)
- # overlap keeps OURS on the surfaced conflict head (theirs stays server-side);
- # "none" = deleted on the winning side -> drop.
- pick = {"overlap": o, "ours": o, "theirs": t, "either": o if o is not None else t}.get(decision)
- if pick is not None:
- merged[path] = pick
- if overlaps:
- conflict_ref = f"refs/user/{owner}/conflict/{_next_conflict_index(client, owner)}"
- with suppress(SyncConflict): # someone else grabbed this index; the head still exists
- client.cas_ref(conflict_ref, None, our_commit)
- return {"ok": False, "conflict": True, "conflict_ref": conflict_ref, "overlapping_skills": sorted(overlaps),
- "actual_head": actual_head, "message": (f"{len(overlaps)} skill(s) changed on both sides; wrote "
- f"{conflict_ref}. Resolve out-of-band (hermes sync / NAS UI).")}
- # Merge commit (parents: actual, ours); re-add our objects so the merge push is self-contained.
- merge_objects = ObjectSet()
- merge_objects.objects |= objects.objects
- merged_root = assemble_root_from_skill_trees(merged, merge_objects)
- merge_commit = build_commit(merged_root, [actual_head, our_commit], owner=owner,
- device=stable_device_id(), message=f"merge: {message}", objects=merge_objects)
- client.put_objects(merge_objects.objects)
- try:
- client.cas_ref(user_head_ref(owner), actual_head, merge_commit)
- except SyncConflict as c2:
- return {"ok": False, "conflict": True, "actual_head": c2.actual,
- "message": f"merge CAS lost again (head now {c2.actual}); retry sync."}
- write_sync_state({**read_sync_state(), "head": merge_commit, "root": merged_root})
- return {"ok": True, "head": merge_commit, "merged": True}
-
-
-def _next_conflict_index(client: SyncClient, owner: str) -> int:
- """Next free ``conflict/<n>`` index for the owner."""
- try:
- refs = client.get_refs(f"refs/user/{owner}/conflict/")
- except SyncError:
- return 1
- return 1 + max((int(t) for t in (r.get("name", "").rsplit("/", 1)[-1] for r in refs) if t.isdigit()), default=0)
-
-
-def pull_skills(client: Optional[SyncClient] = None, *, identity: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """Pull the owner's HEAD (if it advanced) and materialize opted-in skills. Opt-ins are first
- adopted FROM the plane manifest; only opted-in paths are written (never resurrects a skill)."""
- identity, client = _personal_client(identity, client)
- if client is None:
- return dict(_NO_BASE_URL)
- owner = identity["owner"]
- checked_capabilities(client)
- head = read_ref_hash(client, user_head_ref(owner))
- if not head:
- return {"ok": True, "reason": "no remote HEAD yet", "noop": True}
- state = read_sync_state()
- if head == state.get("head"):
- return {"ok": True, "reason": "already up to date", "head": head, "noop": True}
- root_tree = root_tree_of_commit(client, head)
- remote_trees = skill_trees_of_root(client, root_tree)
- adopted = _adopt_manifest_opt_ins(read_manifest_of_root(client, root_tree))
- opted_in = set(_opted_in_rel_paths())
- updated = [path for path in remote_trees if not opted_in or path in opted_in]
- for path in updated:
- materialize_tree(client, remote_trees[path], _skills_dir() / path)
- write_sync_state({**state, "head": head})
- return {"ok": True, "head": head, "updated": sorted(updated), "opt_in_adopted": sorted(adopted)}
-
-
-# Gated public entrypoints (gate-and-swallow, like maybe_run_curator): never raise; dict or None.
-def _gate_and_swallow(op: str, run: Callable[[Dict[str, Any]], Optional[Dict[str, Any]]]):
- """Run *run(identity)* only if all gates hold (Nous admin, feature on, base URL); None if inert/error."""
- try:
- identity = resolve_identity()
- if not identity.get("nous_admin") or not sync_feature_enabled() or not resolve_sync_base_url():
- return None
- return run(identity)
- except Exception as e:
- logger.debug("skills_sync_client: %s failed: %s", op, e, exc_info=True)
- return None
-
-
-def maybe_push_skills(*, message: str = "hermes skill sync") -> Optional[Dict[str, Any]]:
- """Best-effort push (debounced skill_manage hook). Never raises."""
- return _gate_and_swallow("maybe_push_skills", lambda identity: push_skills(
- identity=identity, message=message) if list_synced_skill_names() else None)
-
-
-def maybe_pull_skills() -> Optional[Dict[str, Any]]:
- """Best-effort pull (curator tick sites: gateway housekeeping + CLI startup). Never raises."""
- return _gate_and_swallow("maybe_pull_skills", lambda identity: pull_skills(identity=identity))
-
-
-def sync_status() -> Dict[str, Any]:
- """Snapshot for ``hermes sync status``; never raises. ``org_available`` False = not in a shared org."""
- status: Dict[str, Any] = {"nous_admin": False, "logged_in": False, "feature_enabled": sync_feature_enabled(),
- "default_opt_in": sync_default_opt_in(), "base_url": resolve_sync_base_url(),
- "opted_in_skills": [], "local_head": None, "owner": None, "org_available": False,
- "org_id": None, "org_role": None, "org_skills": [], "org_skills_modified": []}
- try:
- identity = resolve_identity()
- status.update(logged_in=True, owner=identity.get("owner"), nous_admin=bool(identity.get("nous_admin")))
- except SyncInertError:
- pass
- except Exception as e:
- logger.debug("skills_sync_client: sync_status identity failed: %s", e)
- with suppress(Exception):
- status["opted_in_skills"] = list_synced_skill_names()
- status["local_head"] = read_sync_state().get("head")
- try:
- org_identity = resolve_org_identity()
- status.update(org_available=True, org_id=org_identity.get("org_id"), org_role=org_identity.get("org_role"),
- org_skills=list_org_skill_names(),
- org_skills_modified=list_locally_modified_org_skills(org_identity.get("org_id")))
- except SyncInertError:
- pass
- except Exception as e:
- logger.debug("skills_sync_client: sync_status org lookup failed: %s", e)
- return status
diff --git a/tools/skills_sync_client_org.py b/tools/skills_sync_client_org.py
deleted file mode 100644
index f8cc09157d4..00000000000
--- a/tools/skills_sync_client_org.py
+++ /dev/null
@@ -1,298 +0,0 @@
-"""Org-shared skills: org pull + propose (``~/.hermes/skills/_org/<org_id>/``).
-Org skills live in a DISTINCT local namespace (read-only to the runtime; a local edit is a personal
-fork until proposed); the canonical set is ``refs/org/<org_id>/HEAD`` with the SAME object model.
-PERSONAL-ORG GATE: NAS stamps ``org_role`` ONLY for multi-member orgs; no claim => pull/propose
-raise SyncInertError and personal sync is untouched. ``propose_skill`` must stay non-interactive.
-Module state (``_skills_dir``, ``_org_dir``, base URL, device id) stays in ``tools.skills_sync_client``
-and is read lazily so tests can monkeypatch it."""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import logging
-import shutil
-from contextlib import suppress
-from pathlib import Path, PurePosixPath
-from typing import Any, Callable, Dict, List, Optional
-
-from tools.skills_sync_client_wire import (
- ObjectSet, SyncClient, SyncConflict, SyncError, assemble_root_from_skill_trees, build_commit, build_tree,
- checked_capabilities, materialize_tree, read_ref_hash, root_tree_of_commit, skill_trees_of_root)
-
-logger = logging.getLogger("tools.skills_sync_client")
-ORG_DIR_NAME = "_org"
-# Propose re-splices onto a moved org HEAD at most this many times. Small: contention means
-# other members are actively proposing; unbounded would spin.
-_ORG_CAS_MAX_ATTEMPTS = 5
-
-
-def _ssc():
- from tools import skills_sync_client
- return skills_sync_client
-
-
-def org_head_ref(org_id: str) -> str:
- return f"refs/org/{org_id}/HEAD"
-
-
-def resolve_org_identity() -> Dict[str, Any]:
- """``resolve_identity()`` + ``org_id``/``org_role``; SyncInertError without an ``org_role`` claim
- (personal org / old issuer): org sync unavailable, NOT an error."""
- ssc = _ssc()
- identity = ssc.resolve_identity()
- claims = identity.get("claims") or {}
- org_id, org_role = claims.get("org_id"), claims.get("org_role")
- if not org_id:
- raise ssc.SyncInertError("no organisation associated with this account")
- if not isinstance(org_role, str) or not org_role:
- raise ssc.SyncInertError("this account isn't a member of a shared organisation")
- identity.update(org_id=str(org_id), org_role=org_role)
- return identity
-
-
-def _org_client(identity: Optional[Dict[str, Any]], client: Optional[SyncClient]):
- """(identity, client, max_object_bytes) for an org operation; SyncInertError when the base URL is
- missing or the server lacks the ``org`` feature."""
- ssc = _ssc()
- identity = identity or resolve_org_identity()
- if client is None:
- if not (base_url := ssc.resolve_sync_base_url()):
- raise ssc.SyncInertError("no sync base URL configured")
- client = SyncClient(base_url, identity["api_key"])
- caps, max_bytes = checked_capabilities(client)
- if "org" not in (caps.get("features") or []):
- raise ssc.SyncInertError("this server does not support org-shared skills")
- return identity, client, max_bytes
-
-
-def _read_org_head(client: SyncClient, org_id: str) -> Optional[str]:
- """Current org HEAD, or None. MUST read through the ORG endpoint."""
- return read_ref_hash(client, org_head_ref(org_id), org_scope=True)
-
-
-# Local mirror sidecars
-def _mirror_root(org_id: Optional[str]) -> Path:
- """``<_org_dir>/<org_id>``; the org-level ``_org/`` root itself when *org_id* is None."""
- return _ssc()._org_dir() / org_id if org_id else _ssc()._org_dir()
-
-
-def _write_sidecar(what: str, path_fn: Callable[[], Path], text: str) -> None:
- """Best-effort sidecar write (path resolution included); never raises."""
- try:
- path = path_fn()
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(text, encoding="utf-8")
- except Exception as e:
- logger.debug("skills_sync_client: %s write failed: %s", what, e)
-
-
-def _skill_dir_fingerprint(path: Path) -> str:
- """Content hash of a skill dir (sorted relative path + bytes; mtime-independent). "" on read failure."""
- h = hashlib.sha256()
- try:
- for f in sorted(p for p in path.rglob("*") if p.is_file()):
- h.update(str(f.relative_to(path)).replace("\\", "/").encode("utf-8"))
- h.update(b"\0")
- h.update(f.read_bytes())
- h.update(b"\0")
- except OSError as e:
- logger.debug("skills_sync_client: fingerprint failed for %s: %s", path, e)
- return ""
- return h.hexdigest()
-
-
-def _sidecar_path(org_id: Optional[str], const: str) -> Path:
- """``<mirror>/<agent.skill_utils.<const>>`` (org-level when org_id is None)."""
- import agent.skill_utils as sku
- return _mirror_root(org_id) / getattr(sku, const)
-
-
-def _read_org_baseline(org_id: str) -> Dict[str, Any]:
- """The baseline sidecar: upstream fingerprint + tree of each mirrored skill ({} if absent)."""
- try:
- return json.loads(_sidecar_path(org_id, "ORG_BASELINE_FILE").read_text(encoding="utf-8-sig"))
- except Exception:
- return {}
-
-
-def _write_org_baseline(org_id: str, baseline: Dict[str, Any]) -> None:
- _write_sidecar("baseline", lambda: _sidecar_path(org_id, "ORG_BASELINE_FILE"),
- json.dumps(baseline, indent=2, sort_keys=True))
-
-
-def _write_org_provenance(org_id: str, data: Dict[str, Any]) -> None:
- _write_sidecar("org provenance", lambda: _sidecar_path(org_id, "ORG_PROVENANCE_FILE"),
- json.dumps(data, indent=2))
-
-
-def _write_active_org_marker(org_id: str) -> None:
- """Record which org's mirror may resolve (agent/skill_utils.read_active_org_id)."""
- _write_sidecar("active-org marker", lambda: _sidecar_path(None, "ORG_ACTIVE_MARKER"), org_id)
-
-
-def _clear_active_org_marker() -> None:
- """Remove the active-org marker so org skills stop resolving."""
- try:
- marker = _sidecar_path(None, "ORG_ACTIVE_MARKER")
- if marker.exists():
- marker.unlink()
- logger.info("skills_sync_client: cleared active-org marker "
- "(token has no org workflow); org skills no longer resolve")
- except Exception as e:
- logger.debug("skills_sync_client: marker clear failed: %s", e)
-
-
-def org_skill_is_locally_modified(skill_rel_path: str, org_id: str) -> bool:
- """Local copy differs from upstream's fingerprint. No baseline (pre-existing mirror) => unmodified."""
- dest = _mirror_root(org_id) / PurePosixPath(skill_rel_path)
- entry = _read_org_baseline(org_id).get(skill_rel_path) or {}
- recorded = entry.get("fingerprint") if isinstance(entry, dict) else entry
- return dest.is_dir() and bool(recorded) and _skill_dir_fingerprint(dest) != recorded
-
-
-def _active_org_id() -> Optional[str]:
- from agent.skill_utils import read_active_org_id
- return read_active_org_id(_ssc()._skills_dir())
-
-
-def list_locally_modified_org_skills(org_id: Optional[str] = None) -> List[str]:
- """Org skills with local edits that upstream has not seen."""
- try:
- org_id = org_id or _active_org_id()
- if not org_id:
- return []
- return sorted(rel for rel in _read_org_baseline(org_id) if org_skill_is_locally_modified(rel, org_id))
- except Exception as e:
- logger.debug("skills_sync_client: modified-scan failed: %s", e)
- return []
-
-
-def list_org_skill_names() -> List[str]:
- """Skill names present in the local org mirror (empty when none pulled)."""
- names: List[str] = []
- try:
- org_id = _active_org_id()
- root = _mirror_root(org_id) if org_id else None
- if root and root.is_dir():
- names = [str(rel).replace("\\", "/") for rel in (p.parent.relative_to(root) for p in root.rglob("SKILL.md"))
- if rel.parts]
- except Exception as e:
- logger.debug("skills_sync_client: org skill listing failed: %s", e)
- return sorted(names)
-
-
-# Pull / propose
-def pull_org_skills(client: Optional[SyncClient] = None, *, identity: Optional[Dict[str, Any]] = None,
- ) -> Dict[str, Any]:
- """Pull the org canonical set into the mirror (fast-forward only, no client merge). A skill with
- LOCAL edits is never clobbered: skipped, and in ``conflicted`` when upstream also moved.
- Returns ``{ok, org_id, head, updated, conflicted}``."""
- identity = identity or resolve_org_identity()
- if "org_id" not in identity:
- raise _ssc().SyncInertError("no organisation context available")
- identity, client, _ = _org_client(identity, client)
- org_id = identity["org_id"]
- head = _read_org_head(client, org_id)
- # Marker written HERE: only after the token's org_id + org_role were verified, so a stale mirror
- # from a previous org stops resolving on a pull under another org.
- _write_active_org_marker(org_id)
- if not head:
- return {"ok": True, "org_id": org_id, "head": None, "updated": []}
- head_commit = client.get_commit_json(head, org_scope=True)
- updated, conflicted = [], []
- baseline = _read_org_baseline(org_id)
- for rel_path, tree_hash in sorted(skill_trees_of_root(client, head_commit["tree"], org_scope=True).items()):
- dest = _mirror_root(org_id) / PurePosixPath(rel_path)
- try:
- if dest.exists():
- if org_skill_is_locally_modified(rel_path, org_id):
- if (baseline.get(rel_path) or {}).get("tree") != tree_hash:
- conflicted.append(rel_path)
- continue
- shutil.rmtree(dest)
- materialize_tree(client, tree_hash, dest, org_scope=True) # creates dest
- baseline[rel_path] = {"fingerprint": _skill_dir_fingerprint(dest), "tree": tree_hash}
- updated.append(rel_path)
- except Exception as e:
- logger.warning("skills_sync_client: org skill materialize failed for %s: %s", rel_path, e)
- # Provenance for the skill_view header: the HEAD author is token-verified by the plane at
- # push time, so it is trustworthy to display.
- author = head_commit.get("author") or {}
- _write_org_provenance(org_id, {"org_id": org_id, "head": head, "author_user_id": author.get("owner", ""),
- "author_device": author.get("device", ""), "ts": head_commit.get("ts", ""),
- "skills": updated})
- _write_org_baseline(org_id, baseline)
- if conflicted:
- logger.warning("skills_sync_client: %d org skill(s) have local edits AND upstream "
- "changes; left untouched: %s", len(conflicted), ", ".join(conflicted))
- return {"ok": True, "org_id": org_id, "head": head, "updated": updated, "conflicted": conflicted}
-
-
-def propose_skill(skill_name: str, client: Optional[SyncClient] = None, *,
- identity: Optional[Dict[str, Any]] = None, message: Optional[str] = None) -> Dict[str, Any]:
- """Propose a local skill to the org canonical set: an org-scoped commit splicing that ONE skill
- subtree into the current org HEAD (per-skill deltas, never a wholesale replace), uploaded with
- ``?scope=org``, then CAS. ADMIN/OWNER -> ``{ok, merged: True}``; MEMBER -> 202 -> ``{ok,
- proposal_pending: True, proposal_id, ref}`` (never presented as live). If HEAD moves before the
- CAS the skill is re-spliced onto the NEW head (replaying the old root would drop others' skills)."""
- ssc = _ssc()
- identity, client, max_bytes = _org_client(identity, client)
- org_id = identity["org_id"]
- rel = ssc._skill_rel_path(skill_name)
- if rel is None:
- raise SyncError(f"skill '{skill_name}' not found under the skills dir")
- skill_dir = ssc._skills_dir() / rel
- if not (skill_dir / "SKILL.md").exists():
- raise SyncError(f"skill '{skill_name}' has no SKILL.md")
- objects = ObjectSet()
- skill_tree = build_tree(skill_dir, objects, max_object_bytes=max_bytes)
- for attempt in range(1, _ORG_CAS_MAX_ATTEMPTS + 1):
- base_head = _read_org_head(client, org_id)
- skill_map = {} if not base_head else skill_trees_of_root(
- client, root_tree_of_commit(client, base_head, org_scope=True), org_scope=True)
- skill_map[str(rel)] = skill_tree
- root_hash = assemble_root_from_skill_trees(skill_map, objects)
- commit_hash = build_commit(root_hash, [base_head] if base_head else [], owner=identity["owner"],
- device=ssc.stable_device_id(), message=message or f"propose {skill_name}",
- objects=objects)
- client.put_objects(objects.objects, org_scope=True)
- try:
- result = client.cas_ref(org_head_ref(org_id), base_head, commit_hash)
- break
- except SyncConflict as conflict:
- if attempt >= _ORG_CAS_MAX_ATTEMPTS:
- raise SyncError("the organisation's skills changed while this was being "
- f"proposed, and {attempt} attempts to catch up all lost "
- "the race β€” run the command again", status=409) from conflict
- logger.debug("propose_skill: org HEAD moved (actual=%r), re-splicing (attempt %d)",
- conflict.actual, attempt)
- if result.get("proposal_pending"):
- return {"ok": True, "proposal_pending": True, "proposal_id": result.get("proposal_id"),
- "ref": result.get("ref"), "commit": commit_hash, "org_id": org_id}
- return {"ok": True, "merged": True, "head": result.get("hash", commit_hash),
- "commit": commit_hash, "org_id": org_id}
-
-
-def maybe_pull_org_skills() -> Optional[Dict[str, Any]]:
- """Best-effort org pull if all gates hold; never raises, None when inert. Marker hygiene: a token
- that VERIFIABLY lacks the org claim clears the active-org marker (org skills stop resolving); an
- unresolvable identity (offline, logged out) leaves it alone so pulled org skills keep working."""
- ssc = _ssc()
- try:
- identity = resolve_org_identity()
- except ssc.SyncInertError:
- with suppress(Exception):
- if not (ssc.resolve_identity().get("claims") or {}).get("org_role"):
- _clear_active_org_marker()
- return None
- except Exception as e:
- logger.debug("skills_sync_client: maybe_pull_org_skills inert/failed: %s", e)
- return None
- try:
- if not ssc.sync_feature_enabled() or not ssc.resolve_sync_base_url():
- return None
- return pull_org_skills(identity=identity)
- except Exception as e:
- logger.debug("skills_sync_client: maybe_pull_org_skills inert/failed: %s", e)
- return None
diff --git a/tools/skills_sync_client_wire.py b/tools/skills_sync_client_wire.py
deleted file mode 100644
index ce29b13c589..00000000000
--- a/tools/skills_sync_client_wire.py
+++ /dev/null
@@ -1,343 +0,0 @@
-"""Skill Sync wire model: content-addressed objects, the HTTP client, tree walks.
-
-Independent of local skill state (no ``~/.hermes`` reads); ``tools/skills_sync_client.py``
-orchestrates push/pull on top of it and re-exports these names. Wire contract version 1:
-``hsp_version`` / ``X-HSP-Object-Type`` are deployed protocol identifiers and are NOT
-renamed with the product name "Skill Sync".
-"""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import logging
-import stat as _stat
-from contextlib import suppress
-from datetime import datetime, timezone
-from pathlib import Path, PurePosixPath
-from typing import Any, Dict, List, Optional, Tuple
-
-logger = logging.getLogger("tools.skills_sync_client")
-WIRE_VERSION = "1"
-DEFAULT_MAX_OBJECT_BYTES = 26214400 # 25 MiB, mirrors capabilities default
-KIND_BLOB, KIND_TREE, KIND_COMMIT = "blob", "tree", "commit"
-MODE_FILE, MODE_EXEC, MODE_DIR = "file", "exec", "dir"
-ARTIFACT_TYPE_SKILL = "skill"
-_EXEC_BITS = _stat.S_IXUSR | _stat.S_IXGRP | _stat.S_IXOTH
-
-# `sync-manifest`: per-skill opt-in is CONTENT in the object model, not a device-local flag --
-# a root-level blob in the tree at refs/user/<owner>/HEAD recording {name, enabled}. The plane
-# manifest is authoritative; the local `.usage.json` `sync` flag is only the editable intent
-# (reconciled FROM it on pull, TO it on push). Shape MUST match gateway-gateway src/sync/manifest.ts.
-SYNC_MANIFEST_ENTRY_NAME = SYNC_MANIFEST_TYPE = "sync-manifest"
-SYNC_MANIFEST_VERSION = 1
-
-
-# Content addressing: the wire uses the FULL 64-hex sha256 -- a different namespace from the
-# truncated 16-hex local `content_hash` (skills_guard.py).
-def wire_address(data: bytes) -> str:
- return "sha256:" + hashlib.sha256(data).hexdigest()
-
-
-def canonical_json_bytes(obj: Dict[str, Any]) -> bytes:
- """Canonical JSON for hashing: UTF-8, sorted keys, no whitespace/trailing newline; arrays already in
- contract order. Client and server MUST agree byte-for-byte or a push fails ``422 hash_mismatch``."""
- return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
-
-
-def build_sync_manifest_bytes(skills: Dict[str, bool]) -> bytes:
- """Canonical ``sync-manifest`` bytes for ``{name: enabled}`` (sorted by name for a stable address)."""
- return canonical_json_bytes({
- "type": SYNC_MANIFEST_TYPE, "version": SYNC_MANIFEST_VERSION,
- "skills": [{"name": name, "enabled": bool(enabled)} for name, enabled in sorted(skills.items())],
- })
-
-
-def parse_sync_manifest(data: bytes) -> Optional[Dict[str, bool]]:
- """``{name: enabled}`` from ``sync-manifest`` bytes, or None if malformed. Strict (mirrors gateway
- ``parseSyncManifest``): a bad manifest must not read as "nothing opted in"."""
- try:
- value = json.loads(data.decode("utf-8"))
- except Exception:
- return None
- if (not isinstance(value, dict) or value.get("type") != SYNC_MANIFEST_TYPE
- or value.get("version") != SYNC_MANIFEST_VERSION or not isinstance(value.get("skills"), list)):
- return None
- out: Dict[str, bool] = {}
- for raw in value["skills"]:
- name, enabled = (raw.get("name"), raw.get("enabled")) if isinstance(raw, dict) else (None, None)
- if not isinstance(name, str) or not name or not isinstance(enabled, bool):
- return None
- out[name] = enabled
- return out
-
-
-# Object building
-class ObjectSet:
- """Objects to push, ``hash -> (kind, bytes)``, deduped by content address."""
-
- def __init__(self) -> None:
- self.objects: Dict[str, Tuple[str, bytes]] = {}
-
- def add(self, kind: str, data: bytes) -> str:
- addr = wire_address(data)
- self.objects.setdefault(addr, (kind, data))
- return addr
-
- def __len__(self) -> int:
- return len(self.objects)
-
-
-def _entry(name: str, kind: str, hash_: str, mode: str) -> Dict[str, str]:
- return {"name": name, "kind": kind, "hash": hash_, "mode": mode}
-
-
-def _add_tree(entries: List[Dict[str, str]], objects: ObjectSet) -> str:
- """Canonicalize *entries* (sorted by name, byte order) into a tree object."""
- entries.sort(key=lambda e: e["name"])
- return objects.add(KIND_TREE, canonical_json_bytes({"type": KIND_TREE, "entries": entries}))
-
-
-def _file_mode(path: Path) -> str:
- """``exec`` if +x else ``file``. No symlink / other modes are emitted."""
- with suppress(OSError):
- if path.stat().st_mode & _EXEC_BITS:
- return MODE_EXEC
- return MODE_FILE
-
-
-def build_tree(dir_path: Path, objects: ObjectSet, *, max_object_bytes: int) -> str:
- """Build objects for *dir_path* recursively; return the tree address. Symlinks/special files are
- skipped (contract). A blob over *max_object_bytes* raises ValueError (server would 413)."""
- entries: List[Dict[str, str]] = []
- for child in sorted(dir_path.iterdir(), key=lambda p: p.name):
- if child.is_symlink():
- logger.debug("skills_sync_client: skipping symlink %s", child)
- elif child.is_dir():
- entries.append(_entry(child.name, KIND_TREE, build_tree(child, objects, max_object_bytes=max_object_bytes),
- MODE_DIR))
- elif child.is_file():
- data = child.read_bytes()
- if len(data) > max_object_bytes:
- raise ValueError(f"file {child} is {len(data)} bytes > max_object_bytes {max_object_bytes}")
- entries.append(_entry(child.name, KIND_BLOB, objects.add(KIND_BLOB, data), _file_mode(child)))
- return _add_tree(entries, objects)
-
-
-def build_commit(tree_hash: str, parents: List[str], *, owner: str, device: str, message: str,
- objects: ObjectSet, ts: Optional[str] = None) -> str:
- """Commit object address. ``parents``: 0 first commit, 1 edit, 2 merge (base first, other head second)."""
- return objects.add(KIND_COMMIT, canonical_json_bytes({
- "type": KIND_COMMIT, "tree": tree_hash, "parents": list(parents),
- "author": {"owner": owner, "device": device},
- "ts": ts or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
- "message": message, "artifact_type": ARTIFACT_TYPE_SKILL}))
-
-
-def build_root_tree(node: Dict[str, Any], objects: ObjectSet, *, manifest_hash: Optional[str] = None) -> str:
- """Canonicalize a nested ``{name: {"__tree__": hash} | subdict}`` root into trees. ``manifest_hash``
- adds the root ``sync-manifest`` BLOB entry (cannot collide with a skill dir: those are trees)."""
- entries: List[Dict[str, str]] = []
- for name, child in node.items():
- leaf = isinstance(child, dict) and "__tree__" in child and len(child) == 1
- entries.append(_entry(name, KIND_TREE, child["__tree__"] if leaf else build_root_tree(child, objects),
- MODE_DIR))
- if manifest_hash is not None:
- entries.append(_entry(SYNC_MANIFEST_ENTRY_NAME, KIND_BLOB, manifest_hash, MODE_FILE))
- return _add_tree(entries, objects)
-
-
-def nest_skill_tree(root: Dict[str, Any], rel_parts: Tuple[str, ...], tree_hash: str) -> None:
- """Insert a skill tree leaf into the nested root structure by path parts."""
- node = root
- for part in rel_parts[:-1]:
- node = node.setdefault(part, {})
- node[rel_parts[-1]] = {"__tree__": tree_hash}
-
-
-def assemble_root_from_skill_trees(skill_trees: Dict[str, str], objects: ObjectSet) -> str:
- """Profile-root tree from ``{posix_rel_path: tree_hash}``; skill trees are assumed durable, only
- the new intermediate/root trees are added."""
- root: Dict[str, Any] = {}
- for path, tree_hash in skill_trees.items():
- nest_skill_tree(root, PurePosixPath(path).parts, tree_hash)
- return build_root_tree(root, objects)
-
-
-# HTTP client (routes under /v1/sync/)
-class SyncError(RuntimeError):
- """A non-recoverable wire error (4xx the client can't retry)."""
-
- def __init__(self, message: str, *, status: Optional[int] = None):
- super().__init__(message)
- self.status = status
-
-
-class SyncConflict(RuntimeError):
- """CAS lost (409); NOT a rejection, pushed objects are durable. ``actual`` = head to merge against,
- or None when the ref does not exist (server sends ""): retry as a create, never fetch it."""
-
- def __init__(self, actual: Optional[str]):
- self.actual: Optional[str] = actual or None
- super().__init__(f"CAS conflict; actual head {self.actual}" if self.actual
- else "CAS conflict; the ref does not exist yet")
-
-
-def _check_version(caps: Dict[str, Any]) -> None:
- """Reject an incompatible server major version."""
- ver = str(caps.get("hsp_version") or "") # wire field name
- if ver.split(".", 1)[0] != WIRE_VERSION:
- raise SyncError(f"this server speaks sync version {ver!r}, but this Hermes speaks "
- f"{WIRE_VERSION} β€” update Hermes to sync with it")
-
-
-def _body(r) -> Dict[str, Any]:
- return r.json() if r.content else {}
-
-
-def checked_capabilities(client: "SyncClient") -> Tuple[Dict[str, Any], int]:
- """Version-checked ``(caps, max_object_bytes)`` for a sync session."""
- caps = client.capabilities()
- _check_version(caps)
- return caps, int(caps.get("max_object_bytes") or DEFAULT_MAX_OBJECT_BYTES)
-
-
-class SyncClient:
- """Sync client bound to a base URL + Nous bearer. Org refs/objects live behind SEPARATE ``org/``
- routes: the personal routes are hard-scoped to the token's owner and would silently answer an
- org query with personal data, so org readers MUST pass ``org_scope=True`` on every hop."""
-
- def __init__(self, base_url: str, api_key: str, *, timeout: float = 30.0):
- self.base = base_url.rstrip("/")
- self.api_key = api_key
- self.timeout = timeout
- import requests # core dependency
- self._session = requests.Session()
- self._session.headers["Authorization"] = f"Bearer {api_key}"
-
- def _request(self, method: str, path: str, op: str, *, ok=(200,), errors: Optional[Dict[int, Any]] = None, **kw):
- """One wire call to ``/v1/sync/<path>``; SyncError unless the status is in *ok*. *errors* maps a
- status to a message (str or ``fn(response)``); anything else gets ``"<op> failed: <code>"``."""
- r = self._session.request(method, f"{self.base}/v1/sync/{path.lstrip('/')}", timeout=self.timeout, **kw)
- if r.status_code in ok:
- return r
- msg = (errors or {}).get(r.status_code)
- raise SyncError((msg(r) if callable(msg) else msg) or f"{op} failed: {r.status_code}", status=r.status_code)
-
- def capabilities(self) -> Dict[str, Any]:
- """GET capabilities (no auth required)."""
- return self._request("GET", "capabilities", "capabilities").json()
-
- def get_refs(self, prefix: str, *, org_scope: bool = False) -> List[Dict[str, str]]:
- """GET refs?prefix=... (or org/refs, filtered client-side by *prefix*)."""
- path, params = ("org/refs", None) if org_scope else ("refs", {"prefix": prefix})
- refs = (self._request("GET", path, "get_refs", params=params).json() or {}).get("refs", [])
- return [r_ for r_ in refs if str(r_.get("name", "")).startswith(prefix)] if org_scope else refs
-
- def get_object(self, obj_hash: str, *, org_scope: bool = False) -> Tuple[str, bytes]:
- """GET objects/:hash -> ``(kind, bytes)``; kind from the object-type header, blob default."""
- r = self._request("GET", f"{'org/' if org_scope else ''}objects/{obj_hash}", "get_object",
- errors={404: f"object {obj_hash} not found", 403: f"object {obj_hash} not readable"})
- return r.headers.get("X-HSP-Object-Type") or KIND_BLOB, r.content
-
- def _get_json_of_kind(self, obj_hash: str, expected: str, org_scope: bool) -> Dict[str, Any]:
- kind, data = self.get_object(obj_hash, org_scope=org_scope)
- if kind != expected:
- raise SyncError(f"{obj_hash} is {kind}, expected {expected}")
- return json.loads(data.decode("utf-8"))
-
- def get_commit_json(self, commit_hash: str, *, org_scope: bool = False) -> Dict[str, Any]:
- return self._get_json_of_kind(commit_hash, KIND_COMMIT, org_scope)
-
- def get_tree_json(self, tree_hash: str, *, org_scope: bool = False) -> Dict[str, Any]:
- return self._get_json_of_kind(tree_hash, KIND_TREE, org_scope)
-
- def put_objects(self, objects: Dict[str, Tuple[str, bytes]], *, org_scope: bool = False) -> Dict[str, Any]:
- """POST objects as multipart (field = claimed ``sha256:<hex>``, filename = kind, body = raw
- bytes; no base64-in-JSON). The server rehashes and 422s the whole batch on mismatch; known
- hashes are no-ops. ``org_scope`` adds ``?scope=org`` (required before an org CAS/propose)."""
- files = [(h, (kind, data, "application/octet-stream")) for h, (kind, data) in objects.items()]
- return _body(self._request(
- "POST", "objects", "put_objects", ok=(200, 201), files=files,
- params={"scope": "org"} if org_scope else None,
- errors={413: "object too large (413)", 422: lambda r: f"hash_mismatch (422): {r.text}"}))
-
- def cas_ref(self, name: str, from_hash: Optional[str], to_hash: str) -> Dict[str, Any]:
- """POST refs/:name -- atomic CAS; SyncConflict on 409. A member's CAS on an org HEAD becomes a
- proposal (202) -> ``{"proposal_pending": True, ...}``: success-shaped, never present as live."""
- r = self._request("POST", f"refs/{name}", "cas_ref", ok=(200, 202, 409),
- json={"from": from_hash, "to": to_hash}, errors={403: "forbidden (403) -- owner/permission"})
- if r.status_code == 202:
- return {"proposal_pending": True, **_body(r)}
- if r.status_code == 409: # "" actual = the ref does not exist server-side (-> None)
- raise SyncConflict((r.json() or {}).get("actual", ""))
- return _body(r)
-
-
-# Reading remote trees
-def read_ref_hash(client: SyncClient, ref: str, *, org_scope: bool = False) -> Optional[str]:
- """Hash of *ref* (queried with itself as prefix), or None if absent."""
- refs = client.get_refs(ref, org_scope=org_scope)
- return next((r.get("hash") for r in refs if r.get("name") == ref), None)
-
-
-def root_tree_of_commit(client: SyncClient, commit_hash: str, *, org_scope: bool = False) -> str:
- return client.get_commit_json(commit_hash, org_scope=org_scope)["tree"]
-
-
-def skill_trees_of_root(client: SyncClient, root_tree_hash: str, *, org_scope: bool = False) -> Dict[str, str]:
- """``{posix_rel_path: skill_tree_hash}`` for every subtree containing a ``SKILL.md`` blob."""
- result: Dict[str, str] = {}
- def _walk(tree_hash: str, prefix: str) -> None:
- entries = client.get_tree_json(tree_hash, org_scope=org_scope).get("entries", [])
- if prefix and any(e.get("name") == "SKILL.md" and e.get("kind") == KIND_BLOB for e in entries):
- result[prefix] = tree_hash
- return
- for e in entries:
- if e.get("kind") == KIND_TREE:
- _walk(e["hash"], f"{prefix}/{e['name']}" if prefix else e["name"])
- _walk(root_tree_hash, "")
- return result
-
-
-def read_manifest_of_root(client: SyncClient, root_tree_hash: str) -> Optional[Dict[str, bool]]:
- """``{name: enabled}`` from the root ``sync-manifest`` blob (how a device learns another's opt-ins)."""
- try:
- for e in client.get_tree_json(root_tree_hash).get("entries", []):
- if e.get("name") == SYNC_MANIFEST_ENTRY_NAME and e.get("kind") == KIND_BLOB:
- return parse_sync_manifest(client.get_object(e["hash"])[1])
- except Exception as e:
- logger.debug("skills_sync_client: manifest read failed: %s", e)
- return None
-
-
-def materialize_tree(client: SyncClient, tree_hash: str, dest: Path, *, org_scope: bool = False) -> None:
- """Write the tree into *dest*: blobs -> files (+x for ``exec``), trees -> subdirs. Does NOT delete
- files absent from the tree (caller decides). Refuses path traversal."""
- dest.mkdir(parents=True, exist_ok=True)
- for entry in client.get_tree_json(tree_hash, org_scope=org_scope).get("entries", []):
- name = entry.get("name", "")
- if not name or "/" in name or name in (".", ".."):
- logger.warning("skills_sync_client: skipping unsafe tree entry %r", name)
- continue
- target, kind = dest / name, entry.get("kind")
- if kind == KIND_TREE:
- materialize_tree(client, entry["hash"], target, org_scope=org_scope)
- elif kind == KIND_BLOB:
- _, data = client.get_object(entry["hash"], org_scope=org_scope)
- target.write_bytes(data)
- if entry.get("mode") == MODE_EXEC:
- with suppress(OSError):
- target.chmod(target.stat().st_mode | _EXEC_BITS)
-
-
-def merge_skill(base: Optional[str], ours: Optional[str], theirs: Optional[str]) -> str:
- """Three-way decision: ``ours``/``theirs``/``either``/``overlap``/``none``. A side "modified" the
- skill when its hash differs from the base (same semantics as skills_sync.py)."""
- if ours == theirs:
- return "either" if ours is not None else "none"
- if theirs == base: # only we moved
- return "ours"
- if ours == base: # only they moved
- return "theirs"
- return "overlap"
diff --git a/tools/skills_tool.py b/tools/skills_tool.py
index 97a794e0d73..2cff3829929 100644
--- a/tools/skills_tool.py
+++ b/tools/skills_tool.py
@@ -404,34 +404,6 @@ def _skill_linked_files(skill_dir: Optional[Path]) -> dict:
return files
-def _org_provenance_header(skill_dir: Path, active_skills_dir: Path):
- """(org_provenance dict, header text) for an org-mirror skill, else (None, ""). Announced IN
- the content the model consumes; the author is token-verified at push time by the sync plane."""
- from agent.skill_utils import ORG_PROVENANCE_FILE, is_org_mirror_path, org_id_of_path
- if not is_org_mirror_path(skill_dir, active_skills_dir):
- return None, ""
- prov_org = org_id_of_path(skill_dir, active_skills_dir)
- prov: dict = {}
- if prov_org:
- with suppress(Exception):
- prov_path = active_skills_dir / "_org" / prov_org / ORG_PROVENANCE_FILE
- loaded = json.loads(_read_skill_text(prov_path))
- prov = loaded if isinstance(loaded, dict) else {}
- author = str(prov.get("author_device") or prov.get("author_user_id") or "")
- ts = str(prov.get("ts") or "")
- header = (
- "> [!NOTE] ORG-SHARED SKILL β€” provenance\n"
- f"> This skill is shared by your organisation (org `{prov_org}`"
- + (f", last updated by `{author}`" if author else "")
- + (f", as of {ts}" if ts else "")
- + "). It was reviewed and approved for the whole\n"
- "> team β€” treat it as third-party instructions rather than your own notes.\n"
- "> You MAY improve it in place like any other skill. Your edits are kept locally\n"
- "> and are never overwritten by org updates; share them back with\n"
- "> `hermes sync propose` (or automatically, if your org enables it).\n\n")
- return {"org_id": prov_org, "shared_by": author or None, "as_of": ts or None}, header
-
-
def _skill_readiness(frontmatter: Dict[str, Any], skill_name: str) -> Tuple[dict, dict]:
"""Resolve required env vars / credential files (prompting for secrets where the surface
allows) and register what's available for sandboxes. Returns ``(fields, extras)``: fields go
@@ -633,13 +605,6 @@ def skill_view(
readiness, readiness_extras = _skill_readiness(frontmatter, skill_name)
rendered_content = content if not preprocess else _preprocess_skill(
content, skill_dir, task_id, "Could not preprocess skill content for %s", skill_name)
- org_provenance, header = None, ""
- if skill_dir:
- try:
- org_provenance, header = _org_provenance_header(skill_dir, active_skills_dir)
- except Exception:
- logger.debug("Could not resolve org provenance for %s", skill_name, exc_info=True)
-
# ── pm tool deps (`deps: [ffmpeg]` frontmatter) ──────────────
# Loading the skill IS the activation moment: ensure each declared
# pm package now so the skill's commands work when the model runs
@@ -669,9 +634,8 @@ def skill_view(
result = {
"success": True, "name": skill_name, "description": frontmatter.get("description", ""),
- "tags": tags, "related_skills": related_skills, "content": header + rendered_content,
+ "tags": tags, "related_skills": related_skills, "content": rendered_content,
"path": rel_path, "skill_dir": str(skill_dir) if skill_dir else None,
- "org_provenance": org_provenance,
"linked_files": linked_files if linked_files else None,
"usage_hint": "To view linked files, call skill_view(name, file_path) where file_path is e.g. 'references/api.md' or 'assets/config.yaml'" if linked_files else None,
**readiness,
diff --git a/website/docs/user-guide/features/curator.md b/website/docs/user-guide/features/curator.md
index f298933f8ec..fcd16c1610f 100644
--- a/website/docs/user-guide/features/curator.md
+++ b/website/docs/user-guide/features/curator.md
@@ -21,7 +21,7 @@ The curator is triggered by an inactivity check, not a cron job. On CLI session
1. Enough time has passed since the last curator run (`interval_hours`, default **7 days**), and
2. The agent has been idle long enough (`min_idle_hours`, default **2 hours**).
-Desktop and other `hermes serve` backends share the existing hourly maintenance timer (first poll after 90 seconds), independently of cron jobs. They measure inactivity from process startup and the most recent chat activity in the same profile, retaining that activity timestamp after a session closes or is reaped, and skip curator while a turn in that profile is running. A connected but inactive window does not block maintenance. This timer also polls personal and organization Skill Sync, subject to those features' own opt-in gates. A running messaging gateway for the same profile owns these chores instead.
+Desktop and other `hermes serve` backends share the existing hourly maintenance timer (first poll after 90 seconds), independently of cron jobs. They measure inactivity from process startup and the most recent chat activity in the same profile, retaining that activity timestamp after a session closes or is reaped, and skip curator while a turn in that profile is running. A connected but inactive window does not block maintenance. A running messaging gateway for the same profile owns these chores instead.
The timer services its backend's profile. In-flight maintenance runs in a worker thread; closing the backend does not cooperatively interrupt that pass. Starting multiple independent serve processes for the same profile can still race the curator's interval check.
diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md
index 8e135593b18..7f41190a0b4 100644
--- a/website/docs/user-guide/multi-profile-gateways.md
+++ b/website/docs/user-guide/multi-profile-gateways.md
@@ -677,7 +677,7 @@ profile and never shares with the default or any sibling:
| Working directory of a turn (unset `terminal.cwd`) | Same rule as a standalone gateway: `$HOME` for the local backend, sandbox default otherwise | Never the directory the multiplexer process was launched from |
| Command approvals (`command_allowlist`, "always" choices) | The profile's own `config.yaml` | A default-profile "always" never pre-approves a secondary's command; a secondary's choice is saved to its own config |
| Sandbox credential-file mounts (`terminal.credential_files`), `security.redact_secrets`, `browser.*` engine/headed flags, `lsp.*`, auxiliary-provider health marks, `logs/mcp-stderr.log` | The profile's own `config.yaml` / `.env` | Documented default β€” never the launch profile's cached value |
-| Cloud-SDK credential clients (Bedrock boto3 clients + model discovery, Azure Entra credential), credential-fetched catalogs (DeepInfra, Copilot context limits, Nous reasoning caps, Ramp Router efforts, xAI / OpenRouter image models, custom-endpoint `/models`), Camofox VNC address, computer-use aux-vision routing, skill-sync push, remote-backend probe text, learned image token costs, `display.skin`, guest-mint back-off, banner skills, Yuanbao "active" adapter, Langfuse client | The profile's own `.env` / `config.yaml` / `<home>/cache` | Documented default β€” never the launch profile's cached value or its credentials |
+| Cloud-SDK credential clients (Bedrock boto3 clients + model discovery, Azure Entra credential), credential-fetched catalogs (DeepInfra, Copilot context limits, Nous reasoning caps, Ramp Router efforts, xAI / OpenRouter image models, custom-endpoint `/models`), Camofox VNC address, computer-use aux-vision routing, remote-backend probe text, learned image token costs, `display.skin`, guest-mint back-off, banner skills, Yuanbao "active" adapter, Langfuse client | The profile's own `.env` / `config.yaml` / `<home>/cache` | Documented default β€” never the launch profile's cached value or its credentials |
| Session-search knobs (`sessions.cjk_fts`, `sessions.search_slow_ms`) | The profile's `config.yaml` | Documented default β€” never the default profile's bridged value |
| RoomLink capability catalog and the signed execution policy it advertises to a remote Bot (`approvals.mode`, `agent.max_turns`, `platform_toolsets.api_server`) | The served profile named by the request (`/p/<profile>/v1/room-members/...`, the RPC `profile` param); `target_profile` is **required** on every catalog β€” there is no `HERMES_PROFILE` fallback | Invitation/capabilities fail with the offending `target_profile` named; a profile that does not exist is refused, never resolved from the launch profile's config |
| Platform proxies (`TELEGRAM_PROXY`, `DISCORD_PROXY`, `HTTPS_PROXY`, …) | The profile's own `.env` | Direct connection β€” never the default profile's proxy |