write_approval_commands.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env python3
  2. """Shared handlers for the /memory and /skills write-approval subcommands."""
  3. from __future__ import annotations
  4. import json
  5. from typing import List, Optional
  6. from tools import write_approval as wa
  7. def _fmt_state(subsystem: str) -> str:
  8. on = wa.write_approval_enabled(subsystem)
  9. return f"{subsystem}.write_approval = {'on' if on else 'off'}"
  10. def _fmt_pending_list(subsystem: str) -> str:
  11. records = wa.list_pending(subsystem)
  12. if not records:
  13. return f"No pending {subsystem} writes."
  14. lines = [f"Pending {subsystem} writes ({len(records)}):"]
  15. for r in records:
  16. origin = r.get("origin", "foreground")
  17. tag = " [auto]" if origin == "background_review" else ""
  18. lines.append(f" {r['id']}{tag} {r.get('summary', '')}")
  19. if subsystem == wa.MEMORY:
  20. lines.extend(f" {line}" for line in _matched_entries(r["payload"]))
  21. lines.append("")
  22. lines.append(f"Apply: /{subsystem} approve <id> Reject: /{subsystem} reject <id>")
  23. if subsystem == wa.SKILLS:
  24. lines.append("Review full diff: /skills diff <id>")
  25. return "\n".join(lines)
  26. def handle_pending_subcommand(
  27. subsystem: str, args: list[str], *, memory_store=None, set_mode_fn=None) -> Optional[str]:
  28. """Dispatch a /memory or /skills write-approval subcommand.
  29. ``memory_store`` applies approved memory writes (CLI passes its live store; gateway a freshly
  30. loaded one); ``set_mode_fn`` persists the write_approval boolean. Returns text for the user,
  31. or None when the args are not a write-approval subcommand so the caller falls through to its
  32. other handling (e.g. /skills search).
  33. """
  34. if not args:
  35. return f"{_fmt_state(subsystem)}\n\n" + _fmt_pending_list(subsystem)
  36. sub, rest = args[0].lower(), args[1:]
  37. if sub == "pending":
  38. return _fmt_pending_list(subsystem)
  39. if sub in {"approve", "apply"}:
  40. return _approve(subsystem, rest, memory_store)
  41. if sub in {"reject", "deny", "drop"}:
  42. return _reject(subsystem, rest)
  43. if sub == "diff" and subsystem == wa.SKILLS:
  44. return _diff(rest)
  45. if sub in {"approval", "mode"}: # 'mode' kept as a back-compat alias
  46. return _set_approval(subsystem, rest, set_mode_fn)
  47. return None # not ours — caller handles
  48. def _usage(subsystem: str) -> str:
  49. return f"Usage: /{subsystem} approve|reject <id> (or 'all')"
  50. def _approve(subsystem: str, rest: list[str], memory_store) -> str:
  51. if not rest:
  52. return _usage(subsystem)
  53. target = rest[0]
  54. records = wa.list_pending(subsystem)
  55. if not records:
  56. return f"No pending {subsystem} writes."
  57. if target.lower() == "all":
  58. targets = list(records)
  59. else:
  60. rec = wa.get_pending(subsystem, target)
  61. if not rec:
  62. return f"No pending {subsystem} write with id '{target}'."
  63. targets = [rec]
  64. applied, failed, overwritten, patched, removed = 0, [], [], [], []
  65. for rec in targets:
  66. ok, msg, result = _apply_one(subsystem, rec, memory_store)
  67. if ok:
  68. wa.discard_pending(subsystem, rec["id"])
  69. applied += 1
  70. overwritten.extend(f" {rec['id']}: {text}" for text in _changed_entries(result, "replaced"))
  71. patched.extend(f" {rec['id']}: {text}" for text in _changed_entries(result, "patched"))
  72. removed.extend(f" {rec['id']}: {text}" for text in _changed_entries(result, "removed"))
  73. else:
  74. failed.append(f"{rec['id']}: {msg}")
  75. out = [f"Approved {applied} {subsystem} write(s)."]
  76. if overwritten:
  77. # A memory 'replace' overwrites the WHOLE matched entry (#117952); the approver
  78. # is the last person who can notice a clause went missing, so show what was lost.
  79. out.append("Overwrote entire entry (re-add anything you still need):")
  80. out.extend(overwritten)
  81. if patched:
  82. # A patch keeps the rest of the entry, so show it as it was, not as lost text.
  83. out.append("Patched entry (as it was before the edit):")
  84. out.extend(patched)
  85. if removed:
  86. out.append("Removed entry (re-add anything you still need):")
  87. out.extend(removed)
  88. if failed:
  89. out.append("Failed:")
  90. out.extend(f" {f}" for f in failed)
  91. return "\n".join(out)
  92. def _changed_entries(result: dict, kind: str) -> list[str]:
  93. """Full text of every entry a memory write changed, single-op or batch shape."""
  94. single = result.get(f"{kind}_entry")
  95. if kind == "patched" and single is None:
  96. single = result.get("patched_entry_before")
  97. batch = result.get(f"{kind}_entries") or {}
  98. return ([single] if single else []) + [batch[k] for k in sorted(batch, key=int)]
  99. def _matched_entries(payload) -> list[str]:
  100. """The full entry each staged memory replace/remove is pinned to: the summary shows only
  101. the old_text search string, and approval applies to this entry, not to that search."""
  102. from tools.memory_tool import destructive_ops
  103. return [f"{op['action']}s entry: {op['matched_entry']}" if op.get("matched_entry")
  104. else f"{op['action']}: unpinned legacy target \u2014 reject and recreate before approving"
  105. for op in destructive_ops(payload)]
  106. def _apply_one(subsystem: str, rec, memory_store):
  107. """``(ok, error, result)`` — *result* is the applier's full payload (empty on exceptions)."""
  108. payload = rec.get("payload", {})
  109. try:
  110. if subsystem == wa.MEMORY:
  111. if memory_store is None:
  112. return False, "memory store unavailable", {}
  113. from tools.memory_tool import apply_memory_pending
  114. result = apply_memory_pending(payload, memory_store)
  115. else:
  116. from tools.skill_manager_tool import apply_skill_pending
  117. result = json.loads(apply_skill_pending(payload))
  118. return bool(result.get("success")), result.get("error", ""), result
  119. except Exception as e:
  120. return False, str(e), {}
  121. def _reject(subsystem: str, rest: list[str]) -> str:
  122. if not rest:
  123. return _usage(subsystem)
  124. target = rest[0]
  125. if target.lower() == "all":
  126. n = sum(1 for rec in wa.list_pending(subsystem) if wa.discard_pending(subsystem, rec["id"]))
  127. return f"Rejected {n} pending {subsystem} write(s)."
  128. if wa.discard_pending(subsystem, target):
  129. return f"Rejected pending {subsystem} write '{target}'."
  130. return f"No pending {subsystem} write with id '{target}'."
  131. def _diff(rest: list[str]) -> str:
  132. if not rest:
  133. return "Usage: /skills diff <id>"
  134. rec = wa.get_pending(wa.SKILLS, rest[0])
  135. if not rec:
  136. return f"No pending skill write with id '{rest[0]}'."
  137. return f"# Pending skill write {rec['id']}: {rec.get('summary', '')}\n\n" + wa.skill_pending_diff(rec)
  138. _APPROVAL_VALUES = {
  139. **dict.fromkeys(("on", "true", "yes", "1", "enable", "enabled"), True),
  140. **dict.fromkeys(("off", "false", "no", "0", "disable", "disabled"), False)}
  141. def _set_approval(subsystem: str, rest: list[str], set_mode_fn) -> str:
  142. """Turn the approval gate on/off for a subsystem."""
  143. if not rest:
  144. return (f"{_fmt_state(subsystem)}\n"
  145. f"Set with: /{subsystem} approval <on|off>")
  146. arg = rest[0].strip().lower()
  147. enabled = _APPROVAL_VALUES.get(arg)
  148. if enabled is None:
  149. return f"Invalid value '{arg}'. Use: on or off."
  150. if set_mode_fn is None:
  151. val = "true" if enabled else "false"
  152. return (f"To change the {subsystem} approval gate, run:\n"
  153. f" hermes config set {subsystem}.write_approval {val}")
  154. try:
  155. set_mode_fn(enabled)
  156. except Exception as e:
  157. return f"Failed to set {subsystem}.write_approval: {e}"
  158. return f"{subsystem}.write_approval set to '{'on' if enabled else 'off'}'."