The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): unify SyncClient HTTP request/error handling; compact skills_sync_client trio
Teknium71a9022c48bd
diff --git a/tools/skills_sync_client.py b/tools/skills_sync_client.pyindex 1ff1b45713d..2444c2862e3 100644--- a/tools/skills_sync_client.py+++ b/tools/skills_sync_client.py@@ -1,22 +1,16 @@#!/usr/bin/env python3"""Skill Sync client -- the low-level sync layer.-Builds content-addressed objects from local skills and talks the sync wire-contract (push objects + CAS a ref, pull the owner's HEAD, three-way merge on-a 409). Driven by the debounced push hook in ``skill_manage``, the periodic-``maybe_pull_skills`` at the curator tick sites, and the ``hermes sync`` CLI.-Lives under tools/ (NOT hermes_cli/) so it never imports the CLI at module-load. ``skills_sync_client_wire`` (object model + HTTP client + tree walks) and-``skills_sync_client_org`` (org-shared skills) are re-exported here.--ACCESS GATE (pre-launch): sync is INERT unless the signed-in user is a Nous-admin, read off the ``tool_gateway_admin`` JWT claim. The claim name is NAS's-and misleading: it is the global portal-admin permission, NOT a tool-gateway-right. Replace with a real entitlement before shipping to users.--OPT-IN DEFAULT (provisional): nothing syncs unless the user marks a skill for-sync. Local intent is the ``sync`` flag in ``.usage.json``; the DURABLE-cross-device state is the committed ``sync-manifest`` blob in the plane. Only+Builds content-addressed objects from local skills and talks the sync wire contract (push+objects + CAS a ref, pull the owner's HEAD, three-way merge on a 409). Driven by the debounced+push hook in ``skill_manage``, ``maybe_pull_skills`` at the curator tick sites, and ``hermes+sync``. Lives under tools/ (NOT hermes_cli/) so it never imports the CLI at module load;+``skills_sync_client_wire`` and ``skills_sync_client_org`` are re-exported here.+ACCESS GATE (pre-launch): sync is INERT unless the signed-in user is a Nous admin, read off the+``tool_gateway_admin`` JWT claim (NAS's misleading name for the global portal-admin permission;+replace with a real entitlement before shipping). OPT-IN DEFAULT (provisional): nothing syncs+unless the user marks a skill for sync -- local intent is the ``sync`` flag in ``.usage.json``,+the DURABLE cross-device state is the committed ``sync-manifest`` blob in the plane. Onlyagent-created + user-authored skills under ``~/.hermes/skills/`` are eligible."""@@ -45,40 +39,30 @@ logger = logging.getLogger(__name__)_merge_skill = merge_skill_skill_trees_of_root = skill_trees_of_root--# Identity & access gate. The bearer comes from resolve_nous_runtime_credentials()-# (file lock, host allowlist, refresh -- not reimplemented); its payload is-# decoded unverified to read the gate claim.--# Wire claim name is NAS's; it means "Nous admin" (Permissions.ADMIN_ACCESS).+# Identity & access gate. The bearer comes from resolve_nous_runtime_credentials() (file lock,+# host allowlist, refresh); its payload is decoded unverified to read the gate claim, whose+# wire name is NAS's and means "Nous admin" (Permissions.ADMIN_ACCESS).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."""+ """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]:- """Resolve ``{api_key, base_url, owner, nous_admin, claims}``; raises- SyncInertError if not logged in / no bearer. ``owner`` is advisory for local- ref naming only -- the server derives the real owner from the bearer.-- The JWT payload is decoded WITHOUT signature verification. Safe: the claims- are never used for authz here (the server re-verifies); they only decide- whether to attempt sync at all.- """+ """``{api_key, base_url, owner, nous_admin, claims}``; SyncInertError if not logged in / no+ bearer. ``owner`` is advisory for local ref naming only -- the server derives the real owner+ from the bearer. The JWT is decoded WITHOUT signature verification: safe because the claims+ never drive authz here (the server re-verifies), only whether to attempt sync at all."""try:from hermes_cli.auth import resolve_nous_runtime_credentialscreds = resolve_nous_runtime_credentials() or {}except Exception as e:raise SyncInertError(f"no Nous credentials: {e}") from e-api_key = creds.get("api_key")if not api_key:raise SyncInertError("no bearer token available")-try:import jwt # PyJWT, a core dependency@@ -88,18 +72,14 @@ def resolve_identity() -> Dict[str, Any]: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,+ "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 a Hermes Cloud instance can enable sync purely-# through environment variables. Every knob: HERMES_SYNC_<KEY> env -> config.yaml-# ``sync.<key>`` -> built-in default (keys: base_url = the sync plane, NOT the-# inference URL; enabled; default_opt_in; org_auto_propose).+# Configuration -- env-first so a Hermes Cloud instance can enable sync purely through the+# environment. Every knob: HERMES_SYNC_<KEY> env -> config.yaml ``sync.<key>`` -> default+# (keys: base_url = the sync plane, NOT the inference URL; enabled; default_opt_in; org_auto_propose).#: Production Skill Sync plane; a normal user configures nothing.DEFAULT_SYNC_BASE_URL = "https://gateway-gateway.nousresearch.com"@@ -109,8 +89,7 @@ _FALSE = {"0", "false", "no", "off", ""}def _sync_config(key: str) -> Any:- """``sync.<key>`` from config.yaml, or None. Lazy import: this layer must not- import the CLI at module load."""+ """``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@@ -121,9 +100,8 @@ def _sync_config(key: str) -> Any:def resolve_sync_base_url() -> Optional[str]:- """HERMES_SYNC_BASE_URL -> ``sync.base_url`` -> production plane, without a- trailing slash (``/v1/sync/`` is appended by the client). None only if the- default is blanked out."""+ """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("/")@@ -134,8 +112,7 @@ def resolve_sync_base_url() -> Optional[str]:def _parse_bool(value: Any) -> Optional[bool]:- """Parse a config/env bool; None if unrecognized so callers fall through to- the next precedence layer."""+ """Parse a config/env bool; None if unrecognized so callers fall through to the next layer."""if isinstance(value, bool):return valueif value is None:@@ -154,22 +131,19 @@ def _sync_config_bool(env_var: str, config_key: str, *, default: bool) -> bool:def sync_feature_enabled() -> bool:- """Master switch. Checked by the gate-and-swallow entrypoints IN ADDITION to- the Nous-admin gate and a configured base URL -- all three must hold."""+ """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) -- for small high-trust teams."""+ """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 explicitly disabled (the Hermes Cloud default). Provisional."""+ """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)@@ -206,10 +180,9 @@ def _skill_rel_path(skill_name: str) -> Optional[PurePosixPath]:def is_sync_eligible(skill_name: str) -> bool:- """Candidate for sync (before the opt-in check): present locally, NOT- bundled, NOT hub-installed, NOT external, and NOT under the ``_org/`` mirror- (enterprise content must never ride a personal push). Mirrors the curator's- exclusions (tools/skill_usage.py)."""+ """Candidate for sync (before the opt-in check): present locally, NOT bundled, NOT hub-installed,+ NOT external, NOT under the ``_org/`` mirror (enterprise content must never ride a personal+ push). Mirrors the curator's exclusions (tools/skill_usage.py)."""try:from tools.skill_usage import is_bundled, is_hub_installed, _find_skill_dirfrom agent.skill_utils import is_external_skill_path@@ -225,9 +198,9 @@ def is_sync_eligible(skill_name: str) -> bool:def list_synced_skill_names() -> List[str]:- """Names of skills that should sync (sorted, deduped), per ``sync_default_opt_in()``:- opt-in -> only eligible skills whose usage record has ``sync: true``;- opt-out -> every eligible skill unless its record has ``sync: false``."""+ """Names of skills that should sync (sorted, deduped), per ``sync_default_opt_in()``: opt-in ->+ eligible skills whose usage record has ``sync: true``; opt-out -> every eligible skill unless+ its record has ``sync: false``."""try:from tools.skill_usage import load_usageexcept Exception:@@ -242,9 +215,8 @@ def list_synced_skill_names() -> List[str]:def _all_local_skill_names() -> List[str]:- """Every locally-present skill name (a dir under ~/.hermes/skills/ with a- ``SKILL.md``; frontmatter ``name`` falling back to the dir name). Eligibility- is applied by the caller."""+ """Every locally-present skill name (a dir under ~/.hermes/skills/ with a ``SKILL.md``;+ frontmatter ``name`` falling back to the dir name). Eligibility is applied by the caller."""names: List[str] = []root = _skills_dir()try:@@ -272,9 +244,8 @@ def _opted_in_rel_paths() -> List[str]:def _adopt_manifest_opt_ins(remote_manifest: Optional[Dict[str, bool]]) -> List[str]:- """Enable local sync intent for skills the plane manifest has enabled and that- are locally curation-eligible. Enables only -- a pull never silently disables.- Returns the adopted names; best-effort."""+ """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] = []if not remote_manifest:return adopted@@ -293,8 +264,7 @@ def _adopt_manifest_opt_ins(remote_manifest: Optional[Dict[str, bool]]) -> List[# Device label (commit ``author.device``; advisory, never an auth input)def _default_device_label() -> str:- """Short hostname + short random suffix (two machines can share a hostname);- a bare uuid if the hostname is unusable."""+ """Short hostname + random suffix (two machines can share a hostname); bare uuid if unusable."""import socketimport uuid@@ -307,10 +277,9 @@ def _default_device_label() -> str:def stable_device_id() -> str:- """Stable per-device label, persisted at ~/.hermes/skills/.sync_device_id.- An existing file always wins. Otherwise seeded from HERMES_SYNC_DEVICE_NAME- (first use only; lets Hermes Cloud name hosted instances) or a friendly- default, then persisted so a later ``set_device_name()`` still wins."""+ """Stable per-device label persisted at ~/.hermes/skills/.sync_device_id. An existing file+ always wins; otherwise seeded from HERMES_SYNC_DEVICE_NAME (first use only; lets Hermes Cloud+ name hosted instances) or a friendly default, then persisted so a later ``set_device_name()`` wins."""path = _skills_dir() / ".sync_device_id"try:if path.exists():@@ -334,8 +303,7 @@ def _write_device_id(val: str) -> None:def set_device_name(name: str) -> str:- """Overwrite the device label with the trimmed *name*; any non-empty string- is accepted. Returns the stored value; ValueError on empty."""+ """Overwrite the device label with the trimmed *name*; returns it. ValueError on empty."""cleaned = (name or "").strip()if not cleaned:raise ValueError("device name must be a non-empty string")@@ -343,10 +311,9 @@ def set_device_name(name: str) -> str:return cleaned-# Local sync STATE: the last HEAD we pushed/pulled + the root tree at that-# point (FULL-digest namespace). Distinct from the bundled manifest-# (skills_sync.py) and from the plane's `sync-manifest` object. Lives at-# ~/.hermes/skills/.sync_state; a legacy `.sync_manifest` is migrated on read.+# Local sync STATE: the last HEAD we pushed/pulled + the root tree at that point (FULL-digest+# namespace). Distinct from the bundled manifest (skills_sync.py) and from the plane's+# `sync-manifest` object. Lives at ~/.hermes/skills/.sync_state; legacy `.sync_manifest` migrates on read._EMPTY_STATE: Dict[str, Any] = {"head": None, "skills": {}}@@ -370,9 +337,9 @@ def _load_state_file(path: Path, what: str = "sync state read") -> Optional[Dictdef read_sync_state() -> Dict[str, Any]:- """``{"head": "sha256:...|null", "skills": {...}}``; a default on missing/corrupt.- If ``.sync_state`` is absent but the legacy ``.sync_manifest`` exists, it is- read, rewritten to the new path and removed, so no head record is lost."""+ """``{"head": "sha256:...|null", "skills": {...}}``; a default on missing/corrupt. If+ ``.sync_state`` is absent but the legacy ``.sync_manifest`` exists it is read, rewritten to+ the new path and removed, so no head record is lost."""path = _sync_state_path()if path.exists():return _load_state_file(path) or dict(_EMPTY_STATE)@@ -413,16 +380,15 @@ def _record_head(state: Dict[str, Any], head: str, root: str) -> None:write_sync_state(state)-# Profile snapshot -- the root tree mirrors each synced skill's relative path-# under ~/.hermes/skills/ (category dirs become intermediate trees).+# Profile snapshot -- the root tree mirrors each synced skill's relative path under+# ~/.hermes/skills/ (category dirs become intermediate trees).def snapshot_profile(skill_names: List[str], *, max_object_bytes: int = DEFAULT_MAX_OBJECT_BYTES) -> Tuple[ObjectSet, str, Dict[str, str]]:- """Build all objects for *skill_names* + the profile-root tree; returns- ``(objects, root_tree_hash, {skill_name: tree_hash})``. Skills whose blobs- exceed *max_object_bytes* are skipped (logged). The root also carries the- ``sync-manifest`` blob listing every included skill as ``enabled: true``."""+ """Build all objects for *skill_names* + the profile-root tree -> ``(objects, root_tree_hash,+ {skill_name: tree_hash})``. Skills whose blobs exceed *max_object_bytes* are skipped (logged).+ The root also carries the ``sync-manifest`` blob listing every included skill as enabled."""from tools.skill_usage import _find_skill_dirobjects = ObjectSet()@@ -440,7 +406,6 @@ def snapshot_profile(continueskill_tree_map[name] = tree_hashnest_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@@ -454,8 +419,7 @@ def user_head_ref(owner: str) -> str:def _personal_client(identity: Optional[Dict[str, Any]], client: Optional[SyncClient]) -> Tuple[Dict[str, Any], Optional[SyncClient]]:- """Resolve identity + client for a personal sync op. ``client`` is None when- no base URL is configured (callers return a no-op result)."""+ """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:base = resolve_sync_base_url()@@ -473,15 +437,13 @@ def push_skills(identity: Optional[Dict[str, Any]] = None,message: str = "hermes skill sync",) -> Dict[str, Any]:- """Push opted-in skills to ``refs/user/<owner>/HEAD``: upload new objects, CAS- HEAD. A 409 with an actual head -> three-way merge + one retry; a 409 against- a NON-EXISTENT ref (stale local head, e.g. carried over from another plane)- -> redo the CAS as a create. Never raises for the inert / no-op cases."""+ """Push opted-in skills to ``refs/user/<owner>/HEAD``: upload new objects, CAS HEAD. A 409 with+ an actual head -> three-way merge + one retry; a 409 against a NON-EXISTENT ref (stale local+ head, e.g. from another plane) -> redo the CAS as a create. Never raises for inert/no-op cases."""identity, client = _personal_client(identity, client)if client is None:return dict(_NO_BASE_URL)owner = identity["owner"]-if skill_names is None:skill_names = list_synced_skill_names()if not skill_names:@@ -491,11 +453,9 @@ def push_skills(_check_version(caps)max_bytes = int(caps.get("max_object_bytes") or DEFAULT_MAX_OBJECT_BYTES)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 tree hash means- # identical content -- skip building an empty commit.+ # 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}@@ -519,10 +479,6 @@ def push_skills(return result-# Three-way merge per skill against the base we forked from (see merge_skill):-# each side changing a DIFFERENT skill -> merge commit (2 parents) + CAS retry;-# both changing the SAME skill differently -> TRUE OVERLAP -> written to-# refs/user/<owner>/conflict/<n> and surfaced for out-of-band resolution.def _resolve_push_conflict(client: SyncClient,identity: Dict[str, Any],@@ -533,6 +489,9 @@ def _resolve_push_conflict(message: str,base_head: Optional[str],) -> Dict[str, Any]:+ """Three-way merge per skill against the base we forked from (see merge_skill): each side+ changing a DIFFERENT skill -> merge commit (2 parents) + CAS retry; both changing the SAME+ skill -> TRUE OVERLAP -> written to refs/user/<owner>/conflict/<n> for out-of-band resolution."""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))@@ -545,18 +504,16 @@ def _resolve_push_conflict(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.+ # 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] = pickif overlaps:conflict_ref = f"refs/user/{owner}/conflict/{_next_conflict_index(client, owner)}"- try:+ with suppress(SyncConflict): # someone else grabbed this index; the head still existsclient.cas_ref(conflict_ref, None, our_commit)- except SyncConflict:- pass # someone else grabbed this index; the head still existsreturn {"ok": False, "conflict": True, "conflict_ref": conflict_ref,"overlapping_skills": sorted(overlaps), "actual_head": actual_head,@@ -566,8 +523,7 @@ def _resolve_push_conflict(),}- # Merge commit (parents: actual, ours); re-add our objects so the merge- # push is self-contained.+ # Merge commit (parents: actual, ours); re-add our objects so the merge push is self-contained.merge_objects = ObjectSet()merge_objects.objects.update(objects.objects)merged_root = assemble_root_from_skill_trees(merged, merge_objects)@@ -600,44 +556,39 @@ def _next_conflict_index(client: SyncClient, owner: str) -> int:def pull_skills(client: Optional[SyncClient] = None, *, identity: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:- """Pull the owner's HEAD and materialize opted-in skills under ~/.hermes/skills/- if it advanced past our recorded head. Opt-in intent is first adopted FROM- the plane manifest, then only opted-in paths are written so a pull never- resurrects a skill the user hasn't chosen. Best-effort; returns a result dict."""+ """Pull the owner's HEAD and materialize opted-in skills under ~/.hermes/skills/ if it advanced+ past our recorded head. Opt-in intent is first adopted FROM the plane manifest, then only+ opted-in paths are written so a pull never resurrects a skill the user hasn't chosen."""identity, client = _personal_client(identity, client)if client is None:return dict(_NO_BASE_URL)owner = identity["owner"]-_check_version(client.capabilities())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)-state["head"] = headwrite_sync_state(state)return {"ok": True, "head": head, "updated": sorted(updated), "opt_in_adopted": sorted(adopted)}-# Gated public entrypoints (gate-and-swallow, like the curator's-# maybe_run_curator): best-effort, never raise, return a result dict or None.+# Gated public entrypoints (gate-and-swallow, like the curator's maybe_run_curator): best-effort,+# never raise, return a result dict or None.def _gate_and_swallow(op: str, run: Callable[[Dict[str, Any]], Optional[Dict[str, Any]]]):- """Run *run(identity)* only if every background-sync gate holds (Nous admin,- feature on, base URL); None when inert or on any error."""+ """Run *run(identity)* only if every background-sync gate holds (Nous admin, feature on, base+ URL); None when inert or on any error."""try:identity = resolve_identity()if not identity.get("nous_admin") or not sync_feature_enabled() or not resolve_sync_base_url():@@ -657,22 +608,19 @@ def maybe_push_skills(*, message: str = "hermes skill sync") -> Optional[Dict[stdef maybe_pull_skills() -> Optional[Dict[str, Any]]:- """Best-effort pull (curator tick sites: gateway housekeeping + CLI startup).- Never raises."""+ """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]:- """Status snapshot for ``hermes sync status``. Never raises.- ``org_available`` False means the account isn't in a shared organisation- (the org workflow does not apply), not that anything is broken."""+ """Status snapshot for ``hermes sync status``. Never raises. ``org_available`` False means the+ account isn't in a shared organisation (org workflow does not apply), not that anything is broken."""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")))@@ -699,8 +647,8 @@ def sync_status() -> Dict[str, Any]:return status-# Org-shared skills live in skills_sync_client_org; imported last because that-# module reads this module's state lazily.+# Org-shared skills live in skills_sync_client_org; imported last because that module reads+# this module's state lazily.from tools.skills_sync_client_org import ( # noqa: E402,F401 (re-exports)ORG_DIR_NAME, _ORG_CAS_MAX_ATTEMPTS, _clear_active_org_marker, _org_baseline_path,_read_org_baseline, _read_org_head, _skill_dir_fingerprint, _write_active_org_marker,diff --git a/tools/skills_sync_client_org.py b/tools/skills_sync_client_org.pyindex 3994a1c6e8c..a66d3cb6adc 100644--- a/tools/skills_sync_client_org.py+++ b/tools/skills_sync_client_org.py@@ -1,13 +1,12 @@"""Org-shared skills: org pull + propose (``~/.hermes/skills/_org/<org_id>/``).-Org skills live under 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`` -- the SAME object model as personal sync.-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 (automation will drive it).-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.+Org skills live under 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`` -- the SAME+object model as personal sync. 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 (automation will drive it). 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@@ -29,8 +28,8 @@ 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.+# 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@@ -45,11 +44,8 @@ def org_head_ref(org_id: str) -> str:def resolve_org_identity() -> Dict[str, Any]:- """``resolve_identity()`` extended with ``org_id`` + ``org_role``.-- Raises SyncInertError when the token carries no ``org_role`` claim (personal- org / issuer predates org support): org sync is unavailable, NOT an error.- """+ """``resolve_identity()`` extended with ``org_id`` + ``org_role``. Raises SyncInertError when+ the token carries no ``org_role`` claim (personal org / old issuer): unavailable, NOT an error."""from tools.skills_sync_client import SyncInertError, resolve_identityidentity = resolve_identity()@@ -66,8 +62,8 @@ def resolve_org_identity() -> Dict[str, Any]:def _org_client(identity: Optional[Dict[str, Any]], client: Optional[SyncClient]):- """Resolve (identity, client, caps) for an org operation; raises SyncInertError- when the base URL is missing or the server lacks the ``org`` feature."""+ """(identity, client, caps) 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:@@ -104,8 +100,8 @@ def _write_sidecar(what: str, path_fn: Callable[[], Path], text: str) -> None:def _skill_dir_fingerprint(path: Path) -> str:- """Stable content hash of a materialized skill dir (sorted relative path +- bytes, independent of filesystem order and mtimes). "" on read failure."""+ """Stable content hash of a materialized skill dir (sorted relative path + bytes,+ independent of filesystem order and mtimes). "" on read failure."""h = hashlib.sha256()try:for f in sorted(p for p in path.rglob("*") if p.is_file()):@@ -139,15 +135,11 @@ def _read_org_baseline(org_id: str) -> Dict[str, Any]:def _write_org_baseline(org_id: str, baseline: Dict[str, Any]) -> None:- _write_sidecar(- "baseline", lambda: _org_baseline_path(org_id), json.dumps(baseline, indent=2, sort_keys=True)- )+ _write_sidecar("baseline", lambda: _org_baseline_path(org_id), 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)- )+ _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:@@ -170,9 +162,8 @@ def _clear_active_org_marker() -> None:def org_skill_is_locally_modified(skill_rel_path: str, org_id: str) -> bool:- """True when the local copy of an org skill differs from what upstream sent.- No recorded baseline (pre-existing mirror) => unmodified; the next pull- records one."""+ """True when the local copy of an org skill differs from what upstream sent. No recorded+ baseline (pre-existing mirror) => unmodified; the next pull records one."""dest = _mirror_root(org_id) / PurePosixPath(skill_rel_path)if not dest.is_dir():return False@@ -218,10 +209,9 @@ def list_org_skill_names() -> List[str]:def pull_org_skills(client: Optional[SyncClient] = None, *, identity: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:- """Pull the org canonical set into the local mirror (fast-forward only; no- client merge on the org path). A mirrored skill with LOCAL edits is never- clobbered: it is skipped, and reported in ``conflicted`` when upstream also- moved; the member's change of record is ``propose_skill``.+ """Pull the org canonical set into the local mirror (fast-forward only; no client merge on+ the org path). A mirrored skill with LOCAL edits is never clobbered: skipped, and reported+ in ``conflicted`` when upstream also moved; the member's change of record is ``propose_skill``.Returns ``{ok, org_id, head, updated, conflicted}``."""identity = identity or resolve_org_identity()if "org_id" not in identity:@@ -230,16 +220,14 @@ def pull_org_skills(org_id = identity["org_id"]head = _read_org_head(client, org_id)- # Token-gated marker: written HERE because this runs only after the token's- # org_id + org_role were verified. A stale mirror from a previous org stops- # resolving the moment a pull runs under a different org.+ # Token-gated marker: written HERE because this runs only after the token's org_id + org_role+ # were verified. 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)skill_trees = skill_trees_of_root(client, head_commit["tree"], org_scope=True)-dest_root = _mirror_root(org_id)updated: List[str] = []conflicted: List[str] = []@@ -259,8 +247,8 @@ def pull_org_skills(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.+ # 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", ""),@@ -284,16 +272,13 @@ def propose_skill() -> Dict[str, Any]:"""Propose a local (personal) skill's content to the org canonical set.- Snapshots the skill dir as an org-scoped commit splicing that ONE skill- subtree into the current org HEAD (proposals are per-skill deltas, never a- wholesale replace), uploads with ``?scope=org``, then CAS-es the org HEAD:- ADMIN/OWNER -> server merges -> ``{ok, merged: True}``; MEMBER -> 202- proposal -> ``{ok, proposal_pending: True, proposal_id, ref}``, never- presented as live.-- If HEAD moves between read and CAS, the skill is re-spliced onto the NEW- head (not replayed from the old root, which would drop the other member's- skill) up to ``_ORG_CAS_MAX_ATTEMPTS`` times.+ Snapshots the skill dir as an org-scoped commit splicing that ONE skill subtree into the+ current org HEAD (proposals are per-skill deltas, never a wholesale replace), uploads with+ ``?scope=org``, then CAS-es the org HEAD: ADMIN/OWNER -> server merges -> ``{ok, merged:+ True}``; MEMBER -> 202 proposal -> ``{ok, proposal_pending: True, proposal_id, ref}``, never+ presented as live. If HEAD moves between read and CAS the skill is re-spliced onto the NEW+ head (not replayed from the old root, which would drop the other member's skill) up to+ ``_ORG_CAS_MAX_ATTEMPTS`` times."""ssc = _ssc()identity, client, caps = _org_client(identity, client)@@ -309,13 +294,11 @@ def propose_skill(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 = (skill_trees_of_root(client, root_tree_of_commit(client, base_head, org_scope=True), org_scope=True)- if base_head- else {}+ if base_head else {})skill_map[str(rel)] = skill_treeroot_hash = assemble_root_from_skill_trees(skill_map, objects)@@ -335,30 +318,22 @@ def propose_skill("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- )+ 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,- }+ 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 (logged in, org_role claim,- feature enabled, base URL). Never raises; None when inert.-- Marker hygiene: when the token VERIFIABLY lacks the org claim (personal org- / left the org) the active-org marker is cleared so mirrored org skills stop- resolving. When identity cannot be resolved at all (offline, logged out) the- marker is left alone -- offline grace keeps pulled org skills working.- """+ """Best-effort org pull if all gates hold (logged in, org_role claim, feature enabled, base+ URL). Never raises; None when inert. Marker hygiene: when the token VERIFIABLY lacks the org+ claim (personal org / left the org) the active-org marker is cleared so mirrored org skills+ stop resolving; when identity cannot be resolved at all (offline, logged out) the marker is+ left alone -- offline grace keeps pulled org skills working."""ssc = _ssc()try:identity = resolve_org_identity()diff --git a/tools/skills_sync_client_wire.py b/tools/skills_sync_client_wire.pyindex ea1bf5bf19c..d7ee3586be1 100644--- a/tools/skills_sync_client_wire.py+++ b/tools/skills_sync_client_wire.py@@ -1,11 +1,9 @@"""Skill Sync wire model: content-addressed objects, the HTTP client, tree walks.-Everything here is 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".+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@@ -35,35 +33,32 @@ MODE_DIR = "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`: 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"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).+# 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:<64-hex>`` -- the wire address of ``data``."""+ """``sha256:<64-hex>`` -- the wire address of ``data``."""return "sha256:" + hashlib.sha256(data).hexdigest()def canonical_json_bytes(obj: Dict[str, Any]) -> bytes:- """Canonical JSON for tree/commit hashing: UTF-8, sorted keys, no whitespace,- no trailing newline. Arrays must already be in contract order (tree entries- by name, commit parents by significance). Client and server MUST produce- byte-identical output or a push fails ``422 hash_mismatch``."""+ """Canonical JSON for tree/commit hashing: UTF-8, sorted keys, no whitespace, no trailing+ newline. Arrays must already be in contract order (tree entries by name, commit parents by+ significance). 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:- """Serialize ``{name: enabled}`` into canonical ``sync-manifest`` bytes- (entries sorted by name for a stable content address)."""+ """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())],@@ -72,20 +67,15 @@ def build_sync_manifest_bytes(skills: Dict[str, bool]) -> bytes:def parse_sync_manifest(data: bytes) -> Optional[Dict[str, bool]]:"""Parse ``sync-manifest`` bytes into ``{name: enabled}``, or None if malformed.-- Strict (mirrors gateway-gateway ``parseSyncManifest``): unknown type, version- != 1, non-list skills, or a malformed entry all reject -- a malformed- manifest must not be mistaken for "no skills opted in".- """+ Strict (mirrors gateway-gateway ``parseSyncManifest``): unknown type, version != 1, non-list+ skills or a malformed entry all reject -- a bad manifest must not read as "nothing opted in"."""try:value = json.loads(data.decode("utf-8"))except Exception:return Noneif (- 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)+ 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 Noneout: Dict[str, bool] = {}@@ -135,10 +125,9 @@ def _file_mode(path: Path) -> str:def build_tree(dir_path: Path, objects: ObjectSet, *, max_object_bytes: int) -> str:- """Recursively build objects for *dir_path*; return the tree address. Files- -> blobs, subdirs -> nested trees; symlinks/special files are skipped- (contract: no symlinks). A blob over *max_object_bytes* raises ValueError- so the caller can surface / skip the artifact (server -> 413)."""+ """Recursively build objects for *dir_path*; return the tree address. Files -> blobs, subdirs+ -> nested trees; symlinks/special files are skipped (contract: no symlinks). A blob over+ *max_object_bytes* raises ValueError so the caller can surface / skip the artifact (server -> 413)."""entries: List[Dict[str, str]] = []for child in sorted(dir_path.iterdir(), key=lambda p: p.name):if child.is_symlink():@@ -149,9 +138,7 @@ def build_tree(dir_path: Path, objects: ObjectSet, *, max_object_bytes: int) ->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}"- )+ 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)@@ -160,11 +147,8 @@ def build_commit(tree_hash: str, parents: List[str], *, owner: str, device: str, message: str,objects: ObjectSet, ts: Optional[str] = None,) -> str:- """Build a commit object and return its address.-- ``parents``: 0 for the first commit, 1 for an edit, 2 for a merge (order- significant: parents[0] = base fast-forwarded from, parents[1] = other head).- """+ """Build a commit object and return its address. ``parents``: 0 for the first commit, 1 for+ an edit, 2 for a merge (parents[0] = base fast-forwarded from, parents[1] = other head)."""return objects.add(KIND_COMMIT, canonical_json_bytes({"type": KIND_COMMIT, "tree": tree_hash, "parents": list(parents),"author": {"owner": owner, "device": device},@@ -175,10 +159,8 @@ def build_commit(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`` (top level only) adds the root ``sync-manifest`` BLOB entry.- It cannot collide with a skill dir: skill entries are trees, this is a blob.- """+ ``manifest_hash`` (top level only) adds the root ``sync-manifest`` BLOB entry; it cannot+ collide with a skill dir because skill entries are trees."""entries: List[Dict[str, str]] = []for name, child in node.items():if isinstance(child, dict) and "__tree__" in child and len(child) == 1:@@ -199,11 +181,8 @@ def nest_skill_tree(root: Dict[str, Any], rel_parts: Tuple[str, ...], tree_hash:def assemble_root_from_skill_trees(skill_trees: Dict[str, str], objects: ObjectSet) -> str:- """Build a profile-root tree from ``{posix_rel_path: tree_hash}``.-- The skill trees are assumed already durable (they came from either side of- a merge / the org HEAD); only the new intermediate/root trees are added.- """+ """Profile-root tree from ``{posix_rel_path: tree_hash}``. The skill trees are assumed already+ durable (either side of a merge / the org HEAD); 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)@@ -221,19 +200,14 @@ class SyncError(RuntimeError):class SyncConflict(RuntimeError):- """CAS lost (409). NOT a rejection -- pushed objects are already durable.-- ``actual`` is the current head to merge against, or None when the ref does- not exist server-side (the server sends ""). None means "retry as a create";- it must never be fetched as an object -- normalized here, not per call site.- """+ """CAS lost (409). NOT a rejection -- pushed objects are already durable. ``actual`` is the+ current head to merge against, or None when the ref does not exist server-side (the server+ sends ""): "retry as a create"; it must never be fetched as an object -- normalized here."""def __init__(self, actual: Optional[str]):self.actual: Optional[str] = actual or Nonesuper().__init__(- f"CAS conflict; actual head {self.actual}"- if self.actual- else "CAS conflict; the ref does not exist yet"+ f"CAS conflict; actual head {self.actual}" if self.actual else "CAS conflict; the ref does not exist yet")@@ -247,13 +221,16 @@ def _check_version(caps: Dict[str, Any]) -> None:)+def _body(r) -> Dict[str, Any]:+ return r.json() if r.content else {}++class SyncClient:"""Sync client bound to a base URL + Nous bearer.- Org refs/objects live behind SEPARATE ``org/`` routes, not a prefix filter:- the personal routes are hard-scoped to the token's owner and would silently- answer an org query with personal data. Callers reading org content MUST- pass ``org_scope=True`` on every hop.+ Org refs/objects live behind SEPARATE ``org/`` routes, not a prefix filter: the personal+ routes are hard-scoped to the token's owner and would silently answer an org query with+ personal data. Callers reading org content MUST pass ``org_scope=True`` on every hop."""def __init__(self, base_url: str, api_key: str, *, timeout: float = 30.0):@@ -268,39 +245,33 @@ class SyncClient:def _url(self, path: str) -> str:return f"{self.base}/v1/sync/{path.lstrip('/')}"- @staticmethod- def _check(r, op: str, ok=(200,), errors: Optional[Dict[int, str]] = None) -> None:- """Raise SyncError unless the status is in *ok*; *errors* maps specific- statuses to their message, anything else gets ``"<op> failed: <code>"``."""+ def _request(self, method: str, path: str, op: str, *, ok=(200,), errors: Optional[Dict[int, Any]] = None, **kw):+ """One wire call. Raises SyncError unless the status is in *ok*; *errors* maps specific+ statuses to a message (str or ``fn(response)``), anything else gets ``"<op> failed: <code>"``."""+ r = self._session.request(method, self._url(path), timeout=self.timeout, **kw)if r.status_code in ok:- return+ return rmsg = (errors or {}).get(r.status_code)+ if callable(msg):+ msg = msg(r)raise SyncError(msg or f"{op} failed: {r.status_code}", status=r.status_code)def capabilities(self) -> Dict[str, Any]:"""GET capabilities (no auth required)."""- r = self._session.get(self._url("capabilities"), timeout=self.timeout)- self._check(r, "capabilities")- return r.json()+ 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 = "org/refs" if org_scope else "refs"- params = None if org_scope else {"prefix": prefix}- r = self._session.get(self._url(path), params=params, timeout=self.timeout)- self._check(r, "get_refs")- refs = (r.json() or {}).get("refs", [])+ 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", [])if org_scope:refs = [r_ for r_ in refs if str(r_.get("name", "")).startswith(prefix)]return refsdef get_object(self, obj_hash: str, *, org_scope: bool = False) -> Tuple[str, bytes]:- """GET objects/:hash -> ``(kind, bytes)``. Kind comes from the object-type- header; a blob (octet-stream) is returned as ``blob``."""- path = f"org/objects/{obj_hash}" if org_scope else f"objects/{obj_hash}"- r = self._session.get(self._url(path), timeout=self.timeout)- self._check(- r, "get_object",+ """GET objects/:hash -> ``(kind, bytes)``; kind from the object-type header, blob default."""+ r = self._request(+ "GET", f"org/objects/{obj_hash}" if org_scope else f"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@@ -318,39 +289,32 @@ class SyncClient: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 -- batch upload as multipart/form-data: field name = the- claimed ``sha256:<hex>``, ``filename`` = object type, body = raw bytes- (the contract requires raw bytes, not base64-in-JSON). The server- recomputes every hash and rejects the whole batch with 422 on mismatch;- known hashes are idempotent no-ops. ``org_scope`` adds ``?scope=org`` so- objects land org-readable (required before an org CAS/propose)."""+ """POST objects -- batch multipart upload: field name = the claimed ``sha256:<hex>``,+ ``filename`` = object type, body = raw bytes (the contract forbids base64-in-JSON). The+ server recomputes every hash and rejects the whole batch with 422 on mismatch; known+ hashes are idempotent no-ops. ``org_scope`` adds ``?scope=org`` so objects land+ org-readable (required before an org CAS/propose)."""files = [(h, (kind, data, "application/octet-stream")) for h, (kind, data) in objects.items()]- r = self._session.post(- self._url("objects"), files=files, params={"scope": "org"} if org_scope else None, timeout=self.timeout- )- self._check(- r, "put_objects", ok=(200, 201),- errors={413: "object too large (413)", 422: f"hash_mismatch (422): {r.text}"},+ r = 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}"},)- return r.json() if r.content else {}+ return _body(r)def cas_ref(self, name: str, from_hash: Optional[str], to_hash: str) -> Dict[str, Any]:- """POST refs/:name -- atomic compare-and-swap. Raises SyncConflict on 409.-- A non-admin member's CAS on an org HEAD is converted server-side to a- proposal (202) and surfaced as ``{"proposal_pending": True, ...}``: a- SUCCESS-shaped outcome that must never be presented as live/merged.- """- r = self._session.post(- self._url(f"refs/{name}"), json={"from": from_hash, "to": to_hash}, timeout=self.timeout+ """POST refs/:name -- atomic compare-and-swap. Raises SyncConflict on 409. A non-admin+ member's CAS on an org HEAD is converted server-side to a proposal (202) and surfaced as+ ``{"proposal_pending": True, ...}``: SUCCESS-shaped but never to be presented as live/merged."""+ 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, **(r.json() if r.content else {})}- if r.status_code == 409:- # "" actual = the ref does not exist server-side (SyncConflict -> None).+ 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", ""))- self._check(r, "cas_ref", errors={403: "forbidden (403) -- owner/permission"})- return r.json() if r.content else {}+ return _body(r)# Reading remote trees@@ -366,9 +330,8 @@ def root_tree_of_commit(client: SyncClient, commit_hash: str, *, org_scope: booldef skill_trees_of_root(client: SyncClient, root_tree_hash: str, *, org_scope: bool = False) -> Dict[str, str]:- """Flatten a profile-root tree into ``{posix_rel_path: skill_tree_hash}``. A- skill tree is any subtree containing a ``SKILL.md`` blob, keyed by its path- so category nesting is preserved."""+ """Flatten a profile-root tree into ``{posix_rel_path: skill_tree_hash}``: a skill tree is any+ subtree containing a ``SKILL.md`` blob, keyed by its path so category nesting is preserved."""result: Dict[str, str] = {}def _walk(tree_hash: str, prefix: str) -> None:@@ -385,8 +348,8 @@ def skill_trees_of_root(client: SyncClient, root_tree_hash: str, *, org_scope: bdef read_manifest_of_root(client: SyncClient, root_tree_hash: str) -> Optional[Dict[str, bool]]:- """``{name: enabled}`` from the root-level ``sync-manifest`` blob, or None if- absent/malformed. This is how a device learns another device's opt-ins."""+ """``{name: enabled}`` from the root-level ``sync-manifest`` blob, or None if absent/malformed.+ This is how a device learns another device's opt-ins."""try:tree = client.get_tree_json(root_tree_hash)except Exception as e:@@ -404,9 +367,9 @@ def read_manifest_of_root(client: SyncClient, root_tree_hash: str) -> Optional[Ddef materialize_tree(client: SyncClient, tree_hash: str, dest: Path, *, org_scope: bool = False) -> None:- """Write the tree at *tree_hash* into *dest* (created if needed): blobs ->- files (+x restored for ``exec``), trees -> subdirectories. Does NOT delete- files absent from the tree (caller decides). Refuses path traversal."""+ """Write the tree at *tree_hash* into *dest* (created if needed): blobs -> files (+x restored+ for ``exec``), trees -> subdirectories. 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", "")@@ -426,10 +389,9 @@ def materialize_tree(client: SyncClient, tree_hash: str, dest: Path, *, org_scopdef merge_skill(base: Optional[str], ours: Optional[str], theirs: Optional[str]) -> str:- """Three-way decision for one skill's tree hash: ``ours`` / ``theirs`` /- ``either`` / ``overlap`` / ``none``. A side "modified" the skill when its- hash differs from the common base (same semantics as skills_sync.py's- origin/user/incoming block)."""+ """Three-way decision for one skill's tree hash: ``ours`` / ``theirs`` / ``either`` / ``overlap``+ / ``none``. A side "modified" the skill when its hash differs from the common base (same+ semantics as skills_sync.py's origin/user/incoming block)."""if ours == theirs:return "either" if ours is not None else "none"if theirs == base: # only we moved