Skip to content

The agent that grows with you

fix(desktop): surface staged skill-write review on the desktop and TUI

Brooklyn Nicholson036c577c8627
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts
index 1dcb380d4aa..7ebc6130550 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts
@@ -11,6 +11,7 @@ import {
desktopSlashDescription,
type DesktopThemeCommandOption,
filterDesktopCommandsCatalog,
+ filterDesktopSubcommandCompletions,
isDesktopSlashExtensionCommand,
isDesktopSlashSuggestionWithOptions,
rankSkillCommands,
@@ -229,13 +230,19 @@ export function useSlashCompletions(options: {
const isArgCompletion = replaceFrom > 1
const prefix = isArgCompletion ? text.slice(0, replaceFrom) : ''
+ // Commands narrowed by `desktop_subcommands` (e.g. /skills exposes
+ // only its review slice here) must not suggest the subcommands the
+ // exec gate would refuse — filter before the arg-stub rewrite so the
+ // token under test is the bare subcommand word.
+ const scopedItems = filterDesktopSubcommandCompletions(text, result.items ?? [], { isArgCompletion })
+
// An alias the user typed to completion (`/reset`) must surface even
// though aliases are hidden while browsing — otherwise the popover
// says "no matches" for a command Enter happily executes (#57641).
// Only an EXACT match unlocks it; a partial prefix keeps hiding.
const exactAliasQuery = isArgCompletion ? undefined : commandText(query).toLowerCase()
- const decorated = (result.items ?? [])
+ const decorated = scopedItems
.map(item => {
if (!isArgCompletion) {
return item
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index e1550061158..36e7b93ca11 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@ -14,6 +14,7 @@ import {
type DesktopCommandSurface,
type DesktopPickerId,
desktopSlashUnavailableMessage,
+ desktopSubcommandUnavailableMessage,
isDesktopSlashCommand,
resolveDesktopCommand
} from '@/lib/desktop-slash-commands'
@@ -267,12 +268,26 @@ export function useSlashCommand(deps: SlashCommandDeps) {
const { render: renderSlashOutput, sessionId, storedSessionId } = resolved
- if (!isDesktopSlashCommand(name)) {
+ // Resolve the INVOCATION, not just the name: a command the desktop owns
+ // for its management surface can still delegate individual subcommands
+ // to the backend (`/skills pending` — see desktopSubcommandAllowlist).
+ if (!isDesktopSlashCommand(name, arg)) {
renderSlashOutput(desktopSlashUnavailableMessage(name) || `/${name} is not available in the desktop app.`)
return
}
+ // Commands narrowed by `desktop_subcommands` (e.g. /skills exposes
+ // only its write-approval review slice here — the CLI hub mutations
+ // must not be reachable from a desktop exec) stop at the client.
+ const subcommandBlocked = desktopSubcommandUnavailableMessage(name, arg)
+
+ if (subcommandBlocked) {
+ renderSlashOutput(subcommandBlocked)
+
+ return
+ }
+
let slashExecError: unknown = null
const handleDispatch = async (
diff --git a/apps/desktop/src/lib/desktop-slash-commands.test.ts b/apps/desktop/src/lib/desktop-slash-commands.test.ts
index 9225b43dab4..b41a7bf1740 100644
--- a/apps/desktop/src/lib/desktop-slash-commands.test.ts
+++ b/apps/desktop/src/lib/desktop-slash-commands.test.ts
@@ -6,8 +6,10 @@ import {
desktopSkinSlashCompletions,
type DesktopSlashArgumentMode,
desktopSlashCommandArgumentMode,
+ desktopSubcommandUnavailableMessage,
desktopSlashUnavailableMessage,
filterDesktopCommandsCatalog,
+ filterDesktopSubcommandCompletions,
isDesktopSlashCommand,
isDesktopSlashExtensionCommand,
isDesktopSlashSuggestion,
@@ -89,6 +91,44 @@ describe('desktop slash command curation', () => {
expect(desktopSlashCommandArgumentMode('/lcm')).toBe('text')
})
+ it('hands the /skills write-approval subcommands to the backend, keeping the hub mutations off the wire', () => {
+ // #98330: the registry declares `desktop_subcommands` on /skills so the
+ // review slice (pending/approve/reject/diff/approval) is exec-routed
+ // while the CLI-hub mutations (search/install/…) stay refused — an
+ // allowlisted invocation execs, everything else renders the gate message.
+ expect(isDesktopSlashCommand('/skills', 'pending')).toBe(true)
+ expect(isDesktopSlashCommand('/skills', ' approve 9f2c1a ')).toBe(true)
+ for (const sub of ['reject 9f2c1a', 'diff 9f2c1a', 'approval on']) {
+ expect(isDesktopSlashCommand('/skills', sub)).toBe(true)
+ }
+ // The exec gate is desktopSubcommandUnavailableMessage: the hub mutations
+ // render a refusal message instead of reaching the wire, and a bare
+ // /skills never execs into the interactive hub from the desktop.
+ expect(desktopSubcommandUnavailableMessage('/skills', 'search')).toContain('not available in the desktop app')
+ expect(desktopSubcommandUnavailableMessage('/skills', 'install gif-search')).toContain('not available in the desktop app')
+ expect(desktopSubcommandUnavailableMessage('/skills', 'audit')).toContain('not available in the desktop app')
+ expect(desktopSubcommandUnavailableMessage('/skills', '')).toContain('needs a subcommand here')
+ expect(desktopSubcommandUnavailableMessage('/skills', ' ')).toContain('needs a subcommand here')
+ expect(desktopSubcommandUnavailableMessage('/skills', 'pending')).toBeNull()
+
+ // Completion never suggests a subcommand the gate would refuse.
+ const subs = (items: readonly { text?: string }[]) => items.map(item => item.text)
+ expect(subs(filterDesktopSubcommandCompletions(
+ '/skills ', [{ text: 'pending review' }, { text: 'install demo' }], { isArgCompletion: true })
+ )).toEqual(['pending review'])
+ expect(subs(filterDesktopSubcommandCompletions(
+ '/skills ap', [{ text: 'approval on' }], { isArgCompletion: true })
+ )).toEqual(['approval on'])
+ // Value completion for a blocked hub mutation stays empty.
+ expect(filterDesktopSubcommandCompletions(
+ '/skills install ', [{ text: 'demo' }], { isArgCompletion: true })
+ ).toEqual([])
+ // Command-token completions pass through untouched.
+ expect(subs(filterDesktopSubcommandCompletions(
+ '/sk', [{ text: '/skills' }], { isArgCompletion: false })
+ )).toEqual(['/skills'])
+ })
+
it('groups complete.slash rows by backend kind, not the desktop table', () => {
// A registry command the table has never heard of is still a command.
expect(slashCompletionGroup('/refine', 'command')).toBe('Commands')
diff --git a/apps/desktop/src/lib/desktop-slash-commands.ts b/apps/desktop/src/lib/desktop-slash-commands.ts
index be1b40a2f60..cea539ae9d9 100644
--- a/apps/desktop/src/lib/desktop-slash-commands.ts
+++ b/apps/desktop/src/lib/desktop-slash-commands.ts
@@ -11,6 +11,8 @@ export interface CommandsCatalogSection {
export interface CommandCatalogMeta {
argument_mode?: 'mixed' | 'options' | 'text' | null
desktop?: string | null
+ /** Subcommands the desktop surface may offer and forward; absent = all. */
+ desktop_subcommands?: readonly string[] | null
}
export interface CommandsCatalogLike {
@@ -148,6 +150,14 @@ export interface DesktopCommandSpec {
hidden?: boolean
/** Composer behavior for text following the command token. */
argumentMode?: DesktopSlashArgumentMode
+ /**
+ * Subcommands (first argument token) the desktop may forward when the
+ * command is exec-routed. Absent = the whole family is allowed. Registry
+ * commands declare this as `desktop_subcommands` so a desktop-relevant
+ * review slice can be exposed without widening CLI-hub mutations
+ * (e.g. `/skills install`).
+ */
+ desktopSubcommands?: readonly string[]
}
const exec = (): DesktopCommandSurface => ({ kind: 'exec' })
@@ -300,6 +310,17 @@ const DESKTOP_COMMAND_SPECS: readonly DesktopCommandSpec[] = [
name: '/status',
description: 'Show current session status',
surface: rpc('session.status', ctx => ({ session_id: ctx.sessionId }))
+ },
+ {
+ // Keep this explicit so a current Desktop can review staged writes even
+ // when connected to an older backend whose catalog still says the Skills
+ // sidebar owns the command. The sidebar manages installed skills; it does
+ // not expose the write-approval queue (#98330).
+ name: '/skills',
+ description: 'Review staged skill writes and approval mode',
+ surface: exec(),
+ argumentMode: 'options',
+ desktopSubcommands: ['pending', 'approve', 'reject', 'diff', 'approval']
}
]
@@ -456,10 +477,19 @@ function specFromCatalog(command: string): DesktopCommandSpec | null {
name,
surface: exec(),
hidden: entry.desktop === 'hidden',
- argumentMode: asArgumentMode(entry.argument_mode)
+ argumentMode: asArgumentMode(entry.argument_mode),
+ desktopSubcommands: asSubcommandList(entry.desktop_subcommands)
}
}
+function asSubcommandList(value: unknown): readonly string[] | undefined {
+ if (!Array.isArray(value)) {
+ return undefined
+ }
+
+ return value.filter((sub): sub is string => typeof sub === 'string' && sub.trim() !== '')
+}
+
function isAliasCommand(command: string): boolean {
const normalized = normalizeCommand(command)
@@ -504,12 +534,105 @@ export function canonicalDesktopSlashCommand(command: string): string {
export function resolveDesktopCommand(command: string): DesktopCommandSpec | null {
const canonical = canonicalDesktopSlashCommand(command)
const local = SPEC_BY_NAME.get(canonical)
+ const catalog = specFromCatalog(command)
+
+ if (local && catalog?.desktopSubcommands !== undefined) {
+ return { ...local, desktopSubcommands: catalog.desktopSubcommands }
+ }
if (local && REGISTRY_OFFERED_NAMES.has(canonical)) {
- return specFromCatalog(command) ?? local
+ return catalog ?? local
}
- return local ?? specFromCatalog(command)
+ return local ?? catalog
+}
+
+/** Subcommands the desktop may forward for *command*; null = unrestricted. */
+export function desktopSubcommandAllowlist(command: string): readonly string[] | null {
+ return resolveDesktopCommand(command)?.desktopSubcommands ?? null
+}
+
+/**
+ * Execution gate for exec-routed commands whose spec narrows the family to a
+ * subcommand allowlist (see `desktop_subcommands` on the Python registry).
+ * The first argument token must name an allowed subcommand — anything else
+ * (including a bare command, which the CLI would answer with its interactive
+ * hub) stays off the desktop exec path. Returns the message to render instead
+ * of forwarding, or null when the command may run.
+ */
+export function desktopSubcommandUnavailableMessage(command: string, arg: string): string | null {
+ const allowed = desktopSubcommandAllowlist(command)
+
+ if (!allowed) {
+ return null
+ }
+
+ const display = command.trim().startsWith('/') ? command.trim() : `/${command.trim()}`
+
+ if (allowed.length === 0) {
+ return `${display} is not available in the desktop app — use the terminal for it.`
+ }
+
+ const first = arg.trim().split(/\s+/)[0]?.toLowerCase() ?? ''
+
+ if (!first) {
+ return `${display} needs a subcommand here: ${allowed.join(', ')}.`
+ }
+
+ if (!allowed.some(sub => sub.toLowerCase() === first)) {
+ return `${display} ${first} is not available in the desktop app — use the terminal for it. Available here: ${allowed.join(', ')}.`
+ }
+
+ return null
+}
+
+/**
+ * Drop backend `complete.slash` items whose subcommand token the exec gate
+ * above would refuse, so the popover never suggests a dead end. Command-stage
+ * completions pass through. When `stage.isArgCompletion` is provided, that
+ * backend `replace_from` flag wins over re-parsing whitespace in `text`.
+ */
+export function filterDesktopSubcommandCompletions<T extends { text?: string }>(
+ text: string,
+ items: readonly T[],
+ stage?: { isArgCompletion: boolean }
+): T[] {
+ const command = normalizeCommand(text)
+ const allowed = desktopSubcommandAllowlist(command)
+ const trimmedText = text.trimStart()
+ const normalizedText = trimmedText.startsWith('/') ? trimmedText : `/${trimmedText}`
+ const rest = normalizedText.slice(command.length)
+ // Prefer the backend's replace_from stage when the caller has it. Re-parsing
+ // the query from whitespace disagrees with that flag in both directions.
+ const inArgStage = stage?.isArgCompletion ?? /^\s/.test(rest)
+
+ // Only the argument stage (`/skills …`, including a bare trailing space)
+ // carries subcommand items; command-token completions pass through.
+ if (!allowed || !inArgStage) {
+ return [...items]
+ }
+
+ const argumentText = rest.trimStart()
+ const secondTokenBoundary = argumentText.search(/\s/)
+
+ // Once an allowed first argument is complete, the backend owns completion
+ // of its value (for example `approval on` or `approve <id>`). Keep refusing
+ // value completions for a hub mutation that the execution gate would block.
+ if (secondTokenBoundary >= 0) {
+ const first = argumentText.slice(0, secondTokenBoundary).toLowerCase()
+
+ return allowed.some(entry => entry.toLowerCase() === first) ? [...items] : []
+ }
+
+ return items.filter(item => {
+ if (typeof item.text !== 'string') {
+ return false
+ }
+
+ const sub = item.text.trim().split(/\s+/)[0]?.toLowerCase() ?? ''
+
+ return sub !== '' && allowed.some(entry => entry.toLowerCase() === sub)
+ })
}
/** Actions that fork their own run instead of speaking into the current turn. */
@@ -574,12 +697,23 @@ export function slashCompletionGroup(command: string, kind?: string | null): 'Co
return isDesktopSlashExtensionCommand(command) ? 'Skills' : 'Commands'
}
-/** Gates execution: true unless the command is a known no-desktop-surface command. */
-export function isDesktopSlashCommand(command: string): boolean {
+/** Gates execution: true unless the command is a known no-desktop-surface
+ * command. Pass the typed `arg` for registry-narrowed commands
+ * (`desktop_subcommands`): when the invocation's first token is an allowed
+ * subcommand (`/skills pending`) it execs even though the bare command
+ * resolves to `unavailable`. */
+export function isDesktopSlashCommand(command: string, arg = ''): boolean {
const spec = resolveDesktopCommand(command)
if (spec) {
- return spec.surface.kind !== 'unavailable'
+ if (spec.surface.kind !== 'unavailable') {
+ return true
+ }
+
+ const allowed = spec.desktopSubcommands
+ const first = arg.trim().split(/\s+/)[0]?.toLowerCase() ?? ''
+
+ return Boolean(allowed?.some(sub => sub.toLowerCase() === first))
}
return isDesktopSlashExtensionCommand(command)
@@ -612,7 +746,7 @@ export function isDesktopSlashSuggestionWithOptions(command: string, options: {
const spec = resolveDesktopCommand(normalized)
if (spec) {
- return spec.surface.kind !== 'unavailable' && !spec.hidden
+ return spec.surface.kind !== 'unavailable' && !spec.hidden && spec.desktopSubcommands?.length !== 0
}
// Skill / quick commands the backend provides.
diff --git a/apps/desktop/src/lib/desktop-slash-registry.json b/apps/desktop/src/lib/desktop-slash-registry.json
index 9c941cb23b9..31ad516c93e 100644
--- a/apps/desktop/src/lib/desktop-slash-registry.json
+++ b/apps/desktop/src/lib/desktop-slash-registry.json
@@ -94,7 +94,7 @@
"/sessions": null,
"/set-home": "terminal",
"/sethome": "terminal",
- "/skills": "settings",
+ "/skills": null,
"/skin": null,
"/snap": "terminal",
"/snapshot": "terminal",
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 4ca52374a76..3601ce7a235 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3643,6 +3643,7 @@ export interface CommandsCatalogResult {
export interface CommandCatalogMeta {
argument_mode?: ArgumentMode | null
desktop?: string | null
+ desktop_subcommands?: string[] | null
}
export type ArgumentMode = 'options' | 'text' | 'mixed'
export interface CommandCategory {
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 53080ab114b..9afa9281c88 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -7907,6 +7907,21 @@
],
"default": null,
"title": "Desktop"
+ },
+ "desktop_subcommands": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Desktop Subcommands"
}
},
"title": "CommandCatalogMeta",
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.py
index 0597fd616a6..fe6b288e32c 100644
--- a/hermes_cli/commands.py
+++ b/hermes_cli/commands.py
@@ -65,6 +65,12 @@ class CommandDef:
argument_mode: str | None = None # desktop composer: options|text|mixed; None inferred
# Desktop availability: None = offered; "hidden" = runs but out of the popover; else a reason.
desktop: str | None = None
+ # Desktop subcommand scope. When set, the desktop surface only offers
+ # (completion) and forwards (exec) these subcommands — the first argument
+ # token must be one of them. Use when a command family mixes desktop-
+ # relevant review actions with CLI-hub mutations (e.g. /skills install),
+ # so offering the command doesn't widen the whole family.
+ desktop_subcommands: tuple[str, ...] | None = None
def describe(self) -> str:
"""Localized description (``slash.<name>.description``); ``description`` is the English source."""
@@ -245,7 +251,13 @@ COMMAND_REGISTRY: list[CommandDef] = [
gateway_config_gate="skills.write_approval",
subcommands=("search", "browse", "inspect", "install", "audit",
"pending", "approve", "reject", "diff", "approval"),
- desktop="settings"),
+ # Desktop exposes only the write-approval review slice — the
+ # same surface the gateway handler offers. The hub mutations
+ # (search/browse/inspect/install/audit) run a full interactive
+ # CLI hub that must not be reachable from a desktop exec
+ # (#98330 review).
+ desktop_subcommands=("pending", "approve", "reject", "diff",
+ "approval")),
CommandDef("memory", "Review pending memory writes / toggle the approval gate",
"Tools & Skills", args_hint="[pending|approve|reject|approval] [id|on|off]",
subcommands=("pending", "approve", "reject", "approval")),
@@ -349,9 +361,12 @@ def infer_argument_mode(cmd: CommandDef) -> str | None:
return "text" if hint else None
-def command_desktop_meta(cmd: CommandDef) -> dict[str, str | None]:
+def command_desktop_meta(cmd: CommandDef) -> dict[str, object]:
"""Wire shape for ``commands.catalog`` — reads the CommandDef, nothing else."""
- return {"argument_mode": infer_argument_mode(cmd), "desktop": cmd.desktop}
+ meta: dict[str, object] = {"argument_mode": infer_argument_mode(cmd), "desktop": cmd.desktop}
+ if cmd.desktop_subcommands is not None:
+ meta["desktop_subcommands"] = list(cmd.desktop_subcommands)
+ return meta
def desktop_surface_registry() -> dict[str, str | None]:
diff --git a/tests/hermes_cli/test_commands.py b/tests/hermes_cli/test_commands.py
index 5afbcace506..35cc6c0bf5a 100644
--- a/tests/hermes_cli/test_commands.py
+++ b/tests/hermes_cli/test_commands.py
@@ -3,7 +3,7 @@
from prompt_toolkit.completion import CompleteEvent
from prompt_toolkit.document import Document
-from hermes_cli.commands import COMMAND_REGISTRY, COMMANDS_BY_CATEGORY, CommandDef, GATEWAY_KNOWN_COMMANDS, gateway_help_lines, infer_argument_mode, resolve_command
+from hermes_cli.commands import COMMAND_REGISTRY, COMMANDS_BY_CATEGORY, CommandDef, GATEWAY_KNOWN_COMMANDS, command_desktop_meta, gateway_help_lines, infer_argument_mode, resolve_command
from hermes_cli.commands_completion import SlashCommandAutoSuggest, SlashCommandCompleter
from hermes_cli.commands_platforms import _CMD_NAME_LIMIT, _SLACK_RESERVED_COMMANDS, _SLACK_VIA_HERMES_ONLY, _clamp_command_names, _sanitize_telegram_name, slack_app_manifest, slack_native_slashes, slack_subcommand_map, telegram_bot_commands, telegram_menu_commands
@@ -41,6 +41,29 @@ class TestCommandRegistry:
assert resolve_command(alias).name == cmd.name or alias == cmd.name, \
f"Alias '{alias}' of '{cmd.name}' shadows canonical '{target.name}'"
+ def test_skills_desktop_meta_limits_exec_to_review_subcommands(self):
+ # #98330: /skills mixes desktop-relevant write-approval review verbs with CLI-hub
+ # mutations; desktop_subcommands exposes only the review slice to the desktop
+ # surface (completion + exec) without widening the whole family.
+ skills = resolve_command("skills")
+ assert skills is not None
+ assert skills.desktop is None
+ assert command_desktop_meta(skills) == {
+ "argument_mode": "options",
+ "desktop": None,
+ "desktop_subcommands": ["pending", "approve", "reject", "diff", "approval"],
+ }
+ assert set(skills.desktop_subcommands or ()) <= set(skills.subcommands)
+
+ def test_empty_desktop_subcommand_scope_serializes_as_deny_all(self):
+ assert command_desktop_meta(
+ CommandDef("demo", "Demo", "Session", desktop_subcommands=())
+ ) == {
+ "argument_mode": None,
+ "desktop": None,
+ "desktop_subcommands": [],
+ }
+
def test_argument_mode_infers_text_from_any_args_hint(self):
assert infer_argument_mode(CommandDef("demo", "Demo", "Session", args_hint="<prompt>")) == "text"
diff --git a/tests/tools/test_write_approval.py b/tests/tools/test_write_approval.py
index c9ea5d3ae49..9518e012364 100644
--- a/tests/tools/test_write_approval.py
+++ b/tests/tools/test_write_approval.py
@@ -327,3 +327,54 @@ def test_memory_invalid_params_rejected_before_staging(hermes_home):
r = json.loads(memory_tool("add", "memory", None, store=store))
assert r["success"] is False
assert wa.pending_count("memory") == 0
+
+
+# ---------------------------------------------------------------------------
+# Staged-write review hint is surface-aware (#98330)
+# ---------------------------------------------------------------------------
+
+def _stage_one_memory_write():
+ from tools.memory_tool import memory_tool, MemoryStore
+ store = MemoryStore(); store.load_from_disk()
+ r = json.loads(memory_tool("add", "memory", "surface hint fact", store=store))
+ assert r.get("staged") is True, r
+ return r
+
+
+def test_staged_hint_names_the_review_command_on_slash_surfaces(hermes_home):
+ from tools import write_approval as wa
+ _set_approval("memory", True)
+ r = _stage_one_memory_write()
+ # No headless markers bound (plain foreground turn) → the slash hint stands.
+ assert "/memory pending" in r["message"], r["message"]
+ assert wa.pending_count("memory") == 1
+
+
+def test_staged_hint_names_the_pending_dir_on_headless_surfaces(hermes_home, monkeypatch):
+ from tools import write_approval as wa
+ _set_approval("memory", True)
+ monkeypatch.setenv("HERMES_CRON_SESSION", "1")
+ r = _stage_one_memory_write()
+ assert "review with /memory pending" not in r["message"], r["message"]
+ assert "pending records live in" in r["message"]
+ assert str(wa._pending_path(wa.MEMORY, "").parent) in r["message"]
+ monkeypatch.delenv("HERMES_CRON_SESSION")
+
+ monkeypatch.setenv("HERMES_KANBAN_TASK", "task-7")
+ r = _stage_one_memory_write()
+ assert "review with /memory pending" not in r["message"], r["message"]
+ monkeypatch.delenv("HERMES_KANBAN_TASK")
+
+ monkeypatch.setenv("HERMES_SESSION_PLATFORM", "api_server")
+ r = _stage_one_memory_write()
+ assert "review with /memory pending" not in r["message"], r["message"]
+ assert "pending records live in" in r["message"]
+ monkeypatch.delenv("HERMES_SESSION_PLATFORM")
+ assert wa.pending_count("memory") == 3
+
+
+def test_staged_hint_keeps_command_for_chat_gateway_platform(hermes_home, monkeypatch):
+ _set_approval("memory", True)
+ monkeypatch.setenv("HERMES_SESSION_PLATFORM", "telegram")
+ r = _stage_one_memory_write()
+ assert "/memory pending" in r["message"], r["message"]
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index 25d7e1ee7b2..f733e8c5c84 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -3151,6 +3151,92 @@ def test_command_dispatch_and_catalog_resolve_project_skills_from_the_session_cw
assert skill_utils.find_project_root() is None
+def test_command_dispatch_reviews_staged_skill_writes(tmp_path, monkeypatch):
+ # #98330/#118812: command.dispatch is the desktop/TUI FALLBACK stage when the slash
+ # worker cannot start. With no /skills route there, a failed worker turned every
+ # review command into the routing refusal, stranding staged writes with no surface
+ # left. The review slice (pending/approve/reject/diff/approval) must answer; the
+ # CLI-hub mutations must keep refusing.
+ from tools import write_approval as wa
+
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "config.yaml").write_text("skills:\n write_approval: true\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ rec = wa.stage_write(
+ wa.SKILLS,
+ {"action": "create", "name": "demo-review",
+ "content": "---\nname: demo-review\ndescription: Use when testing staged review.\n---\n\nBody.\n"},
+ summary="create demo-review", origin="background_review")
+ server._sessions["sid-wa"] = _session(profile_home=str(home))
+ try:
+ pending = server._methods["command.dispatch"](
+ "d1", {"name": "skills", "arg": "pending", "session_id": "sid-wa"})
+ assert pending["result"]["type"] == "exec", pending
+ assert rec["id"] in pending["result"]["output"]
+ assert "demo-review" in pending["result"]["output"]
+
+ diff = server._methods["command.dispatch"](
+ "d2", {"name": "skills", "arg": f"diff {rec['id']}", "session_id": "sid-wa"})
+ assert diff["result"]["type"] == "exec", diff
+ assert "demo-review" in diff["result"]["output"]
+
+ reject = server._methods["command.dispatch"](
+ "d3", {"name": "skills", "arg": f"reject {rec['id']}", "session_id": "sid-wa"})
+ assert "Rejected pending skills write" in reject["result"]["output"], reject
+ assert wa.pending_count(wa.SKILLS) == 0
+
+ # The hub mutations are NOT routed — the desktop allowlist mirrors this refusal.
+ refused = server._methods["command.dispatch"](
+ "d4", {"name": "skills", "arg": "install demo", "session_id": "sid-wa"})
+ assert refused["error"]["code"] == 4018, refused
+ finally:
+ server._sessions.pop("sid-wa", None)
+
+
+def test_command_dispatch_skills_gate_off_answers_instead_of_refusing(tmp_path, monkeypatch):
+ # Gateway parity: the gate being off must not strand writes that are already staged,
+ # and with an empty pile it points at the toggle instead of the routing refusal.
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "config.yaml").write_text("skills:\n write_approval: false\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ server._sessions["sid-wa"] = _session(profile_home=str(home))
+ try:
+ res = server._methods["command.dispatch"](
+ "d", {"name": "skills", "arg": "pending", "session_id": "sid-wa"})
+ assert res["result"]["type"] == "exec", res
+ assert "write_approval" in res["result"]["output"], res
+ finally:
+ server._sessions.pop("sid-wa", None)
+
+
+def test_command_dispatch_memory_pending_reviews_staged_writes(tmp_path, monkeypatch):
+ # Same fallback for /memory (#118812): the store must resolve under the session's
+ # profile home, applying the write on approve instead of dropping it.
+ from tools import write_approval as wa
+
+ home = tmp_path / "home"
+ home.mkdir()
+ (home / "config.yaml").write_text("memory:\n write_approval: true\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ wa.stage_write(wa.MEMORY, {"action": "add", "target": "memory", "content": "dispatched fact"},
+ summary="add dispatched fact", origin="foreground")
+ server._sessions["sid-wa"] = _session(profile_home=str(home))
+ try:
+ res = server._methods["command.dispatch"](
+ "d1", {"name": "memory", "arg": "pending", "session_id": "sid-wa"})
+ assert res["result"]["type"] == "exec", res
+ assert "dispatched fact" in res["result"]["output"]
+
+ approve = server._methods["command.dispatch"](
+ "d2", {"name": "memory", "arg": "approve all", "session_id": "sid-wa"})
+ assert "Approved 1" in approve["result"]["output"], approve
+ assert wa.pending_count(wa.MEMORY) == 0
+ finally:
+ server._sessions.pop("sid-wa", None)
+
+
def test_complete_slash_and_skills_reload_are_bound_to_the_session_cwd(tmp_path, monkeypatch):
# The '/' popup and /reload-skills ran the registry unbound: the popup never offered a project skill
# ``command.dispatch`` accepts, and a rescan after that dispatch reported the session's project skills
diff --git a/tools/write_approval.py b/tools/write_approval.py
index 289c2f84e9f..eeb088a2993 100644
--- a/tools/write_approval.py
+++ b/tools/write_approval.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import difflib
import json
import logging
+import os
import re
import time
import uuid
@@ -162,10 +163,39 @@ class GateDecision:
message: str = ""
+def _slash_review_surface() -> bool:
+ """Whether the ACTIVE turn has a human who can type ``/<subsystem> pending``: the interactive
+ CLI, TUI/desktop (exec route), and chat-gateway sessions all answer it now. Headless worker
+ contexts — cron (``HERMES_CRON_SESSION``), kanban (``HERMES_KANBAN_TASK``) and the unattended
+ programmatic platforms (api_server, webhook delivery) — have nobody at a prompt, so the staged
+ hint must not name a command nobody can deliver (#98330); it names the pending dir instead."""
+ def _env(name: str) -> str:
+ try:
+ from gateway.session_context import get_session_env
+ return get_session_env(name, "") or ""
+ except Exception: # standalone/tests: process env is the fallback
+ return os.environ.get(name, "") or ""
+ if _env("HERMES_KANBAN_TASK").strip():
+ return False
+ try:
+ from utils import is_truthy_value
+ if is_truthy_value(_env("HERMES_CRON_SESSION")):
+ return False
+ except Exception:
+ pass
+ platform = (_env("HERMES_SESSION_PLATFORM") or os.environ.get("HERMES_PLATFORM", "")).strip().lower()
+ return platform not in {"webhook", "msgraph_webhook", "api_server"}
+
+
def _staged(subsystem: str) -> GateDecision:
- where = "/skills pending" if subsystem == SKILLS else "/memory pending"
+ command = f"/{subsystem} pending"
+ if _slash_review_surface():
+ where = f"review with {command}"
+ else:
+ where = (f"pending records live in {_pending_path(subsystem, '').parent} "
+ f"(review from an interactive CLI session with {command})")
return GateDecision(stage=True, message=(f"Staged for approval ({subsystem}.write_approval is on). "
- f"Not yet saved — review with {where}."))
+ f"Not yet saved — {where}."))
def evaluate_gate(subsystem: str, *, inline_summary: str = "", inline_detail: str = "") -> GateDecision:
diff --git a/tui_gateway/contracts/tools_commands.py b/tui_gateway/contracts/tools_commands.py
index 93fba36745d..cf078a70756 100644
--- a/tui_gateway/contracts/tools_commands.py
+++ b/tui_gateway/contracts/tools_commands.py
@@ -201,6 +201,7 @@ class ArgumentMode(WireEnum):
class CommandCatalogMeta(Result):
argument_mode: ArgumentMode | None = None
desktop: str | None = None
+ desktop_subcommands: list[str] | None = None
class CommandCategory(Result):
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 41b835d169e..b5b7ebd413a 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -975,11 +975,90 @@ def _cmd_compress(rid, params, session, name, arg):
return _err(rid, 5009, f"compress failed: {exc}")
+# ─── /memory + /skills write-approval review ─────────────────────────────────
+# The review surface (pending / approve / reject / diff / approval) is owned by the shared handler
+# hermes_cli/write_approval_commands.handle_pending_subcommand, which the classic CLI and the
+# messaging gateway already reach. Desktop/TUI clients normally get it through slash.exec ->
+# _SlashWorker (a private HermesCLI), but command.dispatch is their FALLBACK stage — with no
+# route here, a failed worker turned every /memory into the routing refusal "not a quick/
+# plugin/bundle/skill command: memory", so staged writes had no review path at all.
+#
+# The store must resolve under the SAME home as the command, which is why these run inside the
+# dispatcher's `_session_home_scope(session)` block: `load_on_disk_store()` reads the profile's
+# MEMORY.md/USER.md and its memory char limits (see the scope note on `_session_home_scope`,
+# #110695).
+_MEMORY_USAGE = ("Unknown /memory subcommand. "
+ "Use: pending, approve <id>, reject <id>, approval <on|off>.")
+_SKILLS_USAGE = ("Unknown /skills subcommand here. "
+ "Use: pending, approve <id>, reject <id>, diff <id>, approval <on|off>. "
+ "(Search/install/browse are terminal-side.)")
+
+
+def _pending_subcommand_store(session):
+ """Memory store for the session's own profile: the live agent's store when there is one, else a
+ freshly loaded on-disk store — mirroring cli.py's /memory handler and the gateway's (Desktop/TUI
+ sessions have no long-lived agent store). ``None`` when even that fails, which the shared handler
+ reports as "memory store unavailable" instead of claiming the write was applied."""
+ if session:
+ with contextlib.suppress(Exception):
+ store = getattr(session.get("agent"), "_memory_store", None)
+ if store is not None:
+ return store
+ with contextlib.suppress(Exception):
+ return _tools_mod("tools.memory_tool").load_on_disk_store()
+ return None
+
+
+def _write_approval_mode_setter(subsystem: str):
+ """Persist ``<subsystem>.write_approval`` into the SESSION's profile config (this runs inside
+ ``_session_home_scope``, so ``_write_config_key`` writes the right profile's config.yaml)."""
+ return lambda enabled: _write_config_key(f"{subsystem}.write_approval", bool(enabled))
+
+
+def _run_pending_review(rid, subsystem: str, arg: str, session, *, unknown: str):
+ from hermes_cli.write_approval_commands import handle_pending_subcommand
+ from tools import write_approval as wa
+ out = handle_pending_subcommand(
+ subsystem, (arg or "").split(),
+ memory_store=_pending_subcommand_store(session) if subsystem == wa.MEMORY else None,
+ set_mode_fn=_write_approval_mode_setter(subsystem))
+ return _exec_out(rid, out if out is not None else unknown)
+
+
+def _cmd_memory(rid, params, session, name, arg):
+ """/memory — review staged memory writes, approve/reject them, toggle the gate."""
+ return _run_pending_review(rid, "memory", arg, session, unknown=_MEMORY_USAGE)
+
+
+def _cmd_skills(rid, params, session, name, arg):
+ """/skills write-approval subcommands only; the hub subcommands stay with the slash worker.
+
+ Returns None (falls through to the routing refusal, unchanged behaviour) for anything outside
+ the review surface — ``search``/``install``/``browse``/``inspect`` are the CLI skills hub's,
+ never a staged-write review. The allowlist mirrors the registry-declared review slice
+ (``CommandDef("skills", desktop_subcommands=...)`` in hermes_cli/commands.py)."""
+ sub = (arg or "").split()
+ commands = _tools_mod("hermes_cli.commands")
+ allowed = getattr(commands.resolve_command("skills"), "desktop_subcommands", None) or ()
+ if not sub or sub[0].lower() not in allowed:
+ return None
+ from tools import write_approval as wa
+ # The gate being off must not strand writes that are already staged (gateway parity): still
+ # answer when a pile exists, and point at the toggle when there is nothing to review.
+ if (sub[0].lower() not in {"approval", "mode"} and not wa.write_approval_enabled(wa.SKILLS)
+ and wa.pending_count(wa.SKILLS) == 0):
+ return _exec_out(rid, "Skill write approval is off (skills.write_approval). "
+ "Enable it with /skills approval on, then review staged writes "
+ "with /skills pending.")
+ return _run_pending_review(rid, "skills", arg, session, unknown=_SKILLS_USAGE)
+
+
_SLASH_BUILTINS = {
"queue": _cmd_queue, "q": _cmd_queue, "learn": _cmd_learn, "plan": _cmd_plan, "init": _cmd_init,
"moa": _cmd_moa, "focus": _cmd_focus, "retry": _cmd_retry, "steer": _cmd_steer, "goal": _cmd_goal,
"loop": _cmd_loop, "undo": _cmd_undo, "snapshot": _cmd_snapshot, "snap": _cmd_snapshot,
- "compress": _cmd_compress, "compact": _cmd_compress}
+ "compress": _cmd_compress, "compact": _cmd_compress,
+ "memory": _cmd_memory, "skills": _cmd_skills}
@method("command.dispatch")
def _(rid, params: dict) -> dict: