Skip to content

The agent that grows with you

refactor(tools): collapse sync-state/device-id/sidecar helpers, fold boolean ladders

Teknium1c389c655e1d
diff --git a/tools/skills_sync_client.py b/tools/skills_sync_client.py
index f4e784794ce..858bbc1f465 100644
--- a/tools/skills_sync_client.py
+++ b/tools/skills_sync_client.py
@@ -54,9 +54,8 @@ def resolve_identity() -> Dict[str, Any]:
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}
+ 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:
@@ -247,12 +246,10 @@ def _default_device_label() -> str:
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."""
- path = _skills_dir() / ".sync_device_id"
with suppress(OSError):
- if path.exists():
- val = path.read_text(encoding="utf-8").strip()
- if val:
- return val
+ val = _device_id_path().read_text(encoding="utf-8").strip()
+ if val:
+ return val
val = (os.environ.get("HERMES_SYNC_DEVICE_NAME") or "").strip() or _default_device_label()
try:
_write_device_id(val)
@@ -261,10 +258,13 @@ def stable_device_id() -> str:
return val
+def _device_id_path() -> Path:
+ return _skills_dir() / ".sync_device_id"
+
+
def _write_device_id(val: str) -> None:
- path = _skills_dir() / ".sync_device_id"
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(val, encoding="utf-8")
+ _device_id_path().parent.mkdir(parents=True, exist_ok=True)
+ _device_id_path().write_text(val, encoding="utf-8")
def set_device_name(name: str) -> str:
@@ -293,11 +293,7 @@ def _load_state_file(path: Path, what: str = "sync state read") -> Optional[Dict
except (OSError, json.JSONDecodeError) as e:
logger.debug("skills_sync_client: %s failed: %s", what, e)
return None
- if not isinstance(data, dict):
- return None
- data.setdefault("head", None)
- data.setdefault("skills", {})
- return data
+ return {**_EMPTY_STATE, **data} if isinstance(data, dict) else None
def read_sync_state() -> Dict[str, Any]:
@@ -307,30 +303,26 @@ def read_sync_state() -> Dict[str, Any]:
if path.exists():
return _load_state_file(path) or dict(_EMPTY_STATE)
legacy = _skills_dir() / ".sync_manifest"
- if legacy.exists():
- data = _load_state_file(legacy, "legacy sync state migrate")
- if data is not None:
- write_sync_state(data)
- with suppress(OSError):
- legacy.unlink()
- return data
- return 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 tools.skill_usage import _atomic_write
- _atomic_write(
- _sync_state_path(), ".sync_state_",
- lambda f: json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False))
+ _atomic_write(_sync_state_path(), ".sync_state_",
+ lambda f: json.dump(data, f, indent=2, sort_keys=True, ensure_ascii=False))
except Exception as e:
logger.debug("skills_sync_client: sync state write failed: %s", e)
def _record_head(state: Dict[str, Any], head: str, root: str) -> None:
- state["head"] = head
- state["root"] = root
+ state.update(head=head, root=root)
write_sync_state(state)
@@ -527,10 +519,8 @@ def _gate_and_swallow(op: str, run: Callable[[Dict[str, Any]], Optional[Dict[str
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,
- )
+ 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]]:
diff --git a/tools/skills_sync_client_org.py b/tools/skills_sync_client_org.py
index c47d17cd82c..a8369f9721e 100644
--- a/tools/skills_sync_client_org.py
+++ b/tools/skills_sync_client_org.py
@@ -44,14 +44,12 @@ def resolve_org_identity() -> Dict[str, Any]:
from tools.skills_sync_client import SyncInertError, resolve_identity
identity = resolve_identity()
claims = identity.get("claims") or {}
- org_id = claims.get("org_id")
- org_role = claims.get("org_role")
+ org_id, org_role = claims.get("org_id"), claims.get("org_role")
if not org_id:
raise SyncInertError("no organisation associated with this account")
if not isinstance(org_role, str) or not org_role:
raise SyncInertError("this account isn't a member of a shared organisation")
- identity["org_id"] = str(org_id)
- identity["org_role"] = org_role
+ identity.update(org_id=str(org_id), org_role=org_role)
return identity
@@ -114,24 +112,22 @@ def _sidecar_path(org_id: Optional[str], const: str) -> Path:
return (_mirror_root(org_id) if org_id else _ssc()._org_dir()) / getattr(sku, const)
-def _org_baseline_path(org_id: str) -> Path:
- """Sidecar recording the upstream fingerprint of each mirrored skill."""
- return _sidecar_path(org_id, "ORG_BASELINE_FILE")
-
-
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(_org_baseline_path(org_id).read_text(encoding="utf-8"))
+ return json.loads(_sidecar_path(org_id, "ORG_BASELINE_FILE").read_text(encoding="utf-8"))
except Exception:
return {}
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: _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))
+ _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:
@@ -145,9 +141,8 @@ def _clear_active_org_marker() -> None:
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")
+ 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)
@@ -242,9 +237,8 @@ def pull_org_skills(client: Optional[SyncClient] = None, *, identity: Optional[D
})
_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))
+ 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}
@@ -271,9 +265,8 @@ def propose_skill(skill_name: str, client: Optional[SyncClient] = None, *,
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 {})
+ 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(
@@ -286,19 +279,15 @@ def propose_skill(skill_name: str, client: Optional[SyncClient] = None, *,
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
+ 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, "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}
diff --git a/tools/tirith_security.py b/tools/tirith_security.py
index 4089d959164..2f775d098b1 100644
--- a/tools/tirith_security.py
+++ b/tools/tirith_security.py
@@ -150,12 +150,10 @@ def _is_install_failed_on_disk() -> bool:
"""True if a recent install failure was persisted and is still non-retryable.
A 'cosign_missing' marker is auto-cleared once cosign appears on PATH."""
reason = _read_failure_reason()
- if reason is None:
- return False
if reason == "cosign_missing" and shutil.which("cosign"):
_clear_install_failed()
return False
- return True
+ return reason is not None
def _mark_install_failed(reason: str = ""):
@@ -284,8 +282,7 @@ def _verify_checksum(archive_path: str, checksums_path: str, archive_name: str)
actual = sha.hexdigest()
if actual != expected:
logger.warning("Checksum mismatch: expected %s, got %s", expected, actual)
- return False
- return True
+ return actual == expected
def _extract_tirith_binary(tar: tarfile.TarFile, dest_dir: str, log) -> tuple[str | None, str]: