chore: delete orphaned bench data, datagen examples and stale one-off docs

Nothing in the tree reads any of these; they landed with feature PRs and
were never routed to their proper home.

- mcp-research-data/: 224K of July tool-search bench result rows. The
  harnesses (scripts/tool_search_livetest_ue*.py) write their output to a
  gitignored dir; the rows were committed by hand once and the headline
  numbers already live in the bench commit messages.
- datagen-config-examples/: Feb 2026 RL datagen configs for a
  WebResearchEnv that no longer exists; the yaml paths point at a
  configs/ dir that was never created.
- docs/: ADR log with one entry, an implemented cron-doctor spec, an RCA
  for a resolved bug, two RFCs whose work shipped, an unimplemented
  profile-builder proposal, the kanban dialog mock HTML and the kanban v1
  spec PDF. profile-routing.md duplicated the profile_routes section of
  website/docs/user-guide/multi-profile-gateways.md.

Kanban docs and the `hermes kanban` parser description pointed readers at
the PDF; those now point at the user guide (the patterns table it was
citing is on that same page).
This commit is contained in:
teknium1
2026-09-13 05:35:24 -07:00
committed by Teknium
parent 956967fbdc
commit 0c0875b746
23 changed files with 5 additions and 8960 deletions
-77
View File
@@ -1,77 +0,0 @@
# Architecture Decision Records
## 2026-07-13: Scope plugin manager state by Hermes home/profile (keyed cache)
Status: Accepted
Context:
Hermes supports multiple profiles via different Hermes home directories.
Homes are switched two ways in a running process: the `HERMES_HOME`
environment variable (single-profile CLI/gateway processes), and the
context-local `set_hermes_home_override()` (`hermes_constants.py`), which
the multiplexed gateway worker (`gateway/run.py`'s `_profile_scope`) and
subagent/embedded callers use to serve several profiles from one
long-lived process. The override is a `ContextVar` and deliberately does
**not** mutate `os.environ`, since that would leak one profile's home
into every other concurrent task in the same process.
The plugin manager was a process-global single-slot singleton
(`_plugin_manager`). User-installed plugins are discovered from
`get_hermes_home() / "plugins"`, and context-engine plugins (e.g.
`hermes-lcm`) capture profile-scoped state — such as the LCM database
path — at registration time. A single-slot cache meant:
1. Switching homes via `set_hermes_home_override()` was invisible to a
naive "did `HERMES_HOME` change" check, so the singleton silently kept
serving the first profile's manager to every other profile in the
process.
2. Even when a fresh `PluginManager` *was* created for a new home, plugin
modules are imported into `sys.modules` as `hermes_plugins.<slug>` by
`_load_directory_module`, and only that top-level module was ever
replaced. A same-slug plugin's *relative* imports
(`from . import state`) are cached separately under
`hermes_plugins.<slug>.<submodule>`, and Python's import machinery
resolves those from `sys.modules` first — so a profile switch could
silently keep serving a previous profile's already-imported submodule
code/state instead of re-executing the new profile's plugin.
Decision:
- Replace the single-slot singleton with a cache keyed on the *resolved*
Hermes home path (`_plugin_managers_by_home: Dict[Path, PluginManager]`).
`get_plugin_manager()` resolves the current home via `get_hermes_home()`
(which itself already consults `get_hermes_home_override()` before
`os.environ`), so both the env-var and context-local override paths are
covered uniformly.
- `_plugin_manager` (the old single-slot name) is kept as a thin "last
manager returned" pointer purely for backward compatibility with
existing test code that does
`monkeypatch.setattr(plugins_mod, "_plugin_manager", some_manager)`.
When that name is monkeypatched to a manager the keyed cache doesn't
know about, `get_plugin_manager()` treats it as an explicit injection
and adopts it into the cache under the *current* resolved home, rather
than discarding it.
- Both `PluginManager._load_directory_module` (initial/`force=True`
reload within the same home) and the shared `_clear_plugin_submodules`
helper (profile switch / test teardown) evict `sys.modules[module_name]`
**and every name prefixed with `module_name + "."`** before a plugin
slug is (re-)imported, so relative-import submodules can never survive
a reload or a home switch.
- Test isolation (`tests/conftest.py`'s `_hermetic_environment` fixture)
calls a new `_reset_plugin_managers_for_tests()` helper that drops the
entire keyed cache and purges every plugin submodule from `sys.modules`
between tests, instead of only resetting the single-slot pointer.
Consequences:
- Per-profile LCM instances (and any other context-engine plugin) use
their own `{home}/lcm.db` regardless of whether the profile switch went
through `HERMES_HOME` or `set_hermes_home_override()`.
- Plugin discovery remains cached within a profile for normal
performance, and re-entering a previously-seen profile reuses its
cached manager instead of rebuilding from scratch.
- Sequential *and* interleaved profile switching — in tests, the gateway
multiplexer worker, or embedded callers using the context-local
override — no longer leaks context-engine state, plugin module state,
or stale relative-import submodules across profiles.
- Regression coverage exercises the real production path
(`set_hermes_home_override()`) rather than only the env-var path, and
includes a dedicated relative-import leak test.
-32
View File
@@ -1,32 +0,0 @@
# Cron Doctor Spec
## Problem
Scheduled jobs can silently degrade when a script is moved, a workdir disappears,
a provider run fails, or delivery starts failing. `hermes cron list` shows some of
this inline, but there is no compact read-only health check that can be run from a
terminal, cron job, or CI-style smoke check.
## Goal
Add `hermes cron doctor` as a read-only diagnostic command that summarizes cron
job health and exits non-zero when actionable issues are found.
## Non-goals
- Do not mutate jobs or auto-repair state.
- Do not start/stop the gateway.
- Do not inspect secrets or print credentials.
## Acceptance criteria
- `hermes cron doctor` returns `0` and prints a healthy message when active jobs
have no detected issues.
- It returns `1` and prints grouped job-level issues when any active job has:
- last run failure (`last_status` not `ok`),
- last delivery failure,
- no `next_run_at` while still active,
- `no_agent` enabled without a script,
- script path missing/outside `HERMES_HOME/scripts`, or
- configured workdir path missing.
- Parser, command dispatch, and focused tests cover the new subcommand.
-903
View File
@@ -1,903 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hermes Kanban — Native Dialog Prototypes</title>
<style>
/* =========================================================== */
/* Design tokens — host @nous-research/ui, oklch→sRGB approx. */
/* =========================================================== */
:root {
--bg: #ffffff;
--bg-subtle: #f8f9fa;
--bg-muted: #f1f3f5;
--border: #e5e7eb;
--border-strong: #d1d5db;
--fg: #0f172a;
--fg-muted: #64748b;
--fg-subtle: #94a3b8;
--ring: #94a3b8;
--accent: #2563eb;
--accent-fg: #ffffff;
--destructive: #dc2626;
--destructive-fg: #ffffff;
--success: #16a34a;
--shadow-md: 0 4px 12px -2px rgba(15, 23, 42, 0.10),
0 2px 4px -2px rgba(15, 23, 42, 0.06);
--shadow-lg: 0 20px 25px -5px rgba(15, 23, 42, 0.10),
0 8px 10px -6px rgba(15, 23, 42, 0.04);
--radius: 10px;
--radius-sm: 6px;
--font: ui-sans-serif, system-ui, -apple-system, "Segoe UI",
Roboto, "Helvetica Neue", Arial, sans-serif;
--mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0b0d10;
--bg-subtle: #11141a;
--bg-muted: #161a22;
--border: #232833;
--border-strong: #2c3140;
--fg: #e6e8ec;
--fg-muted: #9aa3b2;
--fg-subtle: #6b7280;
--ring: #4b5563;
--accent: #3b82f6;
--accent-fg: #ffffff;
--destructive: #ef4444;
--destructive-fg: #ffffff;
--success: #22c55e;
}
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
font-family: var(--font);
color: var(--fg);
background: var(--bg-subtle);
line-height: 1.5;
-webkit-font-smoothing: antialiased;
}
/* =========================================================== */
/* Page chrome */
/* =========================================================== */
header.page {
padding: 24px 32px 16px;
border-bottom: 1px solid var(--border);
background: var(--bg);
}
header.page h1 {
font-size: 18px; font-weight: 600; margin: 0 0 4px;
letter-spacing: -0.01em;
}
header.page p {
font-size: 13px; color: var(--fg-muted); margin: 0;
max-width: 920px;
}
header.page .controls {
margin-top: 14px; display: flex; gap: 8px; flex-wrap: wrap;
}
header.page .controls button {
font: inherit; font-size: 12px; font-weight: 500;
padding: 6px 12px; border-radius: var(--radius-sm);
border: 1px solid var(--border); background: var(--bg);
color: var(--fg); cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
header.page .controls button:hover { background: var(--bg-muted); }
header.page .controls button.active {
background: var(--accent); border-color: var(--accent); color: var(--accent-fg);
}
.board {
padding: 24px 32px 80px;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 20px;
max-width: 1700px;
}
@media (max-width: 1400px) { .board { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 720px) { .board { grid-template-columns: 1fr; } }
section.variant {
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius);
overflow: hidden;
display: flex; flex-direction: column;
min-width: 0;
}
section.variant header {
padding: 14px 16px 12px;
border-bottom: 1px solid var(--border);
background: var(--bg-subtle);
}
section.variant header h2 {
font-size: 11px; font-weight: 600; margin: 0 0 2px;
letter-spacing: 0.08em; text-transform: uppercase;
color: var(--fg-muted);
}
section.variant header .label {
font-size: 15px; font-weight: 600; color: var(--fg);
letter-spacing: -0.01em;
}
section.variant header p {
font-size: 12px; color: var(--fg-muted); margin: 6px 0 0;
line-height: 1.4;
}
section.variant .stage {
flex: 1;
padding: 24px 16px;
display: flex; flex-direction: column; align-items: center;
justify-content: flex-start;
background: var(--bg);
min-height: 540px;
position: relative;
}
section.variant .actions {
padding: 10px 16px;
border-top: 1px solid var(--border);
display: flex; flex-wrap: wrap; gap: 6px;
background: var(--bg-subtle);
}
section.variant .actions button {
font: inherit; font-size: 11px;
padding: 5px 10px; border-radius: var(--radius-sm);
border: 1px solid var(--border); background: var(--bg);
color: var(--fg-muted); cursor: pointer;
}
section.variant .actions button:hover {
border-color: var(--border-strong); color: var(--fg);
}
section.variant .actions .trash {
color: var(--destructive); border-color: var(--destructive);
background: color-mix(in srgb, var(--destructive) 6%, var(--bg));
}
section.variant .note {
font-size: 11px; color: var(--fg-muted);
padding: 8px 12px; background: var(--bg-muted);
border-top: 1px solid var(--border);
line-height: 1.45;
}
section.variant .note strong { color: var(--fg); }
section.variant .note code {
font-family: var(--mono); font-size: 10px;
background: var(--bg); padding: 1px 4px; border-radius: 3px;
border: 1px solid var(--border);
}
/* =========================================================== */
/* Backdrop + dialog (shared) */
/* =========================================================== */
.backdrop {
position: absolute; inset: 0;
background: rgba(15, 23, 42, 0.45);
backdrop-filter: blur(2px);
display: flex; align-items: center; justify-content: center;
z-index: 10;
animation: fade-in 160ms ease both;
padding: 16px;
}
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes dialog-in {
from { opacity: 0; transform: translateY(4px) scale(0.98); }
to { opacity: 1; transform: none; }
}
.dialog {
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow-lg);
width: 100%; max-width: 440px;
padding: 20px;
animation: dialog-in 180ms cubic-bezier(.2,.8,.2,1) both;
font-size: 14px;
}
.dialog h3 {
margin: 0; font-size: 16px; font-weight: 600;
letter-spacing: -0.01em; display: flex; align-items: center; gap: 10px;
color: var(--fg);
}
.dialog p.desc {
margin: 8px 0 0; color: var(--fg-muted); font-size: 13px;
line-height: 1.45;
}
.dialog .body { margin-top: 14px; }
.dialog .actions {
margin-top: 20px;
display: flex; justify-content: flex-end; gap: 8px;
}
.dialog button {
font: inherit; font-size: 13px; font-weight: 500;
padding: 8px 14px; border-radius: var(--radius-sm);
border: 1px solid var(--border); background: var(--bg);
color: var(--fg); cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
.dialog button:hover { background: var(--bg-muted); }
.dialog button:focus-visible {
outline: 2px solid var(--ring); outline-offset: 2px;
}
.dialog button.primary {
background: var(--accent); border-color: var(--accent); color: var(--accent-fg);
}
.dialog button.primary:hover {
background: color-mix(in srgb, var(--accent) 88%, black);
}
.dialog button.destructive {
background: var(--destructive); border-color: var(--destructive); color: var(--destructive-fg);
}
.dialog button.destructive:hover {
background: color-mix(in srgb, var(--destructive) 88%, black);
}
.dialog button:disabled { opacity: 0.5; cursor: not-allowed; }
.dialog .spinner {
display: inline-block;
width: 12px; height: 12px;
border: 2px solid currentColor;
border-right-color: transparent;
border-radius: 50%;
animation: spin 0.7s linear infinite;
vertical-align: -2px;
margin-right: 6px;
}
@keyframes spin { to { transform: rotate(360deg); } }
.dialog textarea, .dialog input[type="text"] {
font: inherit; font-size: 13px;
width: 100%; padding: 8px 10px;
border: 1px solid var(--border-strong); border-radius: var(--radius-sm);
background: var(--bg); color: var(--fg);
resize: vertical;
}
.dialog textarea:focus, .dialog input[type="text"]:focus {
outline: 2px solid var(--ring); outline-offset: -1px; border-color: var(--ring);
}
.dialog textarea.invalid, .dialog input.invalid {
border-color: var(--destructive);
}
.dialog .helper {
font-size: 11px; color: var(--fg-muted);
margin-top: 4px; min-height: 16px;
}
.dialog .helper.error { color: var(--destructive); }
/* =========================================================== */
/* Icons (inline SVG, Lucide-style) */
/* =========================================================== */
.ico { width: 18px; height: 18px; stroke: currentColor; fill: none;
stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;
flex-shrink: 0; }
.ico.muted { color: var(--fg-muted); }
.ico.destructive { color: var(--destructive); }
.ico.success { color: var(--success); }
/* =========================================================== */
/* Toast container (Variant C) */
/* =========================================================== */
.toast-container {
position: absolute; right: 16px; bottom: 16px;
display: flex; flex-direction: column-reverse; gap: 8px;
z-index: 11; width: 320px;
pointer-events: none;
}
.toast {
background: var(--fg);
color: var(--bg);
border-radius: var(--radius-sm);
padding: 10px 12px;
box-shadow: var(--shadow-lg);
display: flex; flex-direction: column; gap: 6px;
pointer-events: auto;
animation: toast-in 220ms cubic-bezier(.2,.8,.2,1) both;
font-size: 13px;
}
.toast.error { background: var(--destructive); color: var(--destructive-fg); }
@keyframes toast-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: none; }
}
.toast .title {
display: flex; align-items: center; gap: 8px;
font-weight: 600;
}
.toast .desc { font-size: 12px; opacity: 0.85; }
.toast .row {
display: flex; align-items: center; justify-content: space-between; gap: 8px;
}
.toast .undo {
font: inherit; font-size: 11px; font-weight: 600;
padding: 4px 10px; border-radius: var(--radius-sm);
background: transparent; color: inherit;
border: 1px solid currentColor;
cursor: pointer;
text-transform: uppercase; letter-spacing: 0.06em;
}
.toast .undo:hover { background: rgba(255,255,255,0.12); }
/* =========================================================== */
/* Bulk-many list (Variant B-refined) */
/* =========================================================== */
.bulk-list {
margin-top: 14px;
border: 1px solid var(--border); border-radius: var(--radius-sm);
background: var(--bg-subtle);
max-height: 200px; overflow-y: auto;
}
.bulk-item {
padding: 8px 10px;
border-bottom: 1px solid var(--border);
display: flex; align-items: flex-start; gap: 8px;
font-size: 12px;
}
.bulk-item:last-child { border-bottom: none; }
.bulk-item .meta { flex: 1; min-width: 0; }
.bulk-item .meta .title {
font-weight: 500; color: var(--fg);
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.bulk-item .meta .id {
font-family: var(--mono); font-size: 10px; color: var(--fg-subtle);
margin-top: 1px;
}
.bulk-item textarea {
font: inherit; font-size: 11px;
width: 100%; padding: 4px 6px;
border: 1px solid var(--border); border-radius: 4px;
background: var(--bg); color: var(--fg);
margin-top: 4px;
min-height: 22px; resize: vertical;
}
/* =========================================================== */
/* Decision legend */
/* =========================================================== */
.legend {
padding: 16px 32px 24px;
background: var(--bg);
border-top: 1px solid var(--border);
font-size: 12px; color: var(--fg-muted);
max-width: 1700px;
}
.legend h3 {
font-size: 11px; font-weight: 600; color: var(--fg);
letter-spacing: 0.08em; text-transform: uppercase;
margin: 0 0 8px;
}
.legend table { border-collapse: collapse; width: 100%; max-width: 1100px; }
.legend th, .legend td {
text-align: left; padding: 6px 10px;
border-bottom: 1px solid var(--border);
font-size: 12px;
}
.legend th { color: var(--fg); font-weight: 600; }
.legend td.yes { color: var(--success); }
.legend td.no { color: var(--fg-subtle); }
.legend td.partial { color: var(--accent); }
</style>
</head>
<body>
<header class="page">
<h1>Hermes Kanban — Native Dialog Prototypes</h1>
<p>
Four approaches to replacing <code>window.confirm()</code>,
<code>window.prompt()</code>, and <code>window.alert()</code> in
<code>plugins/kanban/dashboard/dist/index.js</code>. Click a page-level
trigger to fire the same flow in every variant simultaneously, or use the
per-variant buttons to fire flows unique to that variant.
</p>
<div class="controls">
<button data-trigger="move-done">Trigger: Mark Done (with summary)</button>
<button data-trigger="move-blocked">Trigger: Mark Blocked</button>
<button data-trigger="bulk-delete">Trigger: Bulk delete (3 tasks)</button>
<button data-trigger="archive-board">Trigger: Archive board</button>
<button data-trigger="remove-attachment">Trigger: Remove attachment</button>
<button data-trigger="error">Trigger: Error toast</button>
<button data-trigger="clear">Clear all stages</button>
</div>
</header>
<div class="board">
<!-- ============================================================ -->
<!-- VARIANT A — Conservative -->
<!-- ============================================================ -->
<section class="variant" data-variant="A">
<header>
<h2>Variant A</h2>
<div class="label">Conservative</div>
<p>Direct 1:1 mapping to the host's <code>ConfirmDialog</code>. Single-line input. Minimal chrome.</p>
</header>
<div class="stage" data-stage="A">
<div class="placeholder">Click a trigger to preview.</div>
</div>
<div class="note">
<strong>Trade-off:</strong> Safest to ship — zero new components, zero new
patterns. Fails the GPT-OSS review on three points: no multi-line
summary, validation triggers a SECOND dialog instead of inline, no bulk
affordance.
</div>
</section>
<!-- ============================================================ -->
<!-- VARIANT B — Strong-fit (Pro's pick) -->
<!-- ============================================================ -->
<section class="variant" data-variant="B">
<header>
<h2>Variant B</h2>
<div class="label">Strong-fit (Pro's pick)</div>
<p>Textarea + contextual SVG icon + inline validation + pluralized copy. What the design brief recommends.</p>
</header>
<div class="stage" data-stage="B">
<div class="placeholder">Click a trigger to preview.</div>
</div>
<div class="note">
<strong>Trade-off:</strong> Best baseline, but Pro suggested <em>either</em>
a disabled-button <em>or</em> an inline error — GPT-OSS caught that both
are needed (button disabled AND error visible) for screen-reader users.
Bottom-sheet on mobile is the right move but still has keyboard edge cases.
</div>
</section>
<!-- ============================================================ -->
<!-- VARIANT B-refined (Pro + GPT-OSS synthesis) -->
<!-- ============================================================ -->
<section class="variant" data-variant="B2">
<header>
<h2>Variant B-refined</h2>
<div class="label">Synthesis (recommended)</div>
<p>All of B's improvements + GPT-OSS fixes: auto-focus, dual-validation, cancellable-spinner, per-task summaries in bulk.</p>
</header>
<div class="stage" data-stage="B2">
<div class="placeholder">Click a trigger to preview.</div>
</div>
<div class="note">
<strong>Why this is the recommendation:</strong> Single contextual icon
(not four) keeps the title readable. Confirm button stays enabled until
textarea has content; the inline error appears on submit-attempted-empty
AND on blur if still empty. Cancel button stays clickable during the
PATCH (only the confirm shows the spinner) so users can abort slow
networks. Bulk-many shows an expandable list with per-task summary
fields.
</div>
</section>
<!-- ============================================================ -->
<!-- VARIANT C — Divergent (undo toast, non-destructive only) -->
<!-- ============================================================ -->
<section class="variant" data-variant="C">
<header>
<h2>Variant C</h2>
<div class="label">Divergent: undo toast</div>
<p>Skip the modal entirely for non-destructive moves. Optimistic UI + 5s undo in a bottom-right toast.</p>
</header>
<div class="stage" data-stage="C">
<div class="placeholder">Click a trigger to preview.</div>
<div class="toast-container" data-toasts></div>
</div>
<div class="note">
<strong>Trade-off:</strong> Radical speedup for routine moves, but breaks
the required-summary flow (you can't optimistically "complete" a task
that's missing required schema data). Best used as a
<em>complement</em> to B-refined — undo toast for the safe moves,
modal for <code>done</code>/<code>blocked</code>/<code>archive</code>.
</div>
</section>
</div>
<div class="legend">
<h3>Decision matrix — recommended pick: B-refined</h3>
<table>
<thead>
<tr><th>Capability</th><th>A</th><th>B</th><th>B-refined</th><th>C</th></tr>
</thead>
<tbody>
<tr><td>Centered modal (Radix)</td> <td class="yes">✓</td> <td class="yes">✓</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Multi-line summary</td> <td class="no">✗</td> <td class="yes">✓</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Single contextual icon</td> <td class="no">✗</td> <td class="partial">4</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Inline validation (no second dialog)</td><td class="no">✗</td> <td class="partial">~</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Disabled button + persistent error</td> <td class="no">✗</td> <td class="partial">~</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Cancellable spinner during PATCH</td> <td class="no">✗</td> <td class="no">✗</td> <td class="yes">✓</td> <td class="yes">✓</td></tr>
<tr><td>Bulk-many expandable list</td> <td class="no">✗</td> <td class="no">✗</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Auto-focus textarea + mobile scroll</td> <td class="no">✗</td> <td class="partial">~</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
<tr><td>Toast on success</td> <td class="no">✗</td> <td class="no">✗</td> <td class="no">✗</td> <td class="yes">✓</td></tr>
<tr><td>Toast on error</td> <td class="no">✗</td> <td class="no">✗</td> <td class="partial">opt.</td> <td class="yes">✓</td></tr>
<tr><td>Survives the required-summary flow</td> <td class="no">✗</td> <td class="yes">✓</td> <td class="yes">✓</td> <td class="no">✗</td></tr>
</tbody>
</table>
</div>
<script>
/* =========================================================== */
/* Shared icon library (inline SVG) */
/* =========================================================== */
const ICONS = {
check: '<svg class="ico success" viewBox="0 0 24 24"><path d="M20 6 9 17l-5-5"/></svg>',
archive: '<svg class="ico muted" viewBox="0 0 24 24"><rect x="2" y="4" width="20" height="5" rx="1"/><path d="M4 9v9a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9"/><path d="M10 13h4"/></svg>',
pause: '<svg class="ico muted" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M10 9v6M14 9v6"/></svg>',
trash: '<svg class="ico destructive" viewBox="0 0 24 24"><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/></svg>',
paperclip:'<svg class="ico muted" viewBox="0 0 24 24"><path d="m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 17.93 8.8l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"/></svg>',
info: '<svg class="ico muted" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4M12 8h.01"/></svg>',
x: '<svg class="ico" viewBox="0 0 24 24"><path d="M18 6 6 18M6 6l12 12"/></svg>',
undo: '<svg class="ico" viewBox="0 0 24 24"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15-6.7L3 13"/></svg>',
};
/* =========================================================== */
/* Dialog factories */
/* Each factory: (stage, opts) => void; clears stage, mounts */
/* backdrop + dialog. */
/* =========================================================== */
function clearStage(stage) {
// Remove everything except the toast container (for variant C)
const toastContainer = stage.querySelector('.toast-container');
stage.innerHTML = '';
if (toastContainer) stage.appendChild(toastContainer);
}
function mountBackdrop(stage, dialog) {
const backdrop = document.createElement('div');
backdrop.className = 'backdrop';
backdrop.appendChild(dialog);
stage.appendChild(backdrop);
return backdrop;
}
/* ----- Variant A: Conservative -------------------------------- */
function A_moveDone(stage) {
clearStage(stage);
const dlg = document.createElement('div');
dlg.className = 'dialog';
dlg.innerHTML = `
<h3>Mark this task as done?</h3>
<p class="desc">The worker's claim is released and dependent children become ready.</p>
<div class="body">
<input type="text" placeholder="Completion summary" />
</div>
<div class="actions">
<button data-act="cancel">Cancel</button>
<button data-act="confirm" class="primary">Mark Done</button>
</div>
`;
const backdrop = mountBackdrop(stage, dlg);
dlg.querySelector('[data-act=cancel]').onclick = () => clearStage(stage);
dlg.querySelector('[data-act=confirm]').onclick = () => {
// No validation — just shows another alert if empty (current bug)
const v = dlg.querySelector('input').value.trim();
if (!v) { window.alert('Completion summary is required before marking a task done.'); return; }
clearStage(stage);
};
backdrop.onclick = (e) => { if (e.target === backdrop) clearStage(stage); };
}
/* ----- Variant B: Strong-fit ----------------------------------- */
function B_moveDone(stage) {
clearStage(stage);
const dlg = document.createElement('div');
dlg.className = 'dialog';
dlg.innerHTML = `
<h3>${ICONS.check} Mark this task as done?</h3>
<p class="desc">The worker's claim is released and dependent children become ready.</p>
<div class="body">
<textarea rows="3" placeholder="Completion summary — this is stored as the task result."></textarea>
<div class="helper" data-helper></div>
</div>
<div class="actions">
<button data-act="cancel">Cancel</button>
<button data-act="confirm" class="primary">Mark Done</button>
</div>
`;
const backdrop = mountBackdrop(stage, dlg);
const ta = dlg.querySelector('textarea');
const helper = dlg.querySelector('[data-helper]');
const confirm = dlg.querySelector('[data-act=confirm]');
// Pro suggested either disabled OR error — let's show the error path
confirm.onclick = () => {
if (!ta.value.trim()) {
helper.classList.add('error');
helper.textContent = 'Completion summary is required before marking a task done.';
ta.classList.add('invalid');
ta.focus();
return;
}
// Simulate PATCH
confirm.disabled = true;
confirm.innerHTML = '<span class="spinner"></span>Marking done…';
setTimeout(() => clearStage(stage), 1200);
};
dlg.querySelector('[data-act=cancel]').onclick = () => clearStage(stage);
backdrop.onclick = (e) => { if (e.target === backdrop) clearStage(stage); };
}
/* ----- Variant B-refined: synthesis ---------------------------- */
function B2_moveDone(stage, count) {
clearStage(stage);
const isBulk = count && count > 1;
const label = isBulk ? `${count} selected tasks` : 'this task';
const title = isBulk ? `Mark ${count} tasks as done?` : 'Mark this task as done?';
const dlg = document.createElement('div');
dlg.className = 'dialog';
dlg.innerHTML = `
<h3>${ICONS.check} ${title}</h3>
<p class="desc">The worker's claim is released and dependent children become ready.</p>
<div class="body">
<textarea rows="3" autofocus placeholder="Completion summary for ${label}. This is stored as the task result."></textarea>
<div class="helper" data-helper></div>
${isBulk ? bulkList() : ''}
</div>
<div class="actions">
<button data-act="cancel">Cancel</button>
<button data-act="confirm" class="primary" disabled>Mark Done</button>
</div>
`;
const backdrop = mountBackdrop(stage, dlg);
const ta = dlg.querySelector('textarea');
const helper = dlg.querySelector('[data-helper]');
const confirm = dlg.querySelector('[data-act=confirm]');
const cancel = dlg.querySelector('[data-act=cancel]');
const REQUIRED = 'Completion summary is required before marking a task done.';
// Auto-focus + ensure visible on mobile keyboards (best-effort)
setTimeout(() => {
ta.focus();
ta.scrollIntoView({ block: 'center', behavior: 'smooth' });
}, 50);
ta.addEventListener('input', () => {
const valid = ta.value.trim().length > 0;
confirm.disabled = !valid;
if (valid) {
ta.classList.remove('invalid');
helper.classList.remove('error');
helper.textContent = '';
}
});
ta.addEventListener('blur', () => {
if (!ta.value.trim()) {
ta.classList.add('invalid');
helper.classList.add('error');
helper.textContent = REQUIRED;
}
});
confirm.onclick = () => {
if (!ta.value.trim()) {
ta.classList.add('invalid');
helper.classList.add('error');
helper.textContent = REQUIRED;
ta.focus();
return;
}
// Cancel stays enabled; only confirm gets the spinner (GPT-OSS fix)
confirm.disabled = true;
confirm.innerHTML = '<span class="spinner"></span>Marking done…';
setTimeout(() => clearStage(stage), 1200);
};
cancel.onclick = () => clearStage(stage);
backdrop.onclick = (e) => { if (e.target === backdrop) clearStage(stage); };
// Cmd/Ctrl + Enter submits
ta.addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && !confirm.disabled) {
confirm.click();
}
});
}
/* Helper: bulk list markup for B-refined bulk-many dialogs */
function bulkList() {
const items = [
{ id: 't_8c41', title: 'Refactor kanban dispatcher tick interval' },
{ id: 't_8d12', title: 'Add batch delete endpoint smoke test' },
{ id: 't_8e09', title: 'Document goal_mode lifecycle in user guide' },
];
return `
<div class="bulk-list">
${items.map(t => `
<div class="bulk-item">
<div class="meta">
<div class="title">${t.title}</div>
<div class="id">${t.id}</div>
<textarea rows="1" placeholder="Completion summary for this task…"></textarea>
</div>
</div>
`).join('')}
</div>
`;
}
/* ----- Generic destructive confirm (used by A/B for blocked/archive/delete) -- */
function makeConfirm(stage, opts) {
const { icon, title, desc, confirmLabel, destructive, requireReason } = opts;
const dlg = document.createElement('div');
dlg.className = 'dialog';
dlg.innerHTML = `
<h3>${icon} ${title}</h3>
<p class="desc">${desc}</p>
${requireReason ? `
<div class="body">
<textarea rows="2" placeholder="${requireReason}"></textarea>
<div class="helper" data-helper></div>
</div>
` : ''}
<div class="actions">
<button data-act="cancel">Cancel</button>
<button data-act="confirm" class="${destructive ? 'destructive' : 'primary'}">${confirmLabel}</button>
</div>
`;
const backdrop = mountBackdrop(stage, dlg);
const confirm = dlg.querySelector('[data-act=confirm]');
if (requireReason) {
const ta = dlg.querySelector('textarea');
confirm.disabled = true;
ta.addEventListener('input', () => { confirm.disabled = ta.value.trim().length === 0; });
}
dlg.querySelector('[data-act=cancel]').onclick = () => clearStage(stage);
confirm.onclick = () => {
confirm.disabled = true;
confirm.innerHTML = '<span class="spinner"></span>Working…';
setTimeout(() => clearStage(stage), 800);
};
backdrop.onclick = (e) => { if (e.target === backdrop) clearStage(stage); };
}
const makeA_confirm = (s, o) => makeConfirm(s, o);
const makeB_confirm = (s, o) => makeConfirm(s, o);
const makeB2_confirm = (s, o) => makeConfirm(s, o);
/* ----- Variant C: undo toast ----------------------------------- */
function C_undoToast(stage, message, desc) {
const container = stage.querySelector('.toast-container');
const toast = document.createElement('div');
toast.className = 'toast';
toast.innerHTML = `
<div class="title">${ICONS.check} ${message}</div>
${desc ? `<div class="desc">${desc}</div>` : ''}
<div class="row">
<span style="opacity:0.6; font-size: 10px;">Auto-dismiss in 5s</span>
<button class="undo" data-act="undo">Undo</button>
</div>
`;
container.appendChild(toast);
setTimeout(() => toast.remove(), 5200);
toast.querySelector('[data-act=undo]').onclick = () => {
toast.style.opacity = '0';
toast.style.transition = 'opacity 200ms';
setTimeout(() => toast.remove(), 220);
};
}
function C_errorToast(stage, message) {
const container = stage.querySelector('.toast-container');
const toast = document.createElement('div');
toast.className = 'toast error';
toast.dataset.sticky = '1'; // visual marker; doesn't actually stop dismissal
toast.innerHTML = `
<div class="title">${ICONS.x} ${message}</div>
`;
container.appendChild(toast);
// Longer dismiss for screenshot stability
setTimeout(() => toast.remove(), 30000);
}
/* =========================================================== */
/* Dispatch table — fires the right handler per variant */
/* =========================================================== */
const HANDLERS = {
'move-done': () => {
A_moveDone(stage('A'));
B_moveDone(stage('B'));
B2_moveDone(stage('B2'), 1);
C_undoToast(stage('C'), 'Task marked as done', 'The worker claim has been released.');
},
'move-blocked': () => {
const opts = (variant) => ({
icon: variant === 'A' ? '' : ICONS.pause,
title: 'Mark this task as blocked?',
desc: "The worker's claim is released.",
confirmLabel: 'Mark Blocked',
destructive: false,
});
makeA_confirm(stage('A'), opts('A'));
makeB_confirm(stage('B'), opts('B'));
makeB2_confirm(stage('B2'), opts('B2'));
C_undoToast(stage('C'), 'Task marked as blocked', 'Worker claim released. Worker will re-prompt on unblock.');
},
'bulk-delete': () => {
const isBulk = true;
const count = 3;
const titleAll = isBulk
? `Permanently delete ${count} selected tasks?`
: 'Permanently delete this task?';
const opts = (variant) => ({
icon: variant === 'A' ? '' : ICONS.trash,
title: titleAll,
desc: 'This cannot be undone.',
confirmLabel: isBulk ? `Delete ${count} tasks` : 'Delete',
destructive: true,
requireReason: variant === 'B2' ? 'Optional: why are these being deleted?' : null,
});
makeA_confirm(stage('A'), opts('A'));
makeB_confirm(stage('B'), opts('B'));
// B2 gets the bulk list version
clearStage(stage('B2'));
const dlg = document.createElement('div');
dlg.className = 'dialog';
dlg.innerHTML = `
<h3>${ICONS.trash} Permanently delete 3 selected tasks?</h3>
<p class="desc">This cannot be undone.</p>
<div class="body">${bulkList()}</div>
<div class="actions">
<button data-act="cancel">Cancel</button>
<button data-act="confirm" class="destructive">Delete 3 tasks</button>
</div>
`;
const backdrop = mountBackdrop(stage('B2'), dlg);
dlg.querySelector('[data-act=cancel]').onclick = () => clearStage(stage('B2'));
dlg.querySelector('[data-act=confirm]').onclick = () => {
dlg.querySelector('[data-act=confirm]').disabled = true;
dlg.querySelector('[data-act=confirm]').innerHTML = '<span class="spinner"></span>Deleting…';
setTimeout(() => clearStage(stage('B2')), 1200);
};
backdrop.onclick = (e) => { if (e.target === backdrop) clearStage(stage('B2')); };
C_errorToast(stage('C'), 'Bulk delete is destructive — undo toast not appropriate.');
},
'archive-board': () => {
const msg = "Archive board 'atm10-server'? It will be moved to boards/_archived/ so you can recover it later. Tasks on this board will no longer appear anywhere in the UI.";
const opts = (variant) => ({
icon: variant === 'A' ? '' : ICONS.archive,
title: "Archive board 'atm10-server'?",
desc: msg,
confirmLabel: 'Archive',
destructive: true,
});
makeA_confirm(stage('A'), opts('A'));
makeB_confirm(stage('B'), opts('B'));
makeB2_confirm(stage('B2'), opts('B2'));
C_errorToast(stage('C'), 'Archive is destructive — undo toast not appropriate.');
},
'remove-attachment': () => {
const opts = (variant) => ({
icon: variant === 'A' ? '' : ICONS.paperclip,
title: 'Remove this attachment?',
desc: 'The file will be unlinked from this task. Other references are unaffected.',
confirmLabel: 'Remove',
destructive: true,
});
makeA_confirm(stage('A'), opts('A'));
makeB_confirm(stage('B'), opts('B'));
makeB2_confirm(stage('B2'), opts('B2'));
C_undoToast(stage('C'), 'Attachment removed', 'design-spec-v3.pdf');
},
'error': () => {
// Variant C: error toast is the only place toasts really shine.
[stage('A'), stage('B'), stage('B2')].forEach(s => {
const banner = document.createElement('div');
banner.style.cssText = 'position:absolute; top:12px; left:12px; right:12px; padding:10px 12px; background: color-mix(in srgb, var(--destructive) 10%, var(--bg)); border: 1px solid var(--destructive); color: var(--destructive); border-radius: var(--radius-sm); font-size: 12px;';
banner.textContent = 'Move failed: HTTP 409 — task is in status "todo", only running/ready/blocked can be completed.';
s.appendChild(banner);
});
C_errorToast(stage('C'), 'Move failed: HTTP 409');
},
'clear': () => {
[stage('A'), stage('B'), stage('B2'), stage('C')].forEach(s => clearStage(s));
},
};
function stage(name) { return document.querySelector(`[data-stage="${name}"]`); }
/* =========================================================== */
/* Wire up page-level triggers */
/* =========================================================== */
document.querySelectorAll('header.page .controls button').forEach(btn => {
btn.addEventListener('click', () => {
const handler = HANDLERS[btn.dataset.trigger];
if (handler) handler();
});
});
</script>
</body>
</html>
-146
View File
@@ -1,146 +0,0 @@
# Profile Builder — Dashboard-Native, Full-Featured Profile Creation
Status: design proposal (not yet implemented)
Author: drafted for Teknium
Supersedes: PR #31781 (prompt_toolkit `hermes profile wizard`)
## Why this, not the CLI wizard
PR #31781 added a keyboard-driven `hermes profile wizard` in the terminal.
The decision is to **not** build the profile-creation experience in the CLI.
The dashboard already owns mature, separate pages for every element a profile
needs, and a profile is just a HERMES_HOME directory — so the dashboard is the
right home for a full-featured builder, and it can reuse everything that
already exists.
A profile = a full `~/.hermes/profiles/<name>/` directory with its own:
- `config.yaml` — holds `model`/`provider`, `mcp_servers`, enabled skills
- `skills/` — physical SKILL.md files (built-in seed + optional + hub installs)
- `.env` — secrets
- `SOUL.md` / `USER.md` — identity
So per-profile scoping of Model, MCPs, and Skills is **native** — no data-model
change needed. The gap is purely UX: creation today is a thin modal
(name + clone + model + description), and you can only compose skills/MCPs
*after* the profile exists, by visiting other pages and remembering to scope
them.
## What already exists (reuse, don't rebuild)
| Element | Existing page | Existing API | Profile-scopable? |
|---|---|---|---|
| Name / Description | ProfilesPage create modal | `POST /api/profiles` (`create_profile`) | yes (args) |
| Model + Provider | ModelsPage | `_write_profile_model(profile_dir, …)` | yes — HERMES_HOME override, already wired into create endpoint |
| MCPs | McpPage | `mcp_config._save_mcp_server` + `/api/mcp/catalog` | yes — wrap with HERMES_HOME override |
| Skills (built-in/optional) | SkillsPage | `GET /api/skills`, `/api/skills/toggle` | yes — config write |
| Skills (hub) | SkillsPage | `/api/skills/hub/search`, `/api/skills/hub/install` | **only via subprocess** — see seam #1 |
## Two architectural seams found while grounding this design
These are load-bearing — they change the implementation, not just the polish.
### Seam #1 — hub-skill install cannot use the HERMES_HOME override
`tools/skills_hub.py` binds `SKILLS_DIR = HERMES_HOME / "skills"` at **module
import time**. The context-local `set_hermes_home_override()` swap (which makes
`_write_profile_model` and the MCP write land in the target profile) does NOT
retroactively rebind that already-imported module global. So a data-layer wrap
of hub install would write into the dashboard's *own* active profile, not the
new one.
The correct mechanism is the existing subprocess path: `_spawn_hermes_action`
runs `python -m hermes_cli.main <subcommand>`, and `_apply_profile_override()`
re-reads `sys.argv` at import in the fresh child. Prepend `-p <profile>`:
```python
_spawn_hermes_action(["-p", profile, "skills", "install", identifier], "skills-install")
```
A fresh subprocess re-imports `skills_hub` with the profile's HERMES_HOME bound
from the start, so `SKILLS_DIR` resolves to `<profile>/skills/`. Correct by
construction.
### Seam #2 — hub installs are async, so create cannot be fully atomic
Built-in/optional skill enabling and MCP writes are **synchronous config ops**
and can be part of the create call. Hub installs are long-running git fetches
spawned detached (`_spawn_hermes_action` returns a PID immediately). So the
create flow is:
1. `create_profile()` — make the dir (synchronous)
2. write model (synchronous, HERMES_HOME override)
3. write selected MCP servers (synchronous, HERMES_HOME override)
4. seed/enable selected built-in + optional skills (synchronous)
5. spawn `hermes -p <profile> skills install <id>` per hub skill (async, returns PIDs)
Steps 1–4 commit before the response; step 5 returns a list of action PIDs the
UI polls (same pattern as today's SkillsPage hub install). The builder's
"Review → Create" returns `{ok, name, path, hub_installs: [{id, pid}]}` and the
final screen shows live install progress for the hub skills.
## Proposed backend change (small, follows existing patterns)
Extend `ProfileCreate` and the create endpoint — no new endpoints, no rewrite:
```python
class ProfileCreate(BaseModel):
name: str
clone_from: Optional[str] = None
# Backward compatibility for older dashboard/desktop clients.
clone_from_default: bool = False
clone_all: bool = False
no_skills: bool = False
description: Optional[str] = None
provider: Optional[str] = None
model: Optional[str] = None
# NEW — all optional, all best-effort post-create (profile already exists)
mcp_servers: List[MCPServerCreate] = [] # synchronous, HERMES_HOME override
builtin_skills: List[str] = [] # synchronous enable/seed
hub_skills: List[str] = [] # async spawn, returns PIDs
```
The endpoint already does best-effort post-create steps (`seed_profile_skills`,
`_write_profile_model`). Add two more best-effort blocks (MCP write, hub-skill
spawn) in the same style — a failure in any of them must not 500 the create,
since the profile dir already exists and the user can fix it from the relevant
page afterward. Mirror `_write_profile_model`'s HERMES_HOME-override helper for
the MCP write (`_write_profile_mcp_servers(profile_dir, servers)`).
## Proposed frontend — dedicated builder page `/profiles/new`
A full page (not the cramped modal), stepped, each step reusing the existing
page's component + API, targeted at the new profile:
```
① Identity Name + Description (+ optional clone-from existing profile)
② Model Provider + model picker (reuse ModelsPage picker)
③ Skills Tabs: Built-in · Optional · Hub-search
multi-select; "Start from default bundle" preset button
④ MCPs Tabs: Catalog browse · Manual add (reuse McpPage form)
⑤ Review Blueprint preview → Create
→ progress screen for async hub installs
```
Nothing writes to disk until ⑤.
## Open product decisions (need Teknium)
1. **Skills seeding default.** Fresh profiles auto-seed the default bundle
today. In the builder, should the skill step **replace** the bundle (pick
exactly what you want; offer a "start from default bundle" preset) or
**augment** it? Recommendation: replace + preset button.
2. **Page vs richer modal.** Dedicated `/profiles/new` page (room to grow:
SOUL editing, multi-agent fleets later) vs a bigger create modal on
ProfilesPage. Recommendation: dedicated page — matches "full-featured / way
more options."
## Verification plan (when built)
- Backend E2E with isolated HERMES_HOME: POST a full create body
(name + model + 2 MCPs + 3 builtin skills + 1 hub skill), assert the new
profile dir has the model in config.yaml, both MCP servers in config.yaml,
the builtin skills enabled, and a spawned PID for the hub skill. Negative:
a bad MCP entry must not 500 the create.
- `cd web && npm run build` (no JS test suite in web/).
- Targeted: `pytest tests/<web_server profile tests> -k profile_create`.
Binary file not shown.
-117
View File
@@ -1,117 +0,0 @@
# Profile-Based Routing for Inbound Messages
> **Audience:** Gateway operators and contributors
> **Source files:** `gateway/profile_routing.py`, `gateway/run.py` (`_profile_name_for_source`), `gateway/platforms/base.py` (`build_source`), `gateway/config.py`
> **Related:** [Session Lifecycle](session-lifecycle.md), `docs/design/profile-builder.md`
## Overview
By default a single gateway run uses one profile (memory, persona, tools). **Profile-based
routing** lets one gateway instance serve **multiple isolated profiles**, selecting which
profile handles an inbound message based on *where the message came from* — the platform,
server (`guild_id`), channel (`chat_id`), and/or thread (`thread_id`).
This is the inbound counterpart to multiplexing: instead of running N gateways, run one
gateway and route per-community / per-channel / per-thread to a dedicated profile. Each
profile keeps fully isolated state (`MEMORY.md`, `USER.md`, `SOUL.md`, sessions, tools).
Routing is **platform-generic**: it works for Discord, Telegram, Feishu, Slack, and every
adapter — not just Discord.
## Configuring routes
Routes live under `profile_routes` in `config.yaml`. Both the top-level and the nested
`gateway.profile_routes` forms are accepted (the nested form is what
`hermes config set gateway.profile_routes ...` writes).
```yaml
profile_routes:
# Route an entire Discord server (guild) to one profile.
- name: server-default
platform: discord
guild_id: "1234567890"
profile: server-profile
# Override a specific channel within that server with a different profile.
- name: support-channel
platform: discord
guild_id: "1234567890"
chat_id: "9876543210"
profile: support-profile
# Pin a Telegram group to a profile (Telegram has no guild_id — chat_id only).
- name: tg-group
platform: telegram
chat_id: "-1001234567890"
profile: tg-profile
# Route a single Discord thread.
- name: standup-thread
platform: discord
guild_id: "1234567890"
chat_id: "9876543210"
thread_id: "1111111111"
profile: standup
```
### Fields
| Field | Required | Description |
|---|---|---|
| `name` | yes | Human-readable route identifier (used in logs). |
| `platform` | yes | Adapter platform: `discord`, `telegram`, `feishu`, `slack`, … |
| `profile` | yes | Target profile name (must exist under `~/.hermes/profiles/<name>`). |
| `guild_id` | no | Server/guild (Discord). |
| `chat_id` | no | Channel/group/DM id. |
| `thread_id` | no | Thread id within a channel. |
| `enabled` | no | Default `true`; set `false` to disable a route without removing it. |
## Matching rules
A route matches an inbound source when **every discriminator the route declares is satisfied**
(conjunctive / AND). A field the route leaves unset is ignored.
- **`platform`** must equal the source platform exactly.
- **`thread_id`** (if set) must equal the source thread id.
- **`chat_id`** (if set) must match the source channel **or** its parent — a thread in a
channel matches the channel's route (hierarchical match for Discord forums/threads).
- **`guild_id`** (if set) must equal the source guild.
> A route declaring **both** `guild_id` and `chat_id` requires both to hold. A channel match
> alone does not satisfy a guild constraint — this is intentional and tested.
When multiple routes match, the **most specific** one wins. Specificity is additive:
| Discriminator | Weight |
|---|---|
| `thread_id` | 8 |
| `chat_id` | 4 |
| `guild_id` | 2 |
| (platform only) | 0 |
So a thread route (8) beats a channel route (4) beats a guild route (2) within the same server.
If no route matches, the message uses the default/active profile.
## How it works at runtime
1. An inbound message arrives at a platform adapter.
2. `BasePlatformAdapter.build_source` builds the `SessionSource` for the message. Every
adapter carries a back-reference to the running `GatewayRunner`
(`gateway_runner`, injected in `gateway/run.py`), so it asks the runner to resolve the
target profile via `_profile_name_for_source`.
3. `_profile_name_for_source` runs the configured routes through `match_profile_route` and
stamps `source.profile` with the winning route's profile (or leaves it unset).
4. Downstream, `_resolve_profile_home_for_source` chooses the profile home directory
(`source.profile` → active profile → `default`) and the session is scoped per-profile, so
each routed community gets isolated memory and conversation state.
Because `gateway_runner` is injected for **all** adapters (declared on `BasePlatformAdapter`),
every platform goes through this path — not just Discord.
## Relationship to multiplexing
`profile_routes` requires `gateway.multiplex_profiles: true`. Multiplexing is what
activates the per-profile runtime scope (per-profile `HERMES_HOME`, secret scope, and
profile-namespaced session keys); routing is the decision layer that picks *which*
profile a given guild/channel/thread lands in. With multiplexing off, `profile_routes`
is ignored entirely — behavior is byte-identical to a single-profile gateway.
-54
View File
@@ -1,54 +0,0 @@
# RCA: SSL CA cert bundle corruption after `hermes update`
**Status:** resolved by `fix(ssl): surface broken CA bundles before provider calls`
**Severity:** P2 — degrades the agent into opaque provider/client failures until the user repairs deps or CA configuration.
## Summary
A partial `hermes update`, interrupted venv repair, or stale CA-bundle environment variable can leave Python TLS configuration pointing at a missing, empty, or unloadable CA bundle. The first outbound HTTPS client creation or request can then fail with a raw `FileNotFoundError: [Errno 2] No such file or directory` or a low-level SSL error that does not name the broken CA path.
## Root cause
Hermes uses OpenAI/httpx and requests-based clients for provider calls, model metadata, gateway delivery, and web tools. Those clients inherit CA bundle settings from:
- `HERMES_CA_BUNDLE`
- `SSL_CERT_FILE`
- `REQUESTS_CA_BUNDLE`
- `CURL_CA_BUNDLE`
- the bundled `certifi` package's `cacert.pem`
When the venv is partially refreshed, or when one of those env vars points at a file that no longer exists, provider client construction can fail before Hermes has enough context to produce a useful message.
## Fix
`agent/ssl_guard.py` validates CA bundle configuration before the OpenAI-compatible provider client is created in `agent/agent_init.py`. It:
1. Checks explicit CA bundle env vars and reports the exact broken variable/path,
2. Verifies `certifi` is importable,
3. Verifies `certifi.where()` points at an existing file of plausible size,
4. Builds an `ssl.SSLContext` from each checked bundle,
5. Raises a typed `SSLConfigurationError` with a repair hint before httpx/OpenAI can raise a raw low-level error.
`hermes_cli doctor` exposes the same check under `SSL / CA Certificates`, so users can diagnose the problem without starting a model session.
## Recovery
When the guard fires during agent init, the user sees a message like:
```text
Failed to initialize OpenAI client: SSL_CERT_FILE points to a missing CA bundle: C:\path\to\missing\cacert.pem
Repair: python -m pip install --force-reinstall certifi openai httpx
If you configured a custom corporate CA bundle, fix or unset the broken CA bundle environment variable.
```
For a normal corrupted Hermes venv, reinstall the affected client dependencies:
```bash
python -m pip install --force-reinstall certifi openai httpx
```
For a custom/corporate CA setup, fix the env var so it points at a real PEM bundle, or unset it if Hermes should use the bundled `certifi` store.
## Environment escape hatch
Set `HERMES_SKIP_SSL_GUARD=1` to bypass the preflight check. This is intended only for sandboxed or managed-trust environments where the Python CA path looks unusual but downstream clients are known to work.
@@ -1,134 +0,0 @@
# Research spike: plugin-architecture lessons from Pi and OpenCode
**Issue:** #64180 · **Informs:** #64164 (event bus), #64161 (streaming hooks), #64162 (pluggable approval), #64165 (manifest v2), #64229 (lifecycle/ledger), #64230 (Plugin Doctor)
**Method.** Both systems were read at source level (shallow clones pinned to a commit), not from docs sites alone: Pi (`badlogic/pi-mono`, now `earendil-works/pi`) at `eb79351` (v0.80.7, 2026-07-14) and OpenCode (`sst/opencode`, now `anomalyco/opencode`) at `c69abee` (v1.18.2, 2026-07-16). Claims below carry file:line references into those commits. Where something could not be found (ADRs, policies, timeouts), that absence was verified by search and is reported as a finding. Hermes ground rules from #64182 (additive-only, prompt-cache sacred, observer-first, fail-closed security) are treated as overriding constraints throughout — this report grades imported patterns against them, per the adapt-don't-copy rubric.
**Headline.** The two systems are near-perfect opposites on the four design axes Hermes currently has open, which makes them a natural controlled experiment:
| Axis | Pi | OpenCode | Hermes proposal on the table |
|---|---|---|---|
| Per-delta streaming hook | Yes — awaited inline, no timeout | Structurally absent (text-end only) | Observer per-delta + never-block contract (#64161) |
| Veto semantics | Typed per-event result vocabulary (`{block}`, `{cancel}`, `"handled"`) | Veto-by-throw (bug and policy denial indistinguishable) | TBD in #64162 |
| Guard-hook failure | Fail closed (`tool_call` only) | No runtime containment at all | Ground rule 4: fail closed on security-adjacent |
| Plugin event bus | Yes — 33 lines, **un-namespaced** channels | None (plugins observe core bus, cannot emit) | Namespaced `ctx.emit`/`ctx.subscribe` (#64164) |
Neither system has hook timeouts. Both have shipped hang-class or drift-class failures because of it. That is the single strongest cross-cutting lesson for Hermes.
---
## 1. Pi (badlogic/pi-mono → earendil-works/pi)
Extensions are in-process TypeScript modules (loaded via jiti) receiving an `ExtensionAPI`; no separate process, no IPC, no manifest permissions. Pi explicitly rejected MCP as its extension mechanism (Zechner, ["What if you don't need MCP at all?"](https://mariozechner.at/posts/2025-11-02-what-if-you-dont-need-mcp/)). Notably, Pi's founding "minimal, no hooks" stance (Nov 2025) reversed into a 33-event extension system within ~7 months — extensibility demand won; the no-MCP stance held.
### 1.1 Hook/event taxonomy
33 event types (`src/core/extensions/types.ts:507-902`). The load-bearing design choice: **every mutating event gets its own typed emitter with its own result vocabulary**, rather than one generic middleware pipe —
- `tool_call` → `{ block: true, reason }`; argument mutation in place, explicitly "no re-validation after your mutation" (`docs/extensions.md:742-765`)
- `session_before_*` → `{ cancel: true }`, first canceller wins, later handlers skipped
- `input` → `"handled"` (short-circuit) vs `"transform"` (chain) (`runner.ts:1148-1188`)
- `tool_result` → partial-patch accumulation across handlers (`runner.ts:835-883`)
- `before_agent_start` → system-prompt chaining with a live `ctx.getSystemPrompt()` reflecting earlier handlers (`runner.ts:1034-1098`)
- Observer events have **no return channel at all** — the observer/mutator split is enforced by which emitter the event flows through, not by convention.
Dispatch is fully sequential async (`runner.ts:759-791`): every handler awaited one at a time; the only ordering rule is extension load order (project → global → CLI, `loader.ts:660-708`) then registration order. No priorities, no phases — and no community demand for them in ~8 months. Name collisions are handled per registry with explicit deterministic policies instead of dependency resolution: first-wins tools, suffixed duplicate commands (`name:2`), last-wins shortcuts with a warning plus an 18-key reserved denylist (`runner.ts:421-604`).
Two ordering guarantees worth copying: extensions see events **before** the UI and **before** session persistence (`agent-session.ts:596-601`), and parallel sibling tool calls are "preflighted sequentially, then executed concurrently" (`docs/extensions.md:750`).
### 1.2 Plugin-to-plugin interaction
A 33-line shared event bus (`src/core/event-bus.ts`): `pi.events.emit/on` on **arbitrary string channels** — no namespacing, no declarations, no collision protection; per-handler try/catch and an unsubscribe closure. Everything richer (capability registries, dependencies) is deliberately absent; a community RFC to build richer coordination as an extension (pi#2715) was left to userland.
### 1.3 Compatibility strategy
No API versioning, no handshake, no deprecation annotations. In its place, three working practices: (a) loader-level alias shims that kept old imports resolving across the `@mariozechner`→`@earendil-works` package rename and a pi-ai API split, with pre-announced removal (`loader.ts:47-71`; `CHANGELOG.md:243`); (b) loud "Breaking Changes" changelog sections with **automatic migrations** (directory renames on startup, session format v2→v3 auto-migrated) for the big hooks+customTools→extensions unification (v0.35-0.37); (c) per-tool `prepareArguments()` shims for old argument shapes.
Real breakage on record: pi#2860 — an internal session-management refactor made `pi.sendUserMessage()` after `ctx.newSession()` silently drop messages. The remediation pattern is distinctive: **stale-context poisoning** — after session replacement, every captured context getter throws a paragraph-long teaching error pointing at the safe `withSession` pattern (`runner.ts:514-527`; `docs/extensions.md:1223-1265` documents the footgun with unsafe-pattern code). Compat by making misuse loud, not by never changing.
### 1.4 Failure isolation
Contain errors, don't contain time: every handler call is individually try/caught and surfaced (red stack trace in chat UI), load failures skip only the broken extension, and a `pi -ne` no-extensions escape hatch exists. The **one deliberate exception**: `tool_call` has no internal catch — a guard-hook crash blocks the tool ("Extension failed, blocking execution"), converted into an error tool result the LLM sees; the loop survives, the guard fails closed (`runner.ts:885-906`; `agent-session.ts:454-467`; `agent-loop.ts:657-665`).
**There are zero timeouts.** All handlers — including per-token `message_update` — are awaited inline in the agent event pipeline (`agent-session.ts:598, 728-734`). A hung extension freezes the agent; the changelog records hang-class fixes (pi#5687 background handles, pi#5115 shutdown drains). Mitigations offered are cooperative only (`ctx.signal` AbortSignal, Esc-abort).
No sandbox, documented as a decision: "a partial in-process sandbox would be easy to misunderstand as a security boundary" (`docs/security.md:33-35`); the only gate is project-trust on load.
### 1.5 Design-history record
**Pi has no ADRs** — the Discord recollection that prompted this spike is not substantiated for Pi. Rationale lives in four places: "footgun" sections inside user docs (effectively inline ADRs), a 5,000-line issue-linked changelog (which records abandoned designs: the hooks/customTools split, slash-commands→prompt-templates rename, a fetch-override proxy abandoned for undici dispatchers), Zechner's blog, and issues themselves.
### 1.6 Prompt/context construction
Pi is the only surveyed system that treats **prompt-cache stability as part of the extension API contract**: extensions receive structured prompt inputs (`systemPromptOptions` — the same decomposed inputs Pi itself uses) rather than a final string; per-request context transforms operate on a `structuredClone` so session history is never corrupted; and cache-friendly dynamic tool loading (v0.80.6, pi#6474) activates tools additively via native provider deferred loading (Anthropic `defer_loading`) explicitly to avoid invalidating the prefix cache — with documented warnings about second-order invalidation through prompt-metadata changes (`docs/extensions.md:2254-2290`).
---
## 2. OpenCode (sst/opencode → anomalyco/opencode)
Server (Bun/Effect) + clients (TUI/desktop/web); plugins are npm packages or local TS files loaded in-process, with **two plugin kinds in one package** — `server` and `tui` entrypoints, hard rule one-or-the-other (`shared.ts:103-114, 293-295`). A v2 plugin API ships side-by-side with v1 (`/v2/effect`, `/v2/promise` subpaths), designed in a candid 516-line `PLAN.md`.
### 2.1 Hook/event taxonomy
One `Hooks` bag returned by an async factory (`packages/plugin/src/index.ts:74, 222-335`): ~16 mutating `(input, output)` hooks (mutate `output` in place; host reads it back) plus declarative registries (tools, auth, providers) and a single firehose `event` observer. The whole dispatch engine is ~13 lines (`plugin/index.ts:280-293`): sequential, awaited, load-order, later hooks see earlier mutations — ordering documented as a spec ("global config → project config → global plugin dir → project plugin dir"; v2: "plugin registration order, then transform registration order").
**Veto is throw.** The documented idiom for denying a tool call is `throw new Error("Do not read .env files")` (`plugins.mdx:247-257`) — policy denial and plugin bug are indistinguishable in every consumer downstream.
**A typed-but-dead hook.** `permission.ask` — the only hook with real decision semantics (`output.status: "ask" | "deny" | "allow"`) — exists in the published types but has **no dispatch site anywhere in the tree**: a permission-subsystem rewrite orphaned it, types kept compiling, plugins silently no-op'd (oc#7006, open since Jan 2026). This is the sharpest single failure mode found in the whole spike.
### 2.2 Plugin-to-plugin interaction
No dependencies, no registry, no plugin-emitted events. Interaction is (a) blind composition through the shared mutable `output` (last-writer-wins per field) and (b) observing the core event bus. The 2026 core bus itself is heavyweight — event-sourced, durable (SQLite, per-aggregate sequences, idempotent replay), versioned wire types, and a **backpressure guard**: `allBounded` wraps a dropping queue and fails slow subscribers with `SubscriberOverflowError` (`packages/core/src/event.ts:152-164`). Plugins get the untyped tail of a three-tier bridge (Effect streams → global emitter → `event` hook), fired **fire-and-forget** — an async observer's rejection is an unhandled promise rejection invisible to host error routing (`plugin/index.ts:251-258`).
### 2.3 Compatibility strategy
Lockstep versioning (`opencode` = `@opencode-ai/plugin` = `@opencode-ai/sdk` = 1.18.2) plus one gate: npm plugins may declare `engines.opencode` semver ranges, checked at load (`shared.ts:194-205`) — but it is plugin-opt-in, and local file plugins skip it entirely. Three generations of module shape are loaded simultaneously; superseded packages are silently ignored via a hardcoded `DEPRECATED_PLUGIN_PACKAGES` list.
The community-experience record is instructive: v1.14.42 — a **patch release** — removed the whole `api.command.*` TUI namespace with no deprecation cycle (oc#26557); the aftermath is visible in-tree as a deprecated shim added back *after* the outcry ("Legacy `api.command` API kept so v1 plugins can initialize. Remove in v2", `tui.ts:87-120`). No written deprecation policy exists anywhere. Shims-after-outcry is the de facto process.
### 2.4 Failure isolation
Strong at the edges, absent in the middle. Load is staged (`install | entry | compatibility | missing | load`) with per-plugin, per-stage containment and user-visible toasts (`loader.ts:82-93`; `plugin/index.ts:215-249`). Runtime hooks have **no catch and no timeout**: a throw in a tool hook fails that tool call (the sanctioned veto), a throw in chat/transform hooks aborts the turn (session errors, server survives), a **hang hangs the turn forever** — the v2 PLAN explicitly lists "Transform timeouts" under *Deferred Decisions* (`PLAN.md:507-510`). Boot re-entrancy burned them: a plugin calling the SDK client during its own init deadlocked startup (oc#7741). The official troubleshooting page's first advice is "start by disabling plugins."
Two mature exceptions worth stealing: the streaming hot path is protected **structurally** — there is no per-delta hook at all; text hooks fire once at `text-end` (`processor.ts:512-524`) — and the TUI runtime has scope-tracked registrations (a `Proxy`-wrapped keymap API auto-records every registration per plugin, enabling clean live deactivate) plus a **hard 5s dispose budget** racing each cleanup against a timer (`runtime.ts:122-226, 388-468`).
### 2.5 Design-history record
No ADR system; the `PLAN.md` for v2 is the exception and is better than most ADR archives — it names v1's mistakes (the returned-hooks bag, finalizer-triggered special cases), specifies ordering as a contract, splits replayable *transforms* from live *hooks*, and — crucially — carries an honest **Deferred Decisions** section (typed error model, transform timeouts) rather than pretending closure.
### 2.6 Prompt/context construction
Plugins can touch every layer, but the deep layers are gated behind an `experimental.` prefix (`experimental.chat.system.transform`, `experimental.chat.messages.transform`, compaction prompt replacement) — a deliberate two-tier stability promise: interception at operation boundaries is stable, rewriting the context itself is not. No cache-stability discipline comparable to Pi's was found.
---
## 3. Adopt / Adapt / Avoid for Hermes
Grading against #64182's ground rules. "Validated" = the proposal already on the Hermes issue is independently confirmed by field evidence.
| # | Lesson | Verdict | Maps to | Evidence |
|---|---|---|---|---|
| 1 | **Typed per-hook result vocabularies, not veto-by-throw.** Pi's `{block, reason}` / `{cancel}` / `"handled"` enums vs OpenCode's throw-idiom (bug ≡ policy denial) and its dead `permission.ask`. Approval/gate hooks need enumerated results dispatched from the policy engine itself. | **Adopt** | #64162 | Pi runner.ts:759-1188; oc plugins.mdx:247-257, oc#7006 |
| 2 | **Guard hooks fail closed; observers fail open.** Pi contains every handler error except `tool_call`, whose crash blocks the tool with an LLM-visible error result. Independently confirms ground rule 4 — and refines it: the failure mode of a *crashed* security hook must also be closed, not just its config default. | **Adopt** (validated) | #64162, #64204 | Pi agent-session.ts:454-467, agent-loop.ts:657-665 |
| 3 | **Hook wire-up drift is the killer bug class: CI-check that every declared hook has a live dispatch site.** OpenCode's `permission.ask` sat typed-but-dead for 6+ months after a subsystem rewrite. Hermes already stores unknown hook names for forward compat (`register_hook`, plugins.py ~L1158) — the same drift is possible. A `VALID_HOOKS` ↔ `invoke_hook(` cross-check is a one-file test. | **Adopt now** (cheap, standalone) | #64230 (Doctor), CI | oc index.ts:261 + absent trigger site, oc#7006 |
| 4 | **Deadline budgets on plugin callbacks — be the first framework to have them.** Neither system times out runtime hooks; both shipped hang-class failures (pi#5687/#5115; oc#7741, "Transform timeouts" deferred twice). OpenCode's own TUI dispose path (hard 5s, per-cleanup timer race) proves the mechanism is practical. Observer hooks: enforce a budget and log-and-drop. Mutating/guard hooks: budget + fail per lesson 2. | **Adopt** (differentiator) | #64161, #64164, #64229 | Pi grep: zero timeout logic; oc PLAN.md:507-510, runtime.ts:122-226 |
| 5 | **Per-delta streaming hooks are viable only if non-blocking is structural, not documentary.** The controlled experiment: Pi offers per-delta and awaits inline → slow observer throttles the visible stream, hangs freeze it; OpenCode offers nothing per-delta → hot path safe, TTS use case unserved. #64161's "never-block contract + buffered-queue helper" is the right middle — but make the bounded queue the *only* consumption path (drop/coalesce policy included, cf. OpenCode's `SubscriberOverflowError` dropping queue), not an optional convenience next to a raw sync callback. | **Adapt** | #64161 | Pi agent-session.ts:728-734; oc processor.ts:512-524, event.ts:152-164 |
| 6 | **The namespaced bus proposal is ahead of both systems — proceed, with their two omissions fixed.** Pi's bus works but has arbitrary un-namespaced string channels and no discoverability; OpenCode has no plugin-emit at all. #64164's `<plugin_key>:` enforcement, reserved `hermes:` prefix, advisory declarations, recursion cap, and deterministic subscription order have no counterexample in the field. Carry over per-callback isolation (both systems do this right) and add lesson-4 budgets. Fire-and-forget with return-values-ignored matches both systems' stable practice. | **Adopt own design** (validated) | #64164 | Pi event-bus.ts (whole file); oc plugin/index.ts:251-258 |
| 7 | **Load order as the only priority system; explicit per-registry collision policies.** Zero configuration, deterministic, and no field demand for priorities in either ecosystem. Document Hermes's ordering as a spec the way OpenCode's PLAN does; pick a collision rule per registry (Pi: first-wins tools / suffixed commands / reserved denylist) instead of building dependency resolution. | **Adopt** | #64164, #64229 | Pi loader.ts:660-708, runner.ts:421-604; oc PLAN.md:144-146 |
| 8 | **Host-enforced compat gate + written deprecation window; migration tooling over semver ceremony.** OpenCode's `engines` gate is the right shape but plugin-opt-in only, and its patch-release API removal (oc#26557) shows lockstep versioning without policy is social, not mechanical. Pi shows the complement: loud breaking changes + automatic migrations + alias shims *before* removal. Manifest v2 should carry a host-checked `api_version` range; the repo should carry a one-paragraph deprecation policy. | **Adapt** | #64165, #64179 | oc shared.ts:194-205, tui.ts:87-120, oc#26557; Pi CHANGELOG:243, 3530-3620 |
| 9 | **Scoped registrations with auto-tracked disposal; poison stale contexts with teaching errors.** OpenCode's Proxy-tracked per-plugin scopes (clean live disable) and Pi's post-replacement context poisoning (silent race pi#2860 → loud self-documenting error) are the two halves of a robust lifecycle story — exactly what the #64229 ownership ledger needs. | **Adopt** | #64229 | oc runtime.ts:143-160; Pi runner.ts:514-527, docs:1223-1265 |
| 10 | **Prompt-cache stability as API contract is real and Pi proves it's implementable.** Structured prompt inputs instead of final strings, `structuredClone` for ephemeral transforms, additive-only tool activation with provider deferred loading, documented second-order invalidation warnings. Strongest possible validation of ground rule 2, with a concrete reference implementation for cache-safe injection. | **Adopt** (validated) | #64167 | Pi docs:2254-2290, CHANGELOG 0.80.6/pi#6474 |
| 11 | **Half-sandboxes: both systems refuse, for the same stated reason.** Pi documents that a partial in-process sandbox "would be easy to misunderstand as a security boundary"; OpenCode runs plugins fully privileged with path-containment only. Viable while plugin authors ≈ users; Hermes's Skills-Hub-style trust/scan pipeline is the nearer-term marketplace answer than in-process isolation. | **Adapt with eyes open** | security posture | Pi docs/security.md:5-37; oc shared.ts:89-97 |
| 12 | **Events to plugins before UI and before persistence; boot-stage the plugin-facing client.** Pi's explicit ordering guarantee removes a whole class of races; OpenCode's plugins-as-API-clients design is elegant but deadlocked startup when a plugin called the API mid-init (oc#7741) — if ctx ever grows client-like powers, stage them ("unavailable until ready"). | **Adapt** | #64178, #64229 | Pi agent-session.ts:596-601; oc plugin/index.ts:142-147, oc#7741 |
| 13 | **Neither system has ADRs — and both paid for it.** Pi's rationale is scattered across changelog/blog/footguns; OpenCode broke APIs in patch releases partly because no decision record said not to. Hermes's per-sub-issue design sketches (#64182 style) are already ahead of both; add an explicit **Deferred Decisions** section per design (OpenCode's PLAN.md's best feature) so open questions stay visible instead of silently unresolved. | **Keep + adapt** | process | verified ADR absence in both repos |
## 4. Verified absences (findings, not gaps in the spike)
- **No ADRs in either repo** (repo-wide searches for `adr`/`decision` artifacts). The Discord recollection of "ADRs describing failure modes" is unsubstantiated for both; the nearest equivalents are Pi's docs footgun sections and OpenCode's single v2 PLAN.md.
- **No runtime hook timeouts in either system** (grep-verified in Pi's `src/core/extensions/`; OpenCode's own plan defers them).
- **No written deprecation or plugin-API stability policy in either repo.**
- Caveats: Pi's #2860→remediation causality is inferred from matching failure/fix, not a maintainer statement; OpenCode pre-rewrite history was not diffed (shallow clones); maintainer replies inside cited issues were not visible in fetched content.
---
*Spike time-boxed per #64180. Primary sources: `earendil-works/pi` @ `eb79351` — `packages/coding-agent/src/core/extensions/{runner,loader,types}.ts`, `src/core/{agent-session,event-bus}.ts`, `packages/agent/src/agent-loop.ts`, `docs/{extensions,security}.md`, `CHANGELOG.md`; `anomalyco/opencode` @ `c69abee` — `packages/plugin/src/{index,tui}.ts`, `packages/plugin/src/v2/effect/PLAN.md`, `packages/opencode/src/plugin/{index,shared,loader}.ts`, `packages/opencode/src/plugin/tui/runtime.ts`, `packages/core/src/event.ts`, `packages/web/src/content/docs/plugins.mdx`; issues pi#2860/#2715/#5080/#5687, oc#7006/#26557/#7741/#4850/#12222; mariozechner.at posts (2025-11-02, 2025-11-30).*
-144
View File
@@ -1,144 +0,0 @@
# Plugin Config & State Bridge
**Status:** config + state slice implemented by #64227
**Original design:** Topher Ross (@thebizfixer), RFC PR #58542
**Concrete consumer:** kanban-advanced
## Scope
This slice adds two native `PluginContext` capabilities:
- typed, namespace-jailed settings via `ctx.get_config()` and `ctx.set_config()`;
- atomic, profile-scoped runtime data via `ctx.state`.
Config schema registration, config defaults, and the cron facade from the
original RFC remain separate follow-up work. No core model tool is added.
## Config API
```python
def register(ctx):
endpoint = ctx.get_config("api_url", default="https://example.invalid")
retries = ctx.get_config("retry.attempts", default=3)
ctx.set_config("api_url", "https://api.example.com")
ctx.set_config("retry.attempts", 5)
```
Keys are **relative to the calling plugin**. The example above reads and writes:
```yaml
plugins:
entries:
<effective-plugin-id>:
settings:
api_url: https://api.example.com
retry:
attempts: 5
```
`<effective-plugin-id>` is `manifest.key` when present, otherwise
`manifest.name`. `settings` is the canonical namespace chosen after the issue
discussion in #64227/#67531. For migration safety, reads fall back to the former
`plugins.entries.<id>.config.*` subtree only when the canonical value is absent.
Writes always target `settings`; they do not rewrite or delete legacy values.
### Namespace jail
The API does not accept full config paths. A plugin can never use it to inspect
or change arbitrary Hermes configuration.
Accepted:
```python
ctx.get_config("endpoint")
ctx.set_config("retry.policy", {"attempts": 3})
```
Rejected with `ValueError` and a warning log:
```python
ctx.get_config("security.approval_mode")
ctx.set_config("model.provider", "attacker-proxy")
ctx.set_config("plugins.entries.other.settings.token", "...")
ctx.set_config("../../security.approval_mode", "always_allow")
ctx.set_config(r"..\..\model.provider", "attacker-proxy")
```
There is no global read allowlist: `ctx.profile_name` already exposes the only
small host fact requested by the RFC. Settings writes use Hermes'
profile-aware config loader/saver and atomic YAML replacement. The bridge
validates the existing YAML before writing so malformed config is never
silently replaced. Every operation resolves the active context-local
`HERMES_HOME`, so one globally loaded plugin context follows multiplexed
profile turns without crossing profile data.
## Durable state API
Use state for plugin-owned runtime data such as cursors, dedupe sets, and
caches. Do not put those values in user-owned config.
```python
def register(ctx):
cursor = ctx.state.get("cursor", default={"page": 0})
ctx.state.set("cursor", {"page": cursor["page"] + 1})
```
The facade stores one JSON object at:
```text
<HERMES_HOME>/plugin-data/<plugin-data-namespace>/state.json
```
Portable Agent Plugins use their existing `PLUGIN_DATA` namespace exactly.
Native and nested plugin ids use the same collision-resistant, Windows-safe
namespace algorithm. `ctx.state.data_dir` exposes the directory and
`ctx.state.path` exposes the JSON file when a plugin needs to inspect its own
location.
### State guarantees
- **Profile isolation:** the data root resolves from the active context-local
Hermes home on every operation.
- **Atomic replacement:** state writes use temp-file + `fsync` + `os.replace`.
- **Concurrent updates:** a sibling lock file serializes read-modify-write across
threads and processes (`fcntl` on POSIX, `msvcrt` on Windows).
- **Quota:** the complete serialized state is limited to 10 MiB per plugin. A
rejected update leaves the previous file untouched.
- **Fail closed:** malformed/non-object JSON is reported and never overwritten.
- **Typed values:** values must be JSON-serializable.
State keys are 1–128 characters and may contain letters, numbers, `_`, `-`,
`.`, or `:`. Path separators and `..` are rejected.
## State vs. config
| Data | API | Ownership | Example |
|---|---|---|---|
| User-visible behavior | `ctx.get_config` / `ctx.set_config` | User/plugin settings in `config.yaml` | endpoint, timeout, feature mode |
| Runtime bookkeeping | `ctx.state.get` / `ctx.state.set` | Plugin data under `plugin-data/` | cursor, cache, dedupe ids |
Both APIs are additive. Existing plugins that perform their own file I/O keep
working, but new plugins should use this bridge for stable profile and Windows
semantics.
## Verification contract
The implementation is covered with real temporary-Hermes-home tests for:
- fixture-plugin discovery and config/state round trips;
- canonical `settings` writes and legacy `config` read fallback;
- direct global, cross-plugin, POSIX traversal, and Windows traversal rejection;
- concurrent settings writes without lost siblings;
- cross-thread and cross-process state updates;
- atomic quota rejection and malformed-state/config preservation;
- two-profile isolation after the ambient profile changes;
- Unicode and Windows-style path values.
## Related
- [Issue #64227](https://github.com/NousResearch/hermes-agent/issues/64227)
- [RFC PR #58542](https://github.com/NousResearch/hermes-agent/pull/58542) by Topher Ross
- #67531 — standalone plugin settings namespace discussion