The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): squeeze in-function blanks; scan scope check first
Tekniume234d40d0e4c
diff --git a/tools/skills_sync_client.py b/tools/skills_sync_client.pyindex 086b9e4503b..a4d79669ad0 100644--- a/tools/skills_sync_client.py+++ b/tools/skills_sync_client.py@@ -357,7 +357,6 @@ def push_skills(client: Optional[SyncClient] = None, *, skill_names: Optional[Liskill_names = list_synced_skill_names() if skill_names is None else skill_namesif 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()@@ -365,7 +364,6 @@ def push_skills(client: Optional[SyncClient] = None, *, skill_names: Optional[Li# 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)@@ -392,7 +390,6 @@ def _resolve_push_conflict(client: SyncClient, identity: Dict[str, Any], actual_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):@@ -405,7 +402,6 @@ def _resolve_push_conflict(client: SyncClient, identity: Dict[str, Any], actual_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@@ -416,7 +412,6 @@ def _resolve_push_conflict(client: SyncClient, identity: Dict[str, Any], actual_"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.update(objects.objects)@@ -459,7 +454,6 @@ def pull_skills(client: Optional[SyncClient] = None, *, identity: Optional[Dict[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))@@ -510,11 +504,8 @@ def sync_status() -> Dict[str, Any]:passexcept Exception as e:logger.debug("skills_sync_client: sync_status identity failed: %s", e)- try:- status["opted_in_skills"] = list_synced_skill_names()- status["local_head"] = read_sync_state().get("head")- except Exception:- pass+ with suppress(Exception):+ status.update(opted_in_skills=list_synced_skill_names(), 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"),diff --git a/tools/skills_sync_client_org.py b/tools/skills_sync_client_org.pyindex ac98389ccc6..100c127b6c4 100644--- a/tools/skills_sync_client_org.py+++ b/tools/skills_sync_client_org.py@@ -202,7 +202,6 @@ def pull_org_skills(client: Optional[SyncClient] = None, *, identity: Optional[D_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)@@ -247,14 +246,12 @@ def propose_skill(skill_name: str, client: Optional[SyncClient] = None, *,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() / relif 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):@@ -278,7 +275,6 @@ def propose_skill(skill_name: str, client: Optional[SyncClient] = None, *,"the race — run the command again", status=409) from conflictlogger.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}diff --git a/tools/skills_sync_client_wire.py b/tools/skills_sync_client_wire.pyindex 367942fbd82..aba2d8ff5b8 100644--- a/tools/skills_sync_client_wire.py+++ b/tools/skills_sync_client_wire.py@@ -303,7 +303,6 @@ 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]:"""``{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):diff --git a/tools/threat_patterns.py b/tools/threat_patterns.pyindex dffeaee1afc..e43649d1412 100644--- a/tools/threat_patterns.py+++ b/tools/threat_patterns.py@@ -116,15 +116,14 @@ def scan_for_threats(content: str, scope: str = "context") -> List[str]:reported as ``"invisible_unicode_U+XXXX"``. Raises ValueError on an unknown scope."""if not content:return []+ if (patterns := _COMPILED.get(scope)) is None:+ raise ValueError(f"scan_for_threats: unknown scope {scope!r}")content = content[:MAX_SCAN_CHARS]# Invisible unicode is checked on the RAW content: NFKC below can strip these codepoints.findings: List[str] = [f"invisible_unicode_U+{ord(ch):04X}" for ch in set(content) & INVISIBLE_CHARS]# NFKC folds full-width / compatibility variants (cat → cat) against homograph bypass.# It does NOT fold cross-script confusables (Cyrillic ``а``) — that needs a TR#39 database.normalised = unicodedata.normalize("NFKC", content)- patterns = _COMPILED.get(scope)- if patterns is None:- raise ValueError(f"scan_for_threats: unknown scope {scope!r}")findings.extend(pid for compiled, pid in patterns if compiled.search(normalised))return findings@@ -138,10 +137,9 @@ def first_threat_message(content: str, scope: str = "strict") -> Optional[str]:if pid.startswith("invisible_unicode_"):codepoint = pid.replace("invisible_unicode_", "")return f"Blocked: content contains invisible unicode character {codepoint} (possible injection)."- return (- f"Blocked: content matches threat pattern '{pid}'. "- f"Content is injected into the system prompt and must not contain "- f"injection or exfiltration payloads.")+ return (f"Blocked: content matches threat pattern '{pid}'. "+ f"Content is injected into the system prompt and must not contain "+ f"injection or exfiltration payloads.")__all__ = ["INVISIBLE_CHARS", "MAX_SCAN_CHARS", "scan_for_threats", "first_threat_message"]diff --git a/tools/tirith_security.py b/tools/tirith_security.pyindex cea68148dca..aa83ea538d0 100644--- a/tools/tirith_security.py+++ b/tools/tirith_security.py@@ -507,7 +507,6 @@ def check_command_security(command: str) -> dict:except subprocess.TimeoutExpired:_warn_once(f"tirith_timeout:{timeout}", "tirith timed out after %ds", timeout)return _crash(fail_open, f"tirith timed out ({timeout}s)", "tirith timed out (fail-closed)")-exit_code = result.returncodeif (action := _EXIT_ACTIONS.get(exit_code)) is None:# Unknown exit code (includes signal-killed, e.g. -11): respect fail_open.