Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix comments
  • Loading branch information
Alanxtl committed Aug 26, 2026
commit 7ab4d7e781811937054e4f31c21138bb96b3a2a6
76 changes: 73 additions & 3 deletions integrations/hermes/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ With Hermes installed and available on `PATH`, install or refresh the provider
from the matching PowerContext release tag:

```bash
powercontext setup hermes --source oceanbase/powercontext --ref v0.0.2
powercontext setup hermes --source oceanbase/powercontext --ref latest
```

The command copies the exclusive memory provider to
Expand Down Expand Up @@ -168,8 +168,15 @@ Memory entries.

The standalone companion registers `/pc` and `/powercontext` during normal
Hermes plugin discovery, before the first Agent is created. Both aliases are
handled by the PowerContext Memory Provider once it is active. Type `/pc ` or
`/powercontext ` and press Tab/Down to see the available first-level commands:
forwarded to the PowerContext Memory Provider for the current interactive
Hermes Agent once it is active. Type `/pc ` or `/powercontext ` and press
Tab/Down to see the available first-level commands:

Hermes v0.20.4 does not pass gateway session, user, workspace, or scope
context to plugin slash-command handlers. The companion therefore fails closed
for gateway invocations instead of routing a command to another session's
PowerContext scope. Use the provider's Hermes tools for gateway sessions until
Hermes exposes that invocation context.

```text
/pc trace status
Expand All @@ -196,6 +203,69 @@ handled by the PowerContext Memory Provider once it is active. Type `/pc ` or
/pc call OPERATION [PAYLOAD_JSON]
```

### Read, revise, or retire a memory entry

`/pc get` and `/pc retire` do not accept a search keyword or a bare
`entry_id`. They require the complete `citation` object returned by
`/pc search`, including the current Memory revision and the entry version.
Copy only the `hits[].citation` value from the search response, not the whole
hit object.

For example, first write a memory entry and then search for it:

```text
/pc remember preference "Prefers uv for Python project management"
/pc search uv
```

The relevant part of the `/pc search uv` response includes both the returned
text and the citation needed by the exact-entry commands. The identifiers and
revision below are illustrative; always copy them from the current response:

```json
{
"memory": {
"family": "memory",
"artifact_id": "memory",
"revision": 2
},
"mode": "fts",
"hits": [
{
"citation": {
"memory_ref": {
"family": "memory",
"artifact_id": "memory",
"revision": 2
},
"entry_id": "mem_ent_8f9653d66a664398aa18bc5c88e0283d",
"entry_version_id": "mem_ver_b12a8e6434254cae8a747792905006ed"
},
"text": "Prefers uv for Python project management (venv, dependency resolution, lockfile) over pip/Poetry/pip-tools."
}
]
}
```

Copy the `hits[0].citation` object from the actual response and use it as
follows:

```text
/pc get {"memory_ref":{"family":"memory","artifact_id":"memory","revision":2},"entry_id":"mem_ent_8f9653d66a664398aa18bc5c88e0283d","entry_version_id":"mem_ver_b12a8e6434254cae8a747792905006ed"}
/pc retire {"memory_ref":{"family":"memory","artifact_id":"memory","revision":2},"entry_id":"mem_ent_8f9653d66a664398aa18bc5c88e0283d","entry_version_id":"mem_ver_b12a8e6434254cae8a747792905006ed"} "no longer needed"
```

To revise instead of retiring, use the same citation with:

```text
/pc revise {"memory_ref":{"family":"memory","artifact_id":"memory","revision":2},"entry_id":"mem_ent_8f9653d66a664398aa18bc5c88e0283d","entry_version_id":"mem_ver_b12a8e6434254cae8a747792905006ed"} preference "Prefers uv for Python project management" "updated preference"
```

`retire` is a logical retirement; it removes the entry from active memory but
keeps its history. Because every memory mutation advances the artifact
revision, do not reuse this citation after `revise` or another write. Search
again and use the newest citation before the next `get`, `revise`, or `retire`.

Trace enable/disable changes the current Hermes process only. Configure
`evaluation_trace` or `POWERCONTEXT_HERMES_EVALUATION_TRACE` when tracing should
be enabled for future sessions. Trace files may contain prompts and recalled
Expand Down
17 changes: 12 additions & 5 deletions integrations/hermes/plugins/powercontext-command/README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
# PowerContext Hermes Command Companion

