Skip to content

The agent that grows with you

feat(skills): a locked skill can't be changed by the agent through any write path

Teknium91c51e04f457
diff --git a/agent/curator.py b/agent/curator.py
index 439d1d83484..b3f64cb3448 100644
--- a/agent/curator.py
+++ b/agent/curator.py
@@ -227,7 +227,7 @@ def apply_automatic_transitions(now: Optional[datetime] = None) -> dict[str, int
for row in _u.curated_report():
counts["checked"] += 1
name = row["name"]
- if row.get("pinned") or name in protected:
+ if row.get("pinned") or row.get("locked") or name in protected:
continue
# First sight with no persisted record: anchor its clock to now and defer.
if not row.get("_persisted", True):
diff --git a/hermes_cli/curator.py b/hermes_cli/curator.py
index 2e8ccbdaf5d..2bb7681ab2c 100644
--- a/hermes_cli/curator.py
+++ b/hermes_cli/curator.py
@@ -107,7 +107,7 @@ def _cmd_status(args) -> int:
_print_curator_config(curator)
if locked := skill_usage.locked_skill_names():
print(f"\nlocked ({len(locked)}): {', '.join(locked)} "
- f"(autonomous content writes refused; `hermes curator unlock <skill>` lifts it)")
+ f"(the agent cannot change these; `hermes curator unlock <skill>` lifts it)")
rows = skill_usage.curated_report()
if not rows:
print("\nno curator-managed skills")
@@ -242,9 +242,8 @@ def _cmd_unpin(args) -> int: return _set_pin(args, False)
def _set_lock(args, locked: bool) -> int:
"""``hermes curator lock|unlock``: a user declaration stored beside ``pinned`` in the active
- profile's skills/.usage.json. Not restricted to agent-created skills — hand-written skills are
- the main thing people lock — but the name must resolve in this profile, so a typo never forges a
- record for a skill that does not exist."""
+ profile's skills/.usage.json, enforced by tools/skill_lock on every agent write path. Any skill
+ can be locked, but the name must resolve in this profile, so a typo never forges a record."""
from tools import skill_usage
from tools.skill_manager_tool import _find_skill
verb = "lock" if locked else "unlock"
@@ -258,12 +257,12 @@ def _set_lock(args, locked: bool) -> int:
print(f"curator: could not record the {verb} for '{key}' (skills/.usage.json not writable).")
return 1
if locked:
- print(f"curator: locked '{key}' — the background review and curator passes can no longer patch, "
- f"edit, write or remove files in it, or delete it (skill_manage refuses; the skill stays "
- f"readable, listed and auto-loadable). Edits you ask for in a normal turn and your own "
- f"editor are unaffected. Unlock with `hermes curator unlock {key}`.")
+ print(f"curator: locked '{key}'. The agent can no longer change it: skill_manage, write_file, "
+ f"patch and terminal refuse, in normal turns and the background passes alike, and the "
+ f"curator won't archive it. It stays readable and auto-loadable, and you can still edit it "
+ f"yourself. Unlock with `hermes curator unlock {key}`.")
else:
- print(f"curator: unlocked '{key}' — the autonomous passes may improve it again.")
+ print(f"curator: unlocked '{key}'. The agent may edit it again.")
return 0
@@ -680,9 +679,8 @@ _SUBCOMMANDS = (
("resume", "Resume a paused curator", _cmd_resume),
("pin", "Pin a skill so the curator never auto-transitions it", _cmd_pin, _SKILL),
("unpin", "Unpin a skill", _cmd_unpin, _SKILL),
- ("lock", "Lock a skill's content against the background review and curator passes "
- "(skill_manage refuses their patch/edit/write_file/remove_file/delete; the skill stays "
- "readable and auto-loadable; edits you ask for are unaffected)", _cmd_lock, _SKILL),
+ ("lock", "Lock a skill so the agent cannot change it (skill_manage, write_file, patch and terminal "
+ "refuse; it stays readable and auto-loadable; your own edits are unaffected)", _cmd_lock, _SKILL),
("unlock", "Lift a content lock", _cmd_unlock, _SKILL),
("list-unmanaged", "List curation-eligible skills with no provenance marker",
_cmd_list_unmanaged),
diff --git a/tests/tools/test_skill_lock.py b/tests/tools/test_skill_lock.py
new file mode 100644
index 00000000000..af61287a157
--- /dev/null
+++ b/tests/tools/test_skill_lock.py
@@ -0,0 +1,63 @@
+"""A user skill lock holds on every agent write path: write_file, patch and terminal.
+
+skill_manage's side lives in test_skill_manager_tool.py::TestLockedGuard.
+"""
+
+import json
+
+import pytest
+
+
+def locked_home(tmp_path, monkeypatch):
+ home = tmp_path / "hh"
+ skills = home / "skills"
+ for rel in ("ops/locked-skill", "ops/free-skill"):
+ (skills / rel / "scripts").mkdir(parents=True)
+ (skills / rel / "SKILL.md").write_text(f"---\nname: {rel.split('/')[1]}\ndescription: x\n---\nbody\n")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ from tools import skill_usage
+ assert skill_usage.set_locked("locked-skill", True)
+ return home
+
+
+def test_file_tools_refuse_a_locked_skill_and_its_record(locked_home):
+ from tools.file_tools import patch_tool, write_file_tool
+ locked = locked_home / "skills/ops/locked-skill/SKILL.md"
+ free = locked_home / "skills/ops/free-skill/SKILL.md"
+ before = locked.read_text()
+
+ refused = [json.loads(write_file_tool(str(locked), "replaced\n")),
+ json.loads(patch_tool(path=str(locked), old_string="body", new_string="changed")),
+ json.loads(write_file_tool(str(locked.parent / "references/new.md"), "x\n")),
+ json.loads(write_file_tool(str(locked_home / "skills/.usage.json"), "{}\n"))]
+ allowed = json.loads(patch_tool(path=str(free), old_string="body", new_string="changed"))
+
+ for res in refused:
+ assert "locked" in res["error"], res
+ assert locked.read_text() == before
+ assert "error" not in allowed, allowed
+ assert "changed" in free.read_text()
+
+
[email protected]("command, blocked", [
+ ("echo x > {L}/SKILL.md", True),
+ ("sed -i s/a/b/ {L}/SKILL.md", True),
+ ("cd {L} && echo x > SKILL.md", True),
+ ("rm -rf {H}/skills/ops", True),
+ ("git -C {L} checkout -- .", True),
+ ("bash -c 'cp /etc/hosts {L}/SKILL.md'", True),
+ ("python3 -c \"open('{L}/SKILL.md','w').write('x')\"", True),
+ ("echo {{}} > {H}/skills/.usage.json", True),
+ ("hermes curator unlock locked-skill", True),
+ ("cat {L}/SKILL.md", False),
+ ("python3 {L}/scripts/run.py > {H}/out.log 2>&1", False),
+ ("cp {L}/SKILL.md {H}/copy.md", False),
+ ("echo x > {H}/skills/ops/free-skill/SKILL.md", False),
+ ("git -C {L} log --oneline", False),
+])
+def test_terminal_refuses_writes_into_a_locked_skill_but_not_reads(locked_home, command, blocked):
+ from tools.skill_lock import command_refusal
+ lock_dir = locked_home / "skills/ops/locked-skill"
+ reason = command_refusal(command.format(L=lock_dir, H=locked_home), str(locked_home))
+ assert (reason is not None) is blocked, reason
diff --git a/tests/tools/test_skill_manager_tool.py b/tests/tools/test_skill_manager_tool.py
index 5c46c80a540..8c52cdd923d 100644
--- a/tests/tools/test_skill_manager_tool.py
+++ b/tests/tools/test_skill_manager_tool.py
@@ -1464,16 +1464,20 @@ class TestLockedGuard:
assert lifted["success"] is True, lifted
assert "Do the new thing." in (locked / "SKILL.md").read_text()
- def test_foreground_write_to_locked_skill_goes_through(self, tmp_path, monkeypatch):
- """Documented: the lock gates autonomous origins only. A user-directed edit still lands."""
+ def test_foreground_mutations_are_refused_too(self, tmp_path, monkeypatch):
+ """The lock is the user's: a normal turn asking for the edit is refused like the review fork."""
from tools import skill_usage
skills = self._profile(tmp_path, monkeypatch)
with _skill_dir(skills):
d = self._make(skills, "locked-skill")
+ _create_skill("umbrella", VALID_SKILL_CONTENT)
assert skill_usage.set_locked("locked-skill", True)
- res = json.loads(skill_manage(name="locked-skill", **self._PATCH))
- assert res["success"] is True, res
- assert "Do the new thing." in (d / "SKILL.md").read_text()
+ before = self._tree(d)
+ results = [json.loads(skill_manage(name="locked-skill", **op)) for op in self._MUTATIONS]
+ after = self._tree(d)
+ for op, res in zip(self._MUTATIONS, results):
+ assert res["success"] is False and "hermes curator unlock locked-skill" in res["error"], (op, res)
+ assert after == before
def test_batch_refuses_before_any_sibling_op_is_applied(self, tmp_path, monkeypatch):
from tools import skill_usage
diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.py
index 1ef4aa8fe69..ea11d856cde 100644
--- a/tools/file_tools_write_guards.py
+++ b/tools/file_tools_write_guards.py
@@ -171,6 +171,9 @@ def _check_sensitive_path(filepath: str, task_id: str = "default") -> str | None
f"Refusing to write to Hermes config file: {filepath}\n"
"Agent cannot modify security-sensitive configuration. "
"Edit ~/.hermes/config.yaml directly or use 'hermes config' instead.")
+ from tools.skill_lock import path_refusal
+ if reason := path_refusal(candidates):
+ return f"Refusing to write to {filepath}: {reason}"
return None
diff --git a/tools/skill_lock.py b/tools/skill_lock.py
new file mode 100644
index 00000000000..1fbeba79892
--- /dev/null
+++ b/tools/skill_lock.py
@@ -0,0 +1,305 @@
+"""User skill locks, enforced on every agent write path.
+
+``hermes curator lock <skill>`` (or the Desktop lock switch) records ``locked: true`` beside
+``pinned`` in the profile's ``skills/.usage.json``. While a skill is locked the agent cannot change
+it: ``skill_manage`` refuses every mutating action, ``write_file``/``patch`` refuse any path inside
+the skill's directory, and ``terminal`` refuses commands that write there. The lock record itself
+is protected the same way, and the agent cannot run ``hermes curator unlock``. The user's own edits
+(Desktop editor, their own editor, the CLI) are not gated.
+
+The terminal check reads the command's write targets (redirections, tee, cp/mv/rm/sed -i and
+friends, git in the skill's tree, ``cd`` into it, inline interpreter code naming it). It is a
+policy check, not a sandbox: a script that writes there through its own logic is not seen.
+"""
+
+from __future__ import annotations
+
+import itertools
+import os
+import re
+import shlex
+from typing import Iterable
+
+# Verbs whose every path operand is written (or removed/renamed).
+_WRITES_EVERY_OPERAND = frozenset({
+ "rm", "rmdir", "unlink", "truncate", "shred", "touch", "chmod", "chown", "chgrp", "chattr",
+ "setfacl", "mkdir", "mv", "patch", "dos2unix", "unix2dos", "xattr", "ed", "ex", "vi", "vim",
+ "nvim", "nano", "emacs"})
+# Verbs that write only to their LAST operand (the destination).
+_WRITES_LAST_OPERAND = frozenset({"cp", "install", "ln", "rsync", "scp"})
+# Verbs that reach INTO a directory operand recursively, so an ancestor of a locked skill counts.
+_RECURSIVE = frozenset({"rm", "mv", "chmod", "chown", "chgrp", "chattr", "setfacl", "rsync", "find"})
+_INPLACE_EDITORS = frozenset({"sed", "perl", "ruby"})
+_GIT_MUTATIONS = frozenset({
+ "add", "am", "apply", "checkout", "clean", "commit", "merge", "mv", "pull", "rebase", "reset",
+ "restore", "revert", "rm", "stash", "switch", "cherry-pick"})
+_INTERPRETERS = re.compile(
+ r"^(?:python[0-9.]*|node|nodejs|deno|bun|ruby|perl|php|bash|sh|zsh|dash|ksh|pwsh|powershell)$")
+_WRAPPERS = frozenset({"sudo", "env", "command", "builtin", "exec", "nohup", "setsid", "time", "nice", "xargs"})
+_WRITEISH_CODE = re.compile(
+ r"open\s*\(|write|unlink|remove|rmtree|rename|replace|truncate|copy|move|chmod|mkdir|"
+ r"writeFile|appendFile|rmSync|>|sed\s+-i|\bmv\b|\brm\b|\bcp\b", re.IGNORECASE)
+_SEPARATORS = frozenset({";", "&", "&&", "|", "||", "(", ")", "|&", ";;"})
+
+
+def _skill_usage():
+ from tools import skill_usage
+ return skill_usage
+
+
+def locked_skill_dirs() -> list[tuple[str, str]]:
+ """``(name, realpath)`` of every locked skill that resolves in the active profile."""
+ names = _skill_usage().locked_skill_names()
+ if not names:
+ return []
+ from tools.skill_manager_tool import _find_skill
+ found = []
+ for name in names:
+ if hit := _find_skill(name):
+ found.append((name, os.path.realpath(hit["path"])))
+ return found
+
+
+def _record_path() -> str:
+ return os.path.realpath(_skill_usage()._usage_file())
+
+
+def _inside(path: str, root: str) -> bool:
+ return path == root or path.startswith(root.rstrip(os.sep) + os.sep)
+
+
+def skill_refusal(name: str) -> str:
+ return (f"Skill '{name}' is locked by the user, so the agent cannot change it: skill_manage, "
+ f"write_file, patch and terminal all refuse. Don't retry or work around it (no copying it "
+ f"under another name); tell the user what you would change. They can unlock it with "
+ f"`hermes curator unlock {name}` or the lock switch in Desktop.")
+
+
+RECORD_REFUSAL = ("skills/.usage.json holds the user's skill locks, so the agent cannot change it "
+ "while any skill is locked.")
+UNLOCK_REFUSAL = ("Only the user can unlock a skill. Ask them to run `hermes curator unlock <skill>` "
+ "themselves or use the lock switch in Desktop.")
+
+
+def _hit(path: str, locked: list[tuple[str, str]], record: str, *, ancestor: bool = False) -> str | None:
+ """Refusal text when *path* is the lock record, inside a locked skill, or (``ancestor``) above one."""
+ real = os.path.realpath(path)
+ if real == record:
+ return RECORD_REFUSAL
+ for name, root in locked:
+ if _inside(real, root) or (ancestor and real != os.sep and _inside(root, real)):
+ return skill_refusal(name)
+ return None
+
+
+def path_refusal(paths: Iterable[str]) -> str | None:
+ """write_file/patch guard: refusal text when any path lands in a locked skill or the lock record."""
+ locked = locked_skill_dirs()
+ if not locked:
+ return None
+ record = _record_path()
+ for path in paths:
+ if path and (reason := _hit(path, locked, record)):
+ return reason
+ return None
+
+
+# ── terminal ──────────────────────────────────────────────────────────────────────────────────
+
+def _expand(word: str, cwd: str) -> str:
+ """Shell word -> absolute path: ~, $HOME, $HERMES_HOME, then relative to *cwd*; glob tail dropped."""
+ from hermes_constants import get_hermes_home
+ home = os.path.expanduser("~")
+ for var, value in (("HERMES_HOME", str(get_hermes_home())), ("HOME", home)):
+ word = word.replace("${" + var + "}", value).replace("$" + var, value)
+ if word == "~" or word.startswith("~/"):
+ word = home + word[1:]
+ if any(ch in word for ch in "*?["): # a glob reaches everything under its literal prefix
+ word = word[: min(word.index(ch) for ch in "*?[" if ch in word)]
+ word = word.rsplit("/", 1)[0] or "/"
+ return os.path.normpath(os.path.join(cwd, word))
+
+
+def _tokens(command: str) -> list[str]:
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=";&|<>()")
+ lexer.whitespace_split = True
+ lexer.commenters = ""
+ try:
+ return list(lexer)
+ except ValueError: # unbalanced quotes: fall back to whitespace words
+ return command.split()
+
+
+def _segments(tokens: list[str]) -> Iterable[tuple[list[str], list[str]]]:
+ """Yield ``(argv, redirect_targets)`` per simple command."""
+ argv: list[str] = []
+ targets: list[str] = []
+ it = iter(tokens)
+ for tok in it:
+ if ">" in tok and set(tok) <= set("&>|0123456789"):
+ if not tok.endswith("&"):
+ target = next(it, "")
+ if target and not target.startswith("&") and target != "/dev/null":
+ targets.append(target)
+ continue
+ if tok in ("<", "<<", "<<<", "<<-"):
+ next(it, "") # input file / heredoc delimiter / here-string: read, never written
+ continue
+ if tok in _SEPARATORS or (tok and set(tok) <= set(";&|()")):
+ yield argv, targets
+ argv, targets = [], []
+ continue
+ argv.append(tok)
+ yield argv, targets
+
+
+def _strip_wrappers(argv: list[str]) -> list[str]:
+ while argv and (argv[0] in _WRAPPERS or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", argv[0])):
+ argv = argv[1:]
+ while argv and argv[0].startswith("-"):
+ argv = argv[1:]
+ return argv
+
+
+def _operands(args: list[str]) -> list[str]:
+ return [a for a in args if a and not a.startswith("-")]
+
+
+class _Scope:
+ """What a command is checked against: its working dir, the locked skills and the lock record."""
+
+ def __init__(self, cwd: str, locked: list[tuple[str, str]], record: str, depth: int) -> None:
+ self.cwd, self.locked, self.record, self.depth = cwd, locked, record, depth
+
+ def hit(self, word: str, ancestor: bool = False) -> str | None:
+ return _hit(_expand(word, self.cwd), self.locked, self.record, ancestor=ancestor)
+
+ def first_hit(self, words: Iterable[str], ancestor: bool = False) -> str | None:
+ return next((r for w in words if (r := self.hit(w, ancestor))), None)
+
+
+def _check_unlock(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if verb == "hermes" or (verb.startswith("python") and "hermes_cli.main" in args):
+ if "curator" in args and "unlock" in args[args.index("curator"):]:
+ return UNLOCK_REFUSAL
+ return None
+
+
+def _check_file_verbs(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if verb in _WRITES_EVERY_OPERAND or verb == "tee":
+ return scope.first_hit(_operands(args), ancestor=verb in _RECURSIVE)
+ if verb in _WRITES_LAST_OPERAND and (ops := _operands(args)):
+ return scope.hit(ops[-1], ancestor=verb == "rsync" and any(a.startswith("--delete") for a in args))
+ return None
+
+
+def _check_inplace(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if verb in _INPLACE_EDITORS and any(
+ a.startswith("--in-place") or (a.startswith("-") and not a.startswith("--") and "i" in a) for a in args):
+ return scope.first_hit(_operands(args))
+ return None
+
+
+def _check_find(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if verb != "find" or not any(a in ("-delete", "-exec", "-execdir", "-ok") for a in args):
+ return None
+ starts = itertools.takewhile(lambda a: not a.startswith("-"), args)
+ return scope.first_hit(starts, ancestor=True)
+
+
+def _check_git(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if verb != "git":
+ return None
+ where, rest = scope.cwd, list(args)
+ while rest and rest[0].startswith("-"):
+ flag = rest.pop(0)
+ if flag == "-C" and rest:
+ where = _expand(rest.pop(0), scope.cwd)
+ elif flag in ("-c", "--git-dir", "--work-tree") and rest:
+ rest.pop(0)
+ if rest and rest[0] in _GIT_MUTATIONS:
+ return _hit(where, scope.locked, scope.record, ancestor=True)
+ return None
+
+
+def _check_extract(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if verb not in ("tar", "unzip", "bsdtar"):
+ return None
+ dest = scope.cwd
+ for flag, value in itertools.pairwise(args):
+ if flag in ("-C", "--directory", "-d"):
+ dest = _expand(value, scope.cwd)
+ bundled = bool(args) and not args[0].startswith("-") and "x" in args[0] # `tar xzf a.tgz`
+ extracting = verb == "unzip" or bundled or any(
+ a == "--extract" or (a.startswith("-") and not a.startswith("--") and "x" in a) for a in args)
+ return _hit(dest, scope.locked, scope.record) if extracting else None
+
+
+def _check_interpreter(verb: str, args: list[str], scope: _Scope) -> str | None:
+ if not _INTERPRETERS.match(verb):
+ return None
+ for flag, code in itertools.pairwise(args):
+ if flag not in ("-c", "-e", "-E", "--eval", "-Command", "-r"):
+ continue
+ if verb in ("bash", "sh", "zsh", "dash", "ksh") and scope.depth < 3:
+ reason = _command_refusal(code, scope.cwd, scope.locked, scope.record, scope.depth + 1)
+ else:
+ reason = _code_refusal(code, scope.locked, scope.record)
+ if reason:
+ return reason
+ return None
+
+
+_ARGV_CHECKS = (_check_unlock, _check_file_verbs, _check_inplace, _check_find, _check_git,
+ _check_extract, _check_interpreter)
+
+
+def _argv_refusal(argv: list[str], cwd: str, locked, record, depth: int) -> str | None:
+ scope = _Scope(cwd, locked, record, depth)
+ verb = os.path.basename(argv[0])
+ return next((r for check in _ARGV_CHECKS if (r := check(verb, argv[1:], scope))), None)
+
+
+def _code_refusal(code: str, locked, record) -> str | None:
+ """Inline interpreter code that names a locked skill (or the record) AND looks like it writes."""
+ from hermes_constants import get_hermes_home
+ if not _WRITEISH_CODE.search(code):
+ return None
+ home, hermes_home = os.path.expanduser("~"), str(get_hermes_home())
+ text = code.replace("$HERMES_HOME", hermes_home).replace("~", home)
+ skills_root = os.path.realpath(_skill_usage()._skills_dir())
+ if ".usage.json" in text:
+ return RECORD_REFUSAL
+ for name, root in locked:
+ rel = os.path.relpath(root, skills_root) if skills_root and _inside(root, skills_root) else ""
+ if root in text or (rel and f"skills/{rel}" in text) or f"skills/{os.path.basename(root)}" in text:
+ return skill_refusal(name)
+ return None
+
+
+def _command_refusal(command: str, cwd: str, locked, record, depth: int = 0) -> str | None:
+ tokens = _tokens(command)
+ if "<<" in command and (reason := _code_refusal(command, locked, record)):
+ return reason # heredoc-fed interpreter body
+ for argv, targets in _segments(tokens):
+ for target in targets:
+ if reason := _hit(_expand(target, cwd), locked, record):
+ return reason
+ argv = _strip_wrappers(argv)
+ if not argv:
+ continue
+ if argv[0] in ("cd", "pushd") and len(argv) > 1:
+ cwd = _expand(argv[1], cwd)
+ continue
+ if reason := _argv_refusal(argv, cwd, locked, record, depth):
+ return reason
+ return None
+
+
+def command_refusal(command: str, cwd: str) -> str | None:
+ """terminal guard: refusal text when *command* writes into a locked skill, the lock record, or
+ runs ``hermes curator unlock``. None when nothing is locked."""
+ locked = locked_skill_dirs()
+ if not locked:
+ return None
+ return _command_refusal(command, cwd or os.getcwd(), locked, _record_path())
diff --git a/tools/skill_manager_guards.py b/tools/skill_manager_guards.py
index b35e34eba52..896189fbe8f 100644
--- a/tools/skill_manager_guards.py
+++ b/tools/skill_manager_guards.py
@@ -222,38 +222,35 @@ def _background_review_read_before_write_guard(
def _locked_guard(name: str, action: str) -> Optional[dict[str, Any]]:
- """Refuse autonomous mutations (review fork, curator consolidation pass) of a skill the user
- locked with ``hermes curator lock``. Foreground user-directed writes are not gated: the lock is
- against unattended drift, not against the user. ``create`` is exempt (the existing collision
- check already refuses a name that resolves anywhere). Unlike the pin guard this fails CLOSED on
- an unreadable sidecar — silently relaxing a lock the user set is the failure it exists to
- prevent. The lock is keyed by directory name, so the bare, categorized (``cat/name``) and
- frontmatter-name forms the tool accepts all resolve to the same record."""
- if action == "create" or not name or not _is_background_review():
+ """Refuse every mutating ``skill_manage`` action on a skill the user locked (``hermes curator
+ lock`` / the Desktop lock switch), whoever asks: foreground turns, the background review and the
+ curator pass alike. ``create`` is exempt (the collision check already refuses a name that resolves
+ anywhere). An unreadable sidecar fails CLOSED for the autonomous passes (silently relaxing a
+ lock is the failure this exists to prevent) and open for normal turns, so one corrupt file does
+ not freeze every skill edit. Keyed by directory name, so the bare, ``cat/name`` and
+ frontmatter-name forms all resolve to the same record."""
+ if action == "create" or not name:
return None
- refuse = f"Refusing background curator {action} for"
try:
from tools import skill_manager_tool as _smt
from tools import skill_usage
candidates = {name, Path(name).name}
if existing := _smt._find_skill(name):
candidates.add(existing["path"].name)
- locked = any(skill_usage.is_locked(candidate) for candidate in candidates)
+ locked = next((c for c in candidates if skill_usage.is_locked(c)), None)
except Exception:
logger.warning("locked skill guard lookup failed for %s", name, exc_info=True)
+ if not _is_background_review():
+ return None # a corrupt sidecar must not freeze every skill edit in normal turns
return _refusal(
- f"{refuse} skill '{name}': the lock state could not be verified because the "
- f"skills/.usage.json sidecar is unreadable. Leave the skill alone and report it; the user "
+ f"Refusing {action} for skill '{name}': its lock state could not be verified because the "
+ f"skills/.usage.json sidecar is unreadable. Leave the skill alone and tell the user; they "
f"can repair the sidecar or run `hermes curator unlock {name}`.", _locked=True)
if locked:
- return _refusal(
- f"{refuse} locked skill '{name}': the user locked it against autonomous changes. Do not "
- f"retry and do not recreate it under another name; describe the proposed change in your "
- f"summary instead. The user lifts the lock with `hermes curator unlock {name}`.",
- _locked=True)
+ from tools.skill_lock import skill_refusal
+ return _refusal(f"Refusing {action}: {skill_refusal(locked)}", _locked=True)
return None
-
def _background_review_preflight(action: str, name: str) -> Optional[dict[str, Any]]:
"""Guards that run on the bare action/name before any handler, for the single-op AND the
batch path: the content lock (every mutating action) and the ownership delete guard."""
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index e88972a41e5..374377078ff 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -951,7 +951,7 @@ def _command_requires_pipe_stdin(command: str) -> bool:
from tools.terminal_tool_guards import (
_foreground_background_guidance, _safe_command_preview, _validate_workdir,
- gateway_lifecycle_block, self_repo_block, trailing_amp_background_command,
+ gateway_lifecycle_block, locked_skill_block, self_repo_block, trailing_amp_background_command,
)
from tools.terminal_tool_background import _YIELDED_NOTE, spawn_background_process, yield_to_background_handler
from tools.terminal_tool_result import finalize_foreground_result
@@ -1431,7 +1431,8 @@ def _pre_exec_block(
workdir[:200], _safe_command_preview(command))
raise _Rejected(_error_json(workdir_error, status="blocked"))
if env_type == "local":
- blocked = self_repo_block(command=command, cwd=cwd, workdir=workdir, session_key=session_key)
+ blocked = (self_repo_block(command=command, cwd=cwd, workdir=workdir, session_key=session_key)
+ or locked_skill_block(command=command, cwd=cwd, workdir=workdir, session_key=session_key))
if blocked:
raise _Rejected(blocked)
diff --git a/tools/terminal_tool_guards.py b/tools/terminal_tool_guards.py
index 55407280174..28a0aaa8599 100644
--- a/tools/terminal_tool_guards.py
+++ b/tools/terminal_tool_guards.py
@@ -366,3 +366,18 @@ def self_repo_block(
return None
logger.warning("Blocked self-repo git mutation (command: %s)", _safe_command_preview(command))
return _blocked_json(msg, "blocked")
+
+
+def locked_skill_block(*, command: str, cwd: str, workdir: Optional[str], session_key: str) -> Optional[str]:
+ """Refuse commands that write into a skill the user locked, change the lock record, or run
+ ``hermes curator unlock`` (see tools/skill_lock). Local backend only: a remote or container
+ backend cannot reach this profile's skills dir. Returns the JSON error string when blocked."""
+ from tools.skill_lock import command_refusal
+ from tools.terminal_tool import _resolve_command_cwd
+
+ guard_cwd = _resolve_command_cwd(workdir=workdir, default_cwd=cwd, session_key=session_key)
+ reason = command_refusal(command, guard_cwd)
+ if reason is None:
+ return None
+ logger.warning("Blocked write to a locked skill (command: %s)", _safe_command_preview(command))
+ return _blocked_json(f"Blocked: {reason}", "blocked")
diff --git a/website/docs/user-guide/features/curator.md b/website/docs/user-guide/features/curator.md
index f4fcfd1235c..07a7700610c 100644
--- a/website/docs/user-guide/features/curator.md
+++ b/website/docs/user-guide/features/curator.md
@@ -44,7 +44,7 @@ A run has two phases:
By default the curator only **prunes** — the deterministic inactivity pass marks skills stale and archives long-unused ones. The opinionated LLM **consolidation** pass (umbrella-building, merging overlapping skills) is off by default because it costs aux-model tokens on every run and makes broad structural changes to your library. Turn it on with `curator.consolidate: true`, or run it once on demand with `hermes curator run --consolidate`.
:::
-Pinned skills are skipped by the curator's auto-transitions, and the agent's `skill_manage` tool refuses to **delete** them; edits and patches still go through. To stop the autonomous passes from changing a skill's *content*, lock it instead. See [Pinning a skill](#pinning-a-skill) and [Locking a skill's content](#locking-a-skills-content) below.
+Pinned skills are skipped by the curator's auto-transitions, and the agent's `skill_manage` tool refuses to **delete** them; edits and patches still go through. To stop the agent from changing a skill at all, lock it instead. See [Pinning a skill](#pinning-a-skill) and [Locking a skill](#locking-a-skill) below.
## Configuration
@@ -109,7 +109,7 @@ hermes curator pause # stop runs until resumed
hermes curator resume
hermes curator pin <skill> # never auto-transition this skill
hermes curator unpin <skill>
-hermes curator lock <skill> # autonomous passes may not change its content
+hermes curator lock <skill> # the agent may not change it
hermes curator unlock <skill>
hermes curator adopt <skill> # hand an unmanaged skill to the curator
hermes curator adopt --all-unmanaged # hand over every unmanaged skill
@@ -313,9 +313,9 @@ Skills that ARE agent-created follow the full lifecycle:
- Archives are recoverable via `hermes curator restore <name>`
If you want to protect an agent-created skill from archival, use
-`hermes curator pin <name>`. If you want the autonomous passes to stop changing a
-skill's content — for example a hand-authored skill you rely on — use
-`hermes curator lock <name>`. Both are described below.
+`hermes curator pin <name>`. If you want the agent to stop changing a skill at all —
+for example a hand-authored skill you rely on — use `hermes curator lock <name>`.
+Both are described below.
## Pinning a skill
@@ -339,11 +339,11 @@ Only **agent-created** skills can be pinned — `hermes curator pin` refuses on
A small set of **protected built-ins** can be hardcoded as never-archivable and never-consolidatable, regardless of `curator.prune_builtins`, pin state, or LLM judgment. These back load-bearing UX, so silently archiving one would turn its slash command into an "Unknown command" error with no signal to you. (The set is currently empty — `plan`, its original member, graduated to a built-in `/plan` command with no skill on disk.) Protected built-ins are filtered out of the curator's candidate list entirely, so the consolidation pass never sees them.
-If you want a stronger guarantee than "no deletion" — freezing a skill's content against the autonomous passes while the agent still reads it — lock it (next section). Neither pin nor lock guards your own filesystem access: editing `~/.hermes/skills/<name>/SKILL.md` in your editor always works.
+If you want a stronger guarantee than "no deletion" — freezing a skill's content while the agent still reads and uses it — lock it (next section). Neither pin nor lock guards your own edits: your editor and the Desktop skill editor always work.
-## Locking a skill's content
+## Locking a skill
-Pinning stops archival. Locking stops the **autonomous passes from changing what a skill says**, while the skill stays readable, listed in the skill index, auto-loadable and usable exactly as before.
+Pinning stops archival. Locking stops **the agent from changing a skill at all**, while the skill stays readable, listed in the skill index, auto-loadable and usable exactly as before.
```bash
hermes curator lock <skill>
@@ -351,20 +351,25 @@ hermes curator unlock <skill>
hermes curator status # lists locked skills
```
-Once a skill is locked:
+In Desktop, open **Capabilities → Skills**, select the skill and use its lock switch.
-- `skill_manage` **refuses** `patch`, `edit`, `write_file`, `remove_file` and `delete` on it when the write comes from the background self-improvement review or the curator's LLM consolidation pass — the two origins with no user in the loop. The refusal covers the whole skill directory (`SKILL.md`, `references/`, `scripts/`, `templates/`, `assets/`), both the single-op and the atomic batch form of the tool, and it tells the fork not to retry or recreate the skill under another name. Unlocked skills next to it keep learning as usual.
-- **Foreground writes are not blocked.** When you ask the agent in a normal turn to change a locked skill, the edit goes through: the lock is against unattended drift, not against you. To review user-directed writes too, turn on [`skills.write_approval`](./skills.md#gating-agent-skill-writes-skillswrite_approval); the two compose.
-- A corrupt or unreadable `.usage.json` makes the autonomous write **fail closed** (refused with an explanation) rather than quietly treating the skill as unlocked. Repair the sidecar, or run `hermes curator unlock <skill>` to rewrite it.
-- Any skill that resolves in the active profile can be locked — hand-written, agent-created, bundled or hub-installed. The skill must exist: `lock` refuses a name it cannot resolve, so a typo never records a lock for a skill that is not there.
+Once a skill is locked, every way the agent can write refuses it, in normal turns, cron jobs, subagents, the background self-improvement review and the curator pass alike, and even under `--yolo`:
-The flag is stored as `"locked": true` on the skill's entry in `~/.hermes/skills/.usage.json` — the same sidecar as `pinned`, so it is **per profile**: `hermes -p work curator lock deploy-runbook` locks that profile's copy and leaves every other profile's `deploy-runbook` unchanged.
+- **`skill_manage`** refuses `patch`, `edit`, `write_file`, `remove_file` and `delete`, for the single-op and the batch form.
+- **`write_file` and `patch`** refuse any path inside the skill's directory (`SKILL.md`, `references/`, `scripts/`, …).
+- **`terminal`** refuses commands that write there: redirections and `tee`, `cp`/`mv`/`rm`/`touch`/`mkdir`/`chmod`, `sed -i`/`perl -i`, `git` changes in the skill's tree, archive extraction into it, and inline `python -c`/`bash -c` code naming it, including after a `cd` into the skill. Reading the skill and running its scripts keep working.
+- The curator never archives a locked skill.
+- The agent cannot unlock it: `terminal` refuses `hermes curator unlock`, and the lock record (`skills/.usage.json`) is protected the same way while any skill is locked. The refusal tells the agent to describe the change it wanted so you can decide.
+
+Your own edits are not gated: editing the files in your editor or in the Desktop skill editor always works. To let the agent change it again, run `hermes curator unlock <skill>` or flip the switch.
+
+The flag is stored as `"locked": true` on the skill's entry in `~/.hermes/skills/.usage.json`, the same sidecar as `pinned`, so it is **per profile**: `hermes -p work curator lock deploy-runbook` locks that profile's copy only. Any skill that resolves in the profile can be locked (hand-written, agent-created, bundled or hub-installed); `lock` refuses a name it cannot resolve.
What a lock is not:
-- It is **not a sandbox.** It is a policy inside the skill tool and the curator. The agent's generic file tools and `terminal` can still change files under the skills directory if the process can write there. For a path-level gate on the file tools, add a basename pattern such as `SKILL.md` to `security.protected_instruction_extra_patterns` (writes then ask a human first); shell commands need filesystem permissions or a read-only mount.
-- It does **not** change archival or the inactivity clock. Hand-written skills are never archived autonomously anyway; for an agent-created skill you also want kept out of `stale → archived`, pin it as well.
-- It does **not** stop `hermes update` / `hermes skills update` from refreshing a bundled skill you have not modified — those syncs are not `skill_manage` writes.
+- It is a **policy check, not a sandbox.** The terminal check reads the command's write targets; a script that writes into the skill through its own logic, or `execute_code`, is not inspected. Pair it with filesystem permissions if you need a hard boundary.
+- If `.usage.json` is corrupt, the background passes are refused (fail closed) while normal turns proceed, so one broken file does not freeze every skill edit. Repair it, or run `hermes curator unlock <skill>` to rewrite it.
+- It does **not** stop `hermes update` / `hermes skills update` from refreshing a bundled or hub skill you have not modified; those are your commands, not agent writes.
## Usage telemetry
diff --git a/website/docs/user-guide/features/skills.md b/website/docs/user-guide/features/skills.md
index b62317c8080..08869b701ad 100644
--- a/website/docs/user-guide/features/skills.md
+++ b/website/docs/user-guide/features/skills.md
@@ -698,12 +698,11 @@ The review surface works in the interactive CLI and on messaging platforms
in the pending JSON file). Memory writes have the same gate under
`memory.write_approval` — see [Controlling memory writes](./memory.md#controlling-memory-writes-write_approval).
-To protect one *specific* skill from the autonomous passes without gating every
-write, lock it: `hermes curator lock <skill>`. A locked skill stays readable and
-auto-loadable, but the background review and curator passes can no longer patch,
-edit, add or remove files in it, or delete it; edits you ask for in a normal turn
-still go through. Lock and `write_approval` compose. See
-[Locking a skill's content](./curator.md#locking-a-skills-content).
+To stop the agent from changing one *specific* skill at all, lock it:
+`hermes curator lock <skill>` (or the lock switch in Desktop). A locked skill stays
+readable and auto-loadable, but `skill_manage`, `write_file`, `patch` and `terminal`
+all refuse to change it, in every kind of session; your own edits still work. See
+[Locking a skill](./curator.md#locking-a-skill).
> The separate `skills.guard_agent_created` setting is a content scanner
> (dangerous-pattern heuristics), not an approval gate — the two are