This standalone Hermes plugin registers `/pc` during normal plugin discovery,
before Hermes creates its first Agent. It forwards the command to the active
PowerContext Memory Provider once that provider is initialized.
This standalone Hermes plugin registers `/pc` and `/powercontext` during normal
plugin discovery, before Hermes creates its first Agent. It forwards either
command to the PowerContext Memory Provider for the current interactive Agent
once that provider is initialized.

Typing `/pc ` or `/powercontext ` and pressing Tab/Down shows the available
first-level PowerContext commands in Hermes' autocomplete menu.
Expand All @@ -11,9 +12,15 @@ The companion is installed alongside
[`plugins/powercontext`](../powercontext/README.md) by:

```bash
powercontext setup hermes --source oceanbase/powercontext --ref v0.0.2
powercontext setup hermes --source oceanbase/powercontext --ref latest
```

It requires Hermes Agent v0.20.4 or newer. The companion does not provide
memory storage or lifecycle hooks; those remain owned by the exclusive
`powercontext` Memory Provider.
`powercontext` Memory Provider. Hermes v0.20.4 does not provide gateway plugin
commands with caller session or scope context, so the companion fails closed
in gateway sessions to prevent cross-session memory access. Use the provider's
Hermes tools for gateway sessions until Hermes exposes that context.

The [provider README](../powercontext/README.md) contains the citation format
and examples for memory entry operations such as `/pc get` and `/pc retire`.
13 changes: 12 additions & 1 deletion integrations/hermes/plugins/powercontext-command/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
late for the TUI's initial slash-command registry. This small standalone
companion registers the command during normal plugin discovery and forwards to
the active provider once an Agent exists.

Hermes v0.20.4 invokes plugin command handlers with raw arguments only. The
gateway does not provide the caller's session, user, workspace, or scope to
the handler, so this companion only dispatches through Hermes' interactive CLI
reference. Gateway invocations fail closed instead of selecting a provider
from another session.
"""

from __future__ import annotations
Expand Down Expand Up @@ -55,7 +61,12 @@


def _active_provider(context: Any) -> Any | None:
"""Return the active PowerContext provider from the current CLI Agent."""
"""Return the provider for Hermes' current interactive CLI Agent.

``_cli_ref`` is set by the interactive CLI and is ``None`` in the gateway,
where Hermes v0.20.4 does not expose the invoking session to plugin
commands. Do not fall back to a cached or process-global provider.
"""

manager = getattr(context, "_manager", None)
cli = getattr(manager, "_cli_ref", None)
Expand Down
15 changes: 12 additions & 3 deletions integrations/hermes/plugins/powercontext/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ provider configuration is read from `$HERMES_HOME/powercontext/config.json`.
To install or refresh the provider from a matching PowerContext release tag:

```bash
powercontext setup hermes --source oceanbase/powercontext --ref v0.0.2
powercontext setup hermes --source oceanbase/powercontext --ref latest
powercontext doctor hermes
```

Expand Down Expand Up @@ -75,8 +75,14 @@ command can inspect, create, or clear the binding.
The standalone companion registers `/pc` and `/powercontext` during normal
Hermes plugin discovery, so both aliases are known before the first Agent is
created. Type `/pc ` or `/powercontext ` and press Tab/Down to see the
available first-level PowerContext commands. Once this provider is active, it
handles either command:
available first-level PowerContext commands. Once this provider is active, the
companion forwards either command to the current interactive Hermes Agent.

Hermes v0.20.4 does not pass gateway session, user, workspace, or scope
context to plugin slash-command handlers. The companion consequently fails
closed for gateway invocations rather than selecting another session's
provider. Use the provider's Hermes tools for gateway sessions until Hermes
exposes that invocation context.

```text
/pc trace status
Expand All @@ -103,6 +109,9 @@ handles either command:
/pc call OPERATION [PAYLOAD_JSON]
```

For the required citation format and copy-paste examples for `/pc get`,
`/pc revise`, and `/pc retire`, see the [memory entry operation guide](../../README.md#read-revise-or-retire-a-memory-entry).

## CLI commands

After enabling the provider and restarting Hermes so it discovers the command
Expand Down
20 changes: 8 additions & 12 deletions integrations/hermes/plugins/powercontext/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
from pathlib import Path
from typing import Any

from . import commands
from .client import PowerContextClient, PowerContextError
from .provider import PowerContextMemoryProvider

Expand All @@ -48,7 +47,14 @@ def _load_plugin_config() -> dict[str, Any]:


def register(ctx) -> None:
"""Register PowerContext with Hermes' memory provider registry and slash commands."""
"""Register PowerContext with Hermes' memory provider registry.

Slash commands are registered by the standalone ``powercontext-command``
companion. An exclusive memory provider can be initialized once per
Agent, while Hermes stores slash-command handlers on a process-global
registry; registering a provider-bound method here would therefore route
one session's command to another session's scope.
"""
provider = PowerContextMemoryProvider(_load_plugin_config())
ctx.register_memory_provider(provider)
register_skill = getattr(ctx, "register_skill", None)
Expand All @@ -59,16 +65,6 @@ def register(ctx) -> None:
skill_path,
"Use PowerContext memory, continuity, and review operations safely.",
)
register_command = getattr(ctx, "register_command", None)
if callable(register_command):
for name in ("pc", "powercontext"):
register_command(
name,
provider.handle_slash_command,
description="Inspect and manage PowerContext memory, handoffs, artifacts, and traces.",
args_hint="status|search|list|changes|get|remember|revise|retire|flush|stats|handoff|experience|skill|external-skills|review|workstream|trace|call ...",
)
commands.register_subcommands()


__all__ = ["PowerContextClient", "PowerContextError", "PowerContextMemoryProvider", "register"]
60 changes: 57 additions & 3 deletions integrations/hermes/plugins/powercontext/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,55 @@ def parse_json_object(value: str, label: str) -> dict[str, Any]:
return parsed


def _quoted_argument_end(value: str) -> int:
"""Return the end of the first shell-quoted argument in ``value``."""
if not value or value[0] not in {"'", '"'}:
raise ValueError("expected a quoted argument") # noqa: TRY003
quote = value[0]
escaped = False
for index, character in enumerate(value[1:], start=1):
if quote == '"' and escaped:
escaped = False
continue
if quote == '"' and character == "\\":
escaped = True
continue
if character == quote:
return index + 1
raise ValueError("unterminated quoted JSON argument") # noqa: TRY003


def _split_json_argument(raw_args: str, command: str, label: str) -> tuple[str, str]:
"""Extract one JSON object from a command and return it with its tail.

``shlex.split`` cannot be used on the complete command first because it
treats the whitespace and quotes inside an unwrapped JSON object as shell
syntax. Decode the JSON prefix from the raw string, then tokenize only
the arguments that follow it. A shell-quoted JSON object remains accepted
for compatibility with the previous command syntax.
"""
text = raw_args.strip()
tail = text[len(command) :].lstrip()
if not tail:
raise ValueError(f"{label} must be a JSON object") # noqa: TRY003

if tail[0] in {"'", '"'}:
end = _quoted_argument_end(tail)
tokens = shlex.split(tail[:end])
if len(tokens) != 1:
raise ValueError(f"{label} must be a JSON object") # noqa: TRY003
json_text = tokens[0]
else:
try:
_parsed, end = json.JSONDecoder().raw_decode(tail)
except json.JSONDecodeError as error:
raise ValueError(f"{label} must be a JSON object") from error # noqa: TRY003
json_text = tail[:end]

parse_json_object(json_text, label)
return json_text, tail[end:].lstrip()


def workstream_command(provider: Any, args: list[str]) -> str:
action = args[0].lower() if args else "status"
if action == "status":
Expand All @@ -148,7 +197,7 @@ def workstream_command(provider: Any, args: list[str]) -> str:
from .helpers import safe_scope

provider._workstream_bound_scope = safe_scope(args[1])
provider._scope_id = provider._workstream_bound_scope
provider._switch_workstream_scope(provider._workstream_bound_scope)
provider._record_trace_event("workstream_bound", scope_id=provider._scope_id, path=str(path))
return json.dumps(
{"status": "bound", "scope_id": provider._scope_id, "path": str(path)},
Expand Down Expand Up @@ -338,8 +387,13 @@ def handle_slash_command(provider: Any, raw_args: str) -> str: # noqa: C901
logger.debug("PowerContext /pc command failed: %s", error)
return tool_error(f"PowerContext operation failed: {error}")
try:
args = shlex.split(raw_args)
except ValueError as error:
command = raw_parts[0].lower() if raw_parts else ""
if command in {"get", "revise", "retire"}:
citation, remainder = _split_json_argument(raw_args, raw_parts[0], "citation")
args = [command, citation, *shlex.split(remainder)]
else:
args = shlex.split(raw_args)
except (ValueError, TypeError) as error:
return tool_error(f"Invalid /pc arguments: {error}")
if not args or args[0].lower() in {"help", "-h", "--help"}:
return (
Expand Down
Loading
Loading