Skip to content

The agent that grows with you

test: keep cross-cutting architecture lints; drop stale OS-fake baseline entries

teknium14b17b284cec5
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index aada8bc92e6..bca7769eb65 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1862,8 +1862,7 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
return client
# TCP keepalives so dead provider connections are detected (~60s) instead of hanging in
# CLOSE-WAIT. Injected into the local copy only, so each client gets its own httpx.Client;
- # pinned by tests/agent/test_create_openai_client_reuse.py and
- # test_sequential_chats_live.py. What IS shared across those per-client wrappers is the
+ # pinned by tests/agent/test_create_openai_client_reuse.py. What IS shared across those per-client wrappers is the
# connection pool: ``build_keepalive_http_client`` mounts a process-shared ``HTTPTransport``
# behind a per-client view whose ``close()`` is a no-op for the pool, so a closed wrapper
# never takes a sibling's (or the successor's) connections with it
diff --git a/apps/desktop/src/components/ui/__tests__/no-native-title.test.ts b/apps/desktop/src/components/ui/__tests__/no-native-title.test.ts
new file mode 100644
index 00000000000..44bd0bbeceb
--- /dev/null
+++ b/apps/desktop/src/components/ui/__tests__/no-native-title.test.ts
@@ -0,0 +1,177 @@
+import { readdirSync, readFileSync, statSync } from 'node:fs'
+import { join, resolve } from 'node:path'
+
+import { describe, expect, it } from 'vitest'
+
+// Static-analysis guard: no <button> or <Button> element in the desktop renderer
+// may use the native HTML `title=` attribute. Native tooltips are unstyled,
+// delayed (~500ms OS default), and visually inconsistent with the themed `Tip`.
+// When a tip is warranted (see DESIGN.md — not every icon, never menu triggers),
+// use `<Tip label={...}>` instead of `title=`; otherwise keep an `aria-label`.
+//
+// This is a source-text scan, not a behavior test — it's the same category as
+// an ESLint rule, expressed as a vitest so it runs with the rest of the suite.
+
+// Recursively walk a directory and collect all shipped .tsx file paths.
+function collectTsxFiles(dir: string): string[] {
+ const results: string[] = []
+
+ for (const entry of readdirSync(dir)) {
+ // Skip node_modules, dist, and __tests__ (this file itself)
+ if (entry === 'node_modules' || entry === 'dist' || entry === '__tests__') {
+ continue
+ }
+
+ const fullPath = join(dir, entry)
+ const stat = statSync(fullPath)
+
+ if (stat.isDirectory()) {
+ results.push(...collectTsxFiles(fullPath))
+ } else if (entry.endsWith('.tsx') && !entry.endsWith('.test.tsx')) {
+ // Test fixtures (`<button title={title}>` stand-ins for SDK components)
+ // are not shipped UI.
+ results.push(fullPath)
+ }
+ }
+
+ return results
+}
+
+/** Every `<button …>` / `<Button …>` opening tag in `content`, with the
+ * attribute text up to the tag's real closing `>`. */
+function eachButtonOpenTag(content: string): Array<{ attrs: string; index: number; tagName: string }> {
+ const tags: Array<{ attrs: string; index: number; tagName: string }> = []
+ const openPattern = /<(Button|button)\b/gu
+ let match: RegExpExecArray | null
+
+ while ((match = openPattern.exec(content)) !== null) {
+ const attrsStart = match.index + match[0].length
+ const end = findTagClose(content, attrsStart)
+
+ if (end < 0) {
+ continue
+ }
+
+ tags.push({ attrs: content.slice(attrsStart, end), index: match.index, tagName: match[1] })
+ }
+
+ return tags
+}
+
+// The opening tag ends at the first `>` outside every `{…}` expression, string
+// literal and comment. A plain `[^>]*?>` stops inside `onClick={() =>` and
+// hides any `title=` written after the handler (#113688). Comments matter too:
+// a `// …doesn't…` note between attributes would otherwise open a quote.
+function findTagClose(content: string, start: number): number {
+ let depth = 0
+ let quote: null | string = null
+
+ for (let i = start; i < content.length; i++) {
+ const char = content[i]
+
+ if (quote) {
+ if (char === '\\') {
+ i++
+ } else if (char === quote) {
+ quote = null
+ }
+
+ continue
+ }
+
+ if (char === '/' && content[i + 1] === '/') {
+ const eol = content.indexOf('\n', i)
+
+ if (eol < 0) {
+ return -1
+ }
+
+ i = eol
+
+ continue
+ }
+
+ if (char === '/' && content[i + 1] === '*') {
+ const close = content.indexOf('*/', i + 2)
+
+ if (close < 0) {
+ return -1
+ }
+
+ i = close + 1
+
+ continue
+ }
+
+ if (char === '"' || char === "'" || char === '`') {
+ quote = char
+ } else if (char === '{') {
+ depth++
+ } else if (char === '}') {
+ depth--
+ } else if (char === '>' && depth === 0) {
+ return i
+ }
+ }
+
+ return -1
+}
+
+// `title=` as an attribute of its own — not `data-title=` / `subtitle=`.
+const TITLE_ATTR = /(?<![\w.-])title=/u
+
+function titleViolations(content: string, relativePath: string): string[] {
+ const violations: string[] = []
+
+ for (const { attrs, index, tagName } of eachButtonOpenTag(content)) {
+ if (TITLE_ATTR.test(attrs)) {
+ const lineNum = content.slice(0, index).split('\n').length
+
+ violations.push(`${relativePath}:${lineNum} <${tagName}> has title= — use <Tip> or aria-label`)
+ }
+ }
+
+ return violations
+}
+
+describe('no native title= on button elements', () => {
+ it('sees title= after inline handlers and inside comment-bearing tags, and nowhere else', () => {
+ const flagged = [
+ '<button onClick={() => {}} title="probe">hi</button>',
+ '<Button\n onClick={event => {\n event.preventDefault()\n }}\n // macOS doesn\'t focus a button on mousedown\n title={copy.send}\n type="button"\n>',
+ "<button className={cn(saved ? 'a' : 'b')} title={on ? m.off(t) : m.on(t)}>"
+ ]
+
+ const clean = [
+ '<button aria-label="a > b" onClick={() => {}}>hi</button>',
+ '<button data-title="x" onClick={() => {}}>hi</button>',
+ '<button onClick={() => {}}>{`title=${x}`}</button>',
+ '<span title="fine"><button type="button">hi</button></span>'
+ ]
+
+ for (const source of flagged) {
+ expect(titleViolations(source, 'probe.tsx'), source).toHaveLength(1)
+ }
+
+ for (const source of clean) {
+ expect(titleViolations(source, 'probe.tsx'), source).toEqual([])
+ }
+ })
+
+ // Scan every shipped .tsx file under src/ for <button or <Button opening tags
+ // that also carry a title= attribute (anywhere in the opening tag, which may
+ // span multiple lines).
+ it('uses <Tip> or aria-label instead of native title= on all button elements', () => {
+ const violations: string[] = []
+ const srcDir = resolve(__dirname, '../../..')
+
+ for (const filePath of collectTsxFiles(srcDir)) {
+ const content = readFileSync(filePath, 'utf-8')
+ const relativePath = filePath.replace(srcDir + '/', '')
+
+ violations.push(...titleViolations(content, relativePath))
+ }
+
+ expect(violations, violations.join('\n')).toEqual([])
+ })
+})
diff --git a/apps/desktop/src/plugins/hermes-bots/relay-deliver-budget.test.ts b/apps/desktop/src/plugins/hermes-bots/relay-deliver-budget.test.ts
new file mode 100644
index 00000000000..97c82ad8fe0
--- /dev/null
+++ b/apps/desktop/src/plugins/hermes-bots/relay-deliver-budget.test.ts
@@ -0,0 +1,70 @@
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+import { describe, expect, it } from 'vitest'
+
+// #93911 review follow-up: the Desktop deadline for bot_relay.deliver mirrors
+// three backend numbers. Nothing in the type system links a TS constant to a
+// Python default, so this file is the seam: it reads the backend sources and
+// fails when a mirror drifts or the settlement margin stops being positive.
+// Without it, raising the backend turn timeout would silently reintroduce
+// #93911 — the client giving up before a valid typed settlement arrives.
+
+const relaySource = readFileSync(join(process.cwd(), 'src/plugins/hermes-bots/relay.ts'), 'utf8')
+const repoRoot = join(process.cwd(), '..', '..')
+const configDefaults = readFileSync(join(repoRoot, 'hermes_cli/config_defaults.py'), 'utf8')
+const relayPlumbing = readFileSync(join(repoRoot, 'tools/bot_relay.py'), 'utf8')
+
+function tsConstant(name: string): number {
+ const match = relaySource.match(new RegExp(`const ${name} = ([0-9_]+)`))
+ expect(match, `${name} must stay a literal so this test can read it`).toBeTruthy()
+
+ return Number(match![1].replaceAll('_', ''))
+}
+
+function pyConstant(name: string): number {
+ const match = relayPlumbing.match(new RegExp(`^${name}\\s*=\\s*(\\d+)`, 'm'))
+ expect(match, `${name} must exist as a literal in tools/bot_relay.py`).toBeTruthy()
+
+ return Number(match![1])
+}
+
+describe('bot_relay.deliver budget mirrors', () => {
+ it('mirrors the backend turn-lock default', () => {
+ const lockWaitMatch = configDefaults.match(/"turn_wait_seconds":\s*(\d+)/)
+
+ expect(lockWaitMatch, 'bot_mode.turn_wait_seconds default must exist in config_defaults.py').toBeTruthy()
+ expect(tsConstant('RELAY_TURN_LOCK_WAIT_MS')).toBe(Number(lockWaitMatch![1]) * 1000)
+ })
+
+ it('mirrors the backend per-attempt turn timeout', () => {
+ // The backend names both numbers explicitly (tools/bot_relay.py) so the mirror is a
+ // constant-to-constant check, not a count of textual subprocess.run(...) call sites.
+ expect(tsConstant('RELAY_TURN_ATTEMPT_MS')).toBe(pyConstant('TURN_ATTEMPT_TIMEOUT_SECONDS') * 1000)
+ expect(tsConstant('RELAY_TURN_MAX_ATTEMPTS')).toBe(pyConstant('TURN_MAX_ATTEMPTS'))
+ })
+
+ it('shares its settlement margin with the sender-side waiter budget', () => {
+ // tests/tools/test_bot_relay.py checks that REPLY_WAIT_SECONDS exceeds the rebuilt sum.
+ expect(tsConstant('RELAY_DELIVER_SETTLEMENT_MARGIN_MS')).toBe(
+ pyConstant('DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDS') * 1000
+ )
+ })
+
+ it('keeps the client deadline strictly greater than the backend ceiling', () => {
+ const margin = tsConstant('RELAY_DELIVER_SETTLEMENT_MARGIN_MS')
+
+ // Strictly greater, not equal: a backend that answers at its own limit
+ // still has to serialize and transport that answer.
+ expect(margin, 'settlement margin must be positive').toBeGreaterThan(0)
+
+ // The call site must pass the composed budget, not a bare literal.
+ const drain = relaySource.slice(
+ relaySource.indexOf('async function drainRelayOutboxes'),
+ relaySource.indexOf('export function startBotRelay')
+ )
+
+ expect(drain).toMatch(/'bot_relay\.deliver'[\s\S]{0,400}RELAY_DELIVER_TIMEOUT_MS/)
+ expect(drain).not.toMatch(/'bot_relay\.deliver'[\s\S]{0,400}\d{6,}/)
+ })
+})
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py
index 39358fb0e0a..4416a46d7aa 100644
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@ -516,7 +516,7 @@ def _skip_background_prefetch() -> bool:
(``patch("subprocess.run")`` / ``patch("subprocess.Popen")``) can record
that stray spawn in place of the call it meant to pin. Importing
``tui_gateway.server`` starts this prefetch, which is what flaked
- tests/tui_gateway/test_subprocess_encoding.py and test_bot_relay_methods.py.
+ tests/tui_gateway/test_bot_relay_methods.py.
Nothing under pytest needs a live update check; tests that exercise the
prefetch itself monkeypatch this predicate to False.
diff --git a/scripts/ci/check_os_marker_fakes.py b/scripts/ci/check_os_marker_fakes.py
index 2f6509ed865..d3f3891efb0 100644
--- a/scripts/ci/check_os_marker_fakes.py
+++ b/scripts/ci/check_os_marker_fakes.py
@@ -49,15 +49,6 @@ _FAKES = (
# Files that faked macOS before this check existed (#111866). Burn down, never extend.
_BASELINE = frozenset(
{
- "tests/hermes_cli/test_linux_sandbox_fixup.py",
- "tests/hermes_cli/test_macos_fda_guidance.py",
- "tests/hermes_cli/test_orphan_desktop_serve_reap.py",
- "tests/hermes_cli/test_update_launchd_restart_verification.py",
- "tests/hermes_cli/test_update_launchd_unloaded_gateway.py",
- "tests/hermes_cli/test_urllib_security.py",
- "tests/test_hermes_constants.py",
- "tests/tools/test_macos_protected_search.py",
- "tests/tools/test_skills_tool.py",
}
)
diff --git a/tests/agent/test_subprocess_env_guard.py b/tests/agent/test_subprocess_env_guard.py
new file mode 100644
index 00000000000..a904c319951
--- /dev/null
+++ b/tests/agent/test_subprocess_env_guard.py
@@ -0,0 +1,112 @@
+"""Lint guard: no new raw ``os.environ.copy()`` spawn-env sites.
+
+Every child-process env in the codebase must be built through
+``tools.environments.local.build_subprocess_env`` (or its sibling
+``hermes_subprocess_env`` / ``_sanitize_subprocess_env``, which the factory
+wraps) so profile-home propagation and secret-scrubbing have a single owner.
+History: ~11 commits over 6 months each fixed one more spawn site that missed
+``HERMES_HOME`` or secret-scrub propagation.
+
+This test greps the source tree for ``os.environ.copy()`` appearing within
+``PROXIMITY_LINES`` lines of a spawn call (``Popen`` / ``subprocess.run`` /
+``create_subprocess*`` / ``PtyProcess.spawn`` / ``execvpe``) and asserts every
+hit is in the explicit allowlist below. If you are adding a new spawn site:
+
+* use ``build_subprocess_env(...)`` — with ``scrub_secrets=False,
+ inherit_profile_home=False`` if you need today's exact-inherit behavior; or
+* consciously add the file to ``ALLOWED_RAW_SPAWN_ENV_FILES`` with a comment
+ explaining why the factory cannot be used.
+"""
+
+import re
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+# Directories that make up the shipped source tree.
+SCAN_DIRS = ("agent", "hermes_cli", "tools", "gateway", "cron", "tui_gateway")
+SCAN_ROOT_FILES = ("cli.py", "hermes_constants.py")
+
+# How many lines around an `os.environ.copy()` we look for a spawn call.
+PROXIMITY_LINES = 20
+
+SPAWN_RE = re.compile(
+ r"\bPopen\b|\bsubprocess\.run\b|\bcreate_subprocess|\bPtyProcess\.spawn\b"
+ r"|\bexecvpe\b|\bptyprocess\.PtyProcess\b|\bspawn\("
+)
+COPY_RE = re.compile(r"\bos\.environ\.copy\(\)")
+
+# ---------------------------------------------------------------------------
+# ALLOWLIST — intentionally-raw sites. Each entry is a relative posix path.
+# Adding to this list is a conscious decision: document WHY inline here.
+# ---------------------------------------------------------------------------
+ALLOWED_RAW_SPAWN_ENV_FILES = {
+ # THE owner module: _sanitize_subprocess_env / hermes_subprocess_env /
+ # build_subprocess_env legitimately snapshot os.environ — everything else
+ # delegates to them.
+ "tools/environments/local.py",
+ # Bang-shell (`!cmd` in the CLI) goes through build_subprocess_env(); the
+ # only raw copy is the except-fallback for when the tools package itself
+ # cannot be imported, so the user's typed command still runs.
+ "hermes_cli/bang_shell.py",
+}
+
+
+def _iter_source_files():
+ for d in SCAN_DIRS:
+ root = REPO_ROOT / d
+ if root.is_dir():
+ yield from root.rglob("*.py")
+ for f in SCAN_ROOT_FILES:
+ p = REPO_ROOT / f
+ if p.is_file():
+ yield p
+
+
+def _raw_spawn_env_sites():
+ """Return [(relpath, lineno)] of os.environ.copy() near a spawn call."""
+ sites = []
+ for path in _iter_source_files():
+ rel = path.relative_to(REPO_ROOT).as_posix()
+ try:
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError:
+ continue
+ for i, line in enumerate(lines):
+ stripped = line.lstrip()
+ if stripped.startswith("#"):
+ continue # comments referencing the old pattern are fine
+ if not COPY_RE.search(line.split("#", 1)[0]):
+ continue
+ lo = max(0, i - PROXIMITY_LINES)
+ hi = min(len(lines), i + PROXIMITY_LINES + 1)
+ window = "\n".join(lines[lo:hi])
+ if SPAWN_RE.search(window):
+ sites.append((rel, i + 1))
+ return sites
+
+
+def test_no_new_raw_environ_copy_spawn_sites():
+ sites = _raw_spawn_env_sites()
+ offenders = [
+ f"{rel}:{lineno}"
+ for rel, lineno in sites
+ if rel not in ALLOWED_RAW_SPAWN_ENV_FILES
+ ]
+ assert not offenders, (
+ "New raw os.environ.copy() spawn-env site(s) found:\n "
+ + "\n ".join(offenders)
+ + "\nUse tools.environments.local.build_subprocess_env() instead "
+ "(scrub_secrets=False, inherit_profile_home=False preserves exact "
+ "legacy behavior), or consciously extend "
+ "ALLOWED_RAW_SPAWN_ENV_FILES in this test with a justification."
+ )
+
+
+def test_allowlist_entries_still_exist():
+ """Prune the allowlist when files are removed/renamed."""
+ for rel in ALLOWED_RAW_SPAWN_ENV_FILES:
+ assert (REPO_ROOT / rel).is_file(), (
+ f"Allowlist entry {rel} no longer exists — remove it from "
+ "ALLOWED_RAW_SPAWN_ENV_FILES."
+ )
diff --git a/tests/ci/test_classify_changes.py b/tests/ci/test_classify_changes.py
index d79244d2109..3a8d0f88b9d 100644
--- a/tests/ci/test_classify_changes.py
+++ b/tests/ci/test_classify_changes.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import importlib.util
import io
import json
+import re
import subprocess
import sys
from pathlib import Path
@@ -140,6 +141,16 @@ CASES = {
"flake.lock → nix only": (["flake.lock"], _lanes(nix=True)),
# A flake-only file must not mask a Python change beside it.
"nix + python → both": (["nix/checks.nix", "agent/x.py"], _lanes(python=True, scan=True)),
+ # Nine checks run the built binary, so product Python is a nix input even
+ # when the diff touches no file under nix/.
+ "product python → nix": (["hermes_cli/config.py"], _lanes(python=True, scan=True)),
+ # tests/ is not packaged, so the built binary cannot change.
+ "tests-only → no nix": (
+ ["tests/agent/test_foo.py"],
+ _lanes(python=True, python_prod=False, scan=True),
+ ),
+ # Prose cannot change the closure or the binary.
+ "docs-only → no nix": (["README.md"], _lanes()),
# install.ps1 is a shell script Python never imports, but it's also not
# provably prose, so python stays on (fail-open) alongside the Windows lane.
"install.ps1 → installer": (["scripts/install.ps1"], _lanes(python=True, installer=True)),
@@ -147,6 +158,7 @@ CASES = {
["scripts/tests/test-install-ps1-longpath.ps1"],
_lanes(python=True, installer=True),
),
+ "python source alone → no installer lane": (["run_agent.py"], _lanes(python=True, scan=True)),
# The Windows desktop-update hand-off is a PowerShell integration surface:
# its tests spawn the real script and poll its loopback server. They run
# when the script, the Electron side that launches it, or their own test
@@ -169,6 +181,7 @@ CASES = {
["apps/desktop/electron/updater-process.ts"],
_lanes(frontend=True, desktop_updater=True),
),
+ "python source alone → no desktop_updater lane": (["hermes_state.py"], _lanes(python=True, scan=True)),
# `.rs` lives under apps/, so it matches `frontend` too. That lane builds
# TypeScript and cannot notice a Rust error — before `rust` existed it was
# the ONLY lane a Rust change ran, and the crate's tests never executed.
@@ -235,6 +248,22 @@ CASES = {
["eslint.config.shared.mjs"],
_lanes(python=True, ci_review=True),
),
+ "ui-tui eslint config → ci_review": (
+ ["ui-tui/eslint.config.mjs"],
+ _lanes(frontend=True, ci_review=True),
+ ),
+ "web eslint config → ci_review": (
+ ["web/eslint.config.js"],
+ _lanes(frontend=True, ci_review=True),
+ ),
+ "shared package eslint config → ci_review": (
+ ["apps/shared/eslint.config.mjs"],
+ _lanes(frontend=True, ci_review=True),
+ ),
+ "bootstrap-installer eslint config → ci_review": (
+ ["apps/bootstrap-installer/eslint.config.mjs"],
+ _lanes(frontend=True, ci_review=True),
+ ),
"prettier config → ci_review": (
[".prettierrc"],
_lanes(python=True, ci_review=True),
@@ -247,6 +276,14 @@ CASES = {
[".github/actions/retry/action.yml"],
DEFAULT,
),
+ # Normal desktop source doesn't trigger ci_review.
+ "desktop src → no ci_review": (
+ ["apps/desktop/src/app.tsx"],
+ _lanes(frontend=True),
+ ),
+ # Fail open: CI-config / empty / blank diffs run everything.
+ ".github change → all": ([".github/workflows/tests.yml"], DEFAULT),
+ "action change → all": ([".github/actions/detect-changes/action.yml"], DEFAULT),
"empty diff → all": ([], DEFAULT),
"blank lines → all": (["", " "], DEFAULT),
}
@@ -257,6 +294,55 @@ def test_classify(files, expected):
assert classify(files) == expected
+_REPO = Path(__file__).resolve().parents[2]
+
+
+def _yaml(rel: str) -> dict:
+ yaml = pytest.importorskip("yaml")
+ return yaml.safe_load((_REPO / rel).read_text(encoding="utf-8"))
+
+
+def test_every_lane_reaches_the_composite_action():
+ """The action is the one surface every consumer reads, so it must carry all
+ of them — ci.yaml, nix.yml and docker.yml each re-export a different subset.
+ """
+ lanes = set(classify(["run_agent.py"]))
+ action_outputs = set(_yaml(".github/actions/detect-changes/action.yml")["outputs"])
+ assert lanes - action_outputs == set(), "lane(s) missing from the composite action's outputs"
+
+
+def test_ci_jobs_only_gate_on_detect_outputs_that_detect_actually_declares():
+ """An ``if`` that reads an undeclared output resolves to the empty string.
+
+ The lane then reports "skipping" on every PR, forever, and nothing goes red
+ — there is no error for referencing an output a job never declared. That is
+ exactly how the ``rust`` lane shipped dead: the classifier emitted it and
+ the composite action re-exported it, but ci.yaml's ``detect`` job did not,
+ so ``needs.detect.outputs.rust`` was never anything but "".
+ """
+ ci = _yaml(".github/workflows/ci.yaml")
+ declared = set(ci["jobs"]["detect"]["outputs"])
+
+ referenced: set[str] = set()
+ for job in ci["jobs"].values():
+ for expr in _iter_if_expressions(job):
+ referenced.update(re.findall(r"needs\.detect\.outputs\.(\w+)", expr))
+
+ assert referenced, "found no detect-gated jobs — the walk is broken, not the wiring"
+ assert referenced - declared == set(), "job(s) gate on an output detect never declares"
+
+
+def _iter_if_expressions(job: object):
+ """Yield every ``if:`` string in a job, including inside its steps."""
+ if not isinstance(job, dict):
+ return
+ if isinstance(cond := job.get("if"), str):
+ yield cond
+ for step in job.get("steps", []) or []:
+ if isinstance(step, dict) and isinstance(cond := step.get("if"), str):
+ yield cond
+
+
def test_ci_review_files_returns_only_sensitive_paths_sorted_and_unique():
assert ci_review_files([
"apps/desktop/src/app.tsx",
diff --git a/tests/ci/test_live_comment.py b/tests/ci/test_live_comment.py
index 5bc7875ff38..b4c1329eb05 100644
--- a/tests/ci/test_live_comment.py
+++ b/tests/ci/test_live_comment.py
@@ -12,6 +12,7 @@ import importlib.util
import sys
from pathlib import Path
+import pytest
_PATH = Path(__file__).resolve().parents[2] / "scripts" / "ci" / "live_comment.py"
_spec = importlib.util.spec_from_file_location("live_comment", _PATH)
@@ -87,6 +88,55 @@ def test_parse_watch_workflows_keeps_commas_inside_a_name():
assert _mod.parse_watch_workflows("") == []
+def test_workflow_watch_list_names_a_workflow_that_exists():
+ """The names the workflow passes must match real workflow ``name:`` values.
+
+ A name that matches nothing makes the poller silently drop that run
+ from the comment, which no unit test on its own would notice.
+ """
+ yaml = pytest.importorskip("yaml")
+ root = Path(__file__).resolve().parents[2]
+ caller = yaml.safe_load(
+ (root / ".github/workflows/ci-review-comment.yml").read_text(encoding="utf-8")
+ )
+ step = next(
+ s for s in caller["jobs"]["comment"]["steps"]
+ if "WATCH_WORKFLOWS" in (s.get("env") or {})
+ )
+ watched = _mod.parse_watch_workflows(step["env"]["WATCH_WORKFLOWS"])
+ assert watched, "the poller is watching nothing"
+
+ known = set()
+ for path in (root / ".github/workflows").glob("*.yml"):
+ doc = yaml.safe_load(path.read_text(encoding="utf-8"))
+ if isinstance(doc, dict) and isinstance(doc.get("name"), str):
+ known.add(doc["name"])
+
+ assert set(watched) <= known, f"unknown workflow names: {set(watched) - known}"
+
+
+def test_poller_never_watches_its_own_workflow():
+ """The poller's own run must never gate completion.
+
+ ``runs_all_completed`` waits until every relevant run is completed.
+ The poller's run is in progress for as long as it polls, so watching
+ itself would make the loop wait for itself and only ever exit on
+ timeout.
+ """
+ yaml = pytest.importorskip("yaml")
+ root = Path(__file__).resolve().parents[2]
+ doc = yaml.safe_load(
+ (root / ".github/workflows/ci-review-comment.yml").read_text(encoding="utf-8")
+ )
+ own_name = doc["name"]
+ step = next(
+ s for s in doc["jobs"]["comment"]["steps"]
+ if "WATCH_WORKFLOWS" in (s.get("env") or {})
+ )
+ watched = _mod.parse_watch_workflows(step["env"]["WATCH_WORKFLOWS"])
+ assert own_name not in watched
+
+
# ─── runs_all_completed ───────────────────────────────────────────────
diff --git a/tests/gateway/relay/test_relay_sheds_crypto.py b/tests/gateway/relay/test_relay_sheds_crypto.py
new file mode 100644
index 00000000000..0d84c7b8ae0
--- /dev/null
+++ b/tests/gateway/relay/test_relay_sheds_crypto.py
@@ -0,0 +1,90 @@
+"""Invariant: the relay path sheds platform crypto — it re-validates nothing.
+
+Under the A2 trust model (see website/docs/developer-guide/relay-connector-contract.md §6), the
+*connector* is the sole crypto/identity boundary: it verifies/decrypts every
+inbound platform payload at the edge (it holds the tenant secrets), normalizes
+it to a tenant-scoped ``MessageEvent``, and forwards only the sanitized event.
+The gateway re-validates nothing — it cannot, without being handed the shared
+signing secret, which would itself be the leak on a shared bot.
+
+The relay package therefore MUST NOT import or call platform signature/crypto
+verification (Discord ed25519, Twilio HMAC, WeCom BizMsgCrypt, generic webhook
+signature checks). Those live in the *direct* platform adapters
+(``gateway/platforms/*``) which serve non-relay deployments; the relay receives
+already-trusted events. This test fails if someone bolts re-validation onto the
+relay path, re-coupling the gateway to platform secrets it must never hold.
+
+It is an invariant (asserts the *relation* "relay imports no crypto"), not a
+change-detector snapshot of a frozen import list.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+from pathlib import Path
+
+# gateway/relay package directory: tests/gateway/relay/ -> repo root parents[3].
+_REPO_ROOT = Path(__file__).resolve().parents[3]
+_RELAY_PKG = _REPO_ROOT / "gateway" / "relay"
+
+# Modules / symbols that mean "platform crypto re-validation". If the relay path
+# imports any of these it has re-coupled the gateway to a platform secret.
+_FORBIDDEN_MODULE_TOKENS = (
+ "wecom_crypto",
+ "wecom_callback",
+ "webhook", # gateway.platforms.webhook holds signature verification
+)
+_FORBIDDEN_SYMBOL_RE = re.compile(
+ r"(ed25519|verify_key|verifykey|verify_signature|verify_ed25519|"
+ r"verify_webhook|bizmsg|hmac|x[-_]signature)",
+ re.IGNORECASE,
+)
+
+
+def _relay_py_files() -> list[Path]:
+ assert _RELAY_PKG.is_dir(), f"relay package missing at {_RELAY_PKG}"
+ return sorted(_RELAY_PKG.glob("*.py"))
+
+
+# ``auth.py`` is the connector⇄gateway CHANNEL authenticator (the gateway's WS
+# upgrade bearer). It is net-new, intended, and the whole point of
+# authenticating an untrusted/disposable gateway — it is NOT platform crypto.
+# It uses HMAC over the connector's per-gateway secret (NOT any platform's
+# signing secret), so it is exempt from the platform-crypto symbol scan below.
+# The module-import ban (platform-crypto modules) still applies to every file
+# including this one — it imports only stdlib hmac/hashlib, never a
+# platform-crypto module, so it stays clean there.
+_CHANNEL_AUTH_FILES = {"auth.py"}
+
+
+def test_relay_package_calls_no_signature_verification():
+ """No relay module references a PLATFORM signature/crypto-verification symbol.
+
+ Scoped to platform crypto (Discord ed25519, Twilio/WeCom HMAC, webhook
+ signature checks). The connector⇄gateway channel authenticator (``auth.py``)
+ is exempt: its HMAC is over the connector's own per-gateway/per-tenant
+ secrets to authenticate the relay channel itself — the gateway holds NO
+ platform secret and re-validates NO platform payload. See ``auth.py`` and
+ docs/connector-gateway-auth-design.md.
+ """
+ offenders: list[str] = []
+ for path in _relay_py_files():
+ if path.name in _CHANNEL_AUTH_FILES:
+ continue
+ for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
+ # Skip comments / docstrings-as-prose: only flag code-like usage.
+ stripped = line.strip()
+ if stripped.startswith("#"):
+ continue
+ m = _FORBIDDEN_SYMBOL_RE.search(line)
+ if m:
+ offenders.append(f"{path.name}:{lineno}: '{m.group(0)}' in: {stripped[:80]}")
+ assert not offenders, (
+ "The relay path must not perform platform signature/crypto verification "
+ "(A2). Found verification-symbol references:\n "
+ + "\n ".join(offenders)
+ + "\nThe connector verifies at the edge; the gateway re-validates nothing."
+ )
+
+
diff --git a/tests/gateway/test_gateway_utf8_encoding.py b/tests/gateway/test_gateway_utf8_encoding.py
new file mode 100644
index 00000000000..2ecc559e6ad
--- /dev/null
+++ b/tests/gateway/test_gateway_utf8_encoding.py
@@ -0,0 +1,60 @@
+"""Static guard: every ``read_text`` / ``write_text`` call in the gateway and
+bundled update-response adapters must pass an explicit ``encoding=`` keyword
+argument so non-UTF-8 Windows locales don't corrupt file IPC. Mirrors the
+AST-based guard pattern in
+``tests/tools/test_windows_compat.py``.
+"""
+
+import ast
+import pathlib
+import pytest
+
+REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
+GATEWAY_DIR = REPO_ROOT / "gateway"
+UPDATE_RESPONSE_FILES = (
+ REPO_ROOT / "plugins/platforms/discord/adapter.py",
+ REPO_ROOT / "plugins/platforms/telegram/adapter.py",
+ REPO_ROOT / "plugins/platforms/feishu/adapter.py",
+ REPO_ROOT / "plugins/platforms/whatsapp/adapter.py",
+ REPO_ROOT / "plugins/platforms/google_chat/adapter.py",
+ REPO_ROOT / "plugins/platforms/google_chat/oauth.py",
+)
+METHODS = {"read_text", "write_text"}
+SUPPRESSION = "# gateway-utf8: ok"
+
+
+def _find_violations():
+ violations = []
+ py_files = list(GATEWAY_DIR.rglob("*.py")) + list(UPDATE_RESPONSE_FILES)
+ for py_file in sorted(py_files):
+ source = py_file.read_text(encoding="utf-8")
+ source_lines = source.splitlines()
+ try:
+ tree = ast.parse(source, filename=str(py_file))
+ except SyntaxError:
+ continue
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ if not isinstance(func, ast.Attribute):
+ continue
+ if func.attr not in METHODS:
+ continue
+ if any(kw.arg == "encoding" for kw in node.keywords):
+ continue
+ lineno = node.lineno
+ if lineno <= len(source_lines) and SUPPRESSION in source_lines[lineno - 1]:
+ continue
+ rel = py_file.relative_to(REPO_ROOT)
+ violations.append(f"{rel}:{lineno}")
+ return violations
+
+
+def test_all_read_write_text_pass_encoding():
+ violations = _find_violations()
+ assert not violations, (
+ "Bare read_text()/write_text() calls found (missing encoding= kwarg).\n"
+ "Add encoding=\"utf-8\" or suppress with '# gateway-utf8: ok':\n"
+ + "\n".join(f" {v}" for v in violations)
+ )
diff --git a/tests/hermes_cli/test_config_read_guard.py b/tests/hermes_cli/test_config_read_guard.py
new file mode 100644
index 00000000000..d47ca1068ec
--- /dev/null
+++ b/tests/hermes_cli/test_config_read_guard.py
@@ -0,0 +1,132 @@
+"""Lint guard: no new raw yaml.safe_load(config.yaml) reads outside owner modules.
+
+The drift class this kills: scattered ``yaml.safe_load`` reads of the user's
+``config.yaml`` silently miss the managed-scope overlay, ``${ENV_VAR}``
+expansion, profile-aware pathing, and root-model normalization. Each new
+config feature has historically required an N-site sweep (incident chain:
+9cbcc0c9c8 → 732293cf87 → b0e47a98f9 → 1928aa0443).
+
+Canonical owners:
+
+ * ``hermes_cli/config.py`` — ``load_config()`` / ``load_config_readonly()``
+ (merged + managed + env-expanded), ``read_raw_config()`` and
+ ``read_user_config_raw()`` (the ONLY legal raw primitives: write-back
+ round-trips + raw-file diagnostics).
+ * ``gateway/config.py`` — the gateway's ``load_gateway_config`` owner.
+ * ``gateway/run.py`` — ``_load_gateway_config()``'s monkeypatched-home
+ fallback path (delegates to ``read_raw_config`` when paths agree).
+
+Everything else must import one of those. If this test fails on your new
+code, use ``load_config()``/``load_config_readonly()`` for behavioral reads,
+or ``read_user_config_raw()`` for write-back round-trips — do not add your
+file to the allowlist without a reason of the same class.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent.parent
+
+# Files where a yaml.safe_load near a config.yaml reference is legal.
+# Keep this list SHORT and justified:
+ALLOWLIST = {
+ # Canonical loader owners.
+ "hermes_cli/config.py",
+ "gateway/config.py",
+ # load_gateway_config()'s config.yaml phase lives here (extracted from
+ # gateway/config.py); same owner, same managed-overlay contract.
+ "gateway/config_loader.py",
+ # _load_gateway_config()'s fallback path for tests that monkeypatch
+ # gateway.run._hermes_home (delegates to read_raw_config otherwise).
+ "gateway/run.py",
+ # Reads the MANAGED-scope config.yaml (/etc/hermes/...), not the user's —
+ # it IS the overlay source; the canonical loaders call into it.
+ "hermes_cli/managed_scope.py",
+ # Parse-health probe: intentionally answers "does the raw file parse?".
+ "gateway/readiness.py",
+}
+
+# Directories that never count (tests may build fixture configs freely).
+EXCLUDED_DIR_PARTS = {
+ "tests", ".venv", ".git", ".worktrees", "node_modules", "website",
+ "docs", "scripts", "examples", "apps",
+ # Compiled bytecode is not source. Sibling test processes also create
+ # and delete these directories while this scan walks the tree.
+ "__pycache__",
+}
+
+# A safe_load within this many lines of a config.yaml reference is treated
+# as a raw user-config read.
+PROXIMITY = 6
+
+SAFE_LOAD_RE = re.compile(r"\bsafe_load\s*\(")
+CONFIG_YAML_RE = re.compile(r"""["']config\.yaml["']""")
+
+
+def _iter_source_files():
+ # This uses os.walk with a pruned dirnames, and not rglob. rglob descends
+ # into every directory and filters after that, so it calls scandir() on
+ # __pycache__ trees that this guard never inspects. Sibling test processes
+ # create and delete those entries during the run.
+ #
+ # A directory that disappears in the middle of a walk raises
+ # FileNotFoundError out of rglob. The test then fails for a reason that it
+ # does not assert.
+ #
+ # The prune skips those trees. The onerror callback ignores a directory
+ # that disappears anyway.
+ for dirpath, dirnames, filenames in os.walk(REPO_ROOT, onerror=lambda _e: None):
+ dirnames[:] = [d for d in dirnames if d not in EXCLUDED_DIR_PARTS]
+ for name in filenames:
+ if not name.endswith(".py"):
+ continue
+ path = Path(dirpath) / name
+ rel = path.relative_to(REPO_ROOT)
+ if any(part in EXCLUDED_DIR_PARTS for part in rel.parts):
+ continue
+ yield rel, path
+
+
+def test_no_raw_config_yaml_reads_outside_owner_modules():
+ offenders: list[str] = []
+ for rel, path in _iter_source_files():
+ rel_str = str(rel).replace("\\", "/")
+ if rel_str in ALLOWLIST:
+ continue
+ try:
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
+ except OSError:
+ continue
+ cfg_lines = [i for i, ln in enumerate(lines) if CONFIG_YAML_RE.search(ln)]
+ if not cfg_lines:
+ continue
+ for i, ln in enumerate(lines):
+ if not SAFE_LOAD_RE.search(ln):
+ continue
+ # Comment/docstring mentions don't count.
+ stripped = ln.strip()
+ if stripped.startswith("#"):
+ continue
+ if any(abs(i - j) <= PROXIMITY for j in cfg_lines):
+ offenders.append(f"{rel_str}:{i + 1}: {stripped}")
+
+ assert not offenders, (
+ "Raw yaml.safe_load of config.yaml outside allowlisted owner modules.\n"
+ "Behavioral reads must use hermes_cli.config.load_config()/"
+ "load_config_readonly() (or gateway _load_gateway_config); write-back "
+ "round-trips and raw-file diagnostics must use "
+ "hermes_cli.config.read_user_config_raw().\nOffenders:\n "
+ + "\n ".join(offenders)
+ )
+
+
+def test_read_user_config_raw_exists_and_documented():
+ """The shared raw primitive must exist and carry its legality docstring."""
+ from hermes_cli.config import read_user_config_raw
+
+ doc = read_user_config_raw.__doc__ or ""
+ assert "ONLY legal for write-back round-trips and raw-file diagnostics" in doc
+ assert "load_config()" in doc
diff --git a/tests/hermes_cli/test_subprocess_timeouts.py b/tests/hermes_cli/test_subprocess_timeouts.py
new file mode 100644
index 00000000000..47146aac444
--- /dev/null
+++ b/tests/hermes_cli/test_subprocess_timeouts.py
@@ -0,0 +1,44 @@
+"""Tests for subprocess.run() timeout coverage in CLI utilities."""
+import ast
+from pathlib import Path
+
+import pytest
+
+
+# Parameterise over every CLI module that calls subprocess.run
+_CLI_MODULES = [
+ "hermes_cli/doctor.py",
+ "hermes_cli/status.py",
+ "hermes_cli/clipboard.py",
+ "hermes_cli/banner.py",
+]
+
+
+def _subprocess_run_calls(filepath: str) -> list[dict]:
+ """Parse a Python file and return info about subprocess.run() calls."""
+ source = Path(filepath).read_text()
+ tree = ast.parse(source, filename=filepath)
+ calls = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ if (isinstance(func, ast.Attribute) and func.attr == "run"
+ and isinstance(func.value, ast.Name)
+ and func.value.id == "subprocess"):
+ has_timeout = any(kw.arg == "timeout" for kw in node.keywords)
+ calls.append({"line": node.lineno, "has_timeout": has_timeout})
+ return calls
+
+
[email protected]("filepath", _CLI_MODULES)
+def test_all_subprocess_run_calls_have_timeout(filepath):
+ """Every subprocess.run() call in CLI modules must specify a timeout."""
+ if not Path(filepath).exists():
+ pytest.skip(f"{filepath} not found")
+ calls = _subprocess_run_calls(filepath)
+ missing = [c for c in calls if not c["has_timeout"]]
+ assert not missing, (
+ f"{filepath} has subprocess.run() without timeout at "
+ f"line(s): {[c['line'] for c in missing]}"
+ )
diff --git a/tests/hermes_state/test_no_locked_readers_gate.py b/tests/hermes_state/test_no_locked_readers_gate.py
new file mode 100644
index 00000000000..0664669a9a1
--- /dev/null
+++ b/tests/hermes_state/test_no_locked_readers_gate.py
@@ -0,0 +1,291 @@
+"""Pattern-C gate: pure-read SessionDB methods must not take the writer lock.
+
+The gateway shares ONE SessionDB across every agent. ``self._lock`` guards
+the single writer connection — any read-only query executed under it
+convoys every concurrent turn's persistence behind that reader (Pattern C
+of the 2026-08 perf triage; #90734 shipped the unlocked-reader subset,
+this gate covers the locked-reader subset).
+
+``_read_ctx()`` exists precisely for reads: WAL reader from a bounded
+pool, no lock, with a byte-identical fallback to the locked writer when
+WAL is off. Reads have no reason to hold the writer lock.
+
+The gate parses ``hermes_state.py`` with ``ast`` and flags any method
+that (a) opens ``with self._lock:`` and (b) runs ONLY read statements
+(SELECT/PRAGMA-read) on ``self._conn`` inside it — i.e. a pure reader
+convoying on the writer lock. Methods that write under the lock are the
+lock's legitimate users and pass. New violations fail with the method
+name and the fix (route through ``_read_ctx()``).
+
+``SessionDB`` itself is declared in ``hermes_state.py`` as
+``class SessionDB(SessionSearchMixin, SessionSchemaMixin,
+SessionPortabilityMixin)`` — its actual methods live across four files.
+A gate that only opens ``hermes_state.py`` never sees a locked reader
+declared in one of the three mixin files, so ``_ALL_STATE_SOURCES`` scans
+each of them under their own class name.
+
+Deliberately NOT flagged:
+- methods that INSERT/UPDATE/DELETE/REPLACE under the lock (writers);
+- read-modify-write methods (the read is ordered against its own write);
+- ``_read_ctx``'s own writer-fallback (``yield self._conn`` — no execute);
+- SELECTs on ``conn``/other objects (already pooled readers).
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+from pathlib import Path
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_STATE_PY = _REPO_ROOT / "hermes_state.py"
+
+# SessionDB's own class body lives in hermes_state.py; the rest of its
+# methods come from these mixins (see module docstring). Each entry is
+# (source file, class name to scan in that file).
+_ALL_STATE_SOURCES: list[tuple[Path, str]] = [
+ (_STATE_PY, "SessionDB"),
+ (_REPO_ROOT / "hermes_state_search.py", "SessionSearchMixin"),
+ (_REPO_ROOT / "hermes_state_schema.py", "SessionSchemaMixin"),
+ (_REPO_ROOT / "hermes_state_portability.py", "SessionPortabilityMixin"),
+]
+
+_WRITE_RE = re.compile(
+ r"^\s*(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER|VACUUM|BEGIN|COMMIT|ANALYZE)\b",
+ re.IGNORECASE,
+)
+# PRAGMA is read-only EXCEPT the checkpoint/optimize family, which mutates
+# the database file and legitimately belongs on the writer connection.
+_PRAGMA_WRITE_RE = re.compile(
+ r"^\s*PRAGMA\s+(wal_checkpoint|optimize|incremental_vacuum|integrity_check)",
+ re.IGNORECASE,
+)
+_READ_RE = re.compile(r"^\s*(SELECT|PRAGMA)\b", re.IGNORECASE)
+
+# Methods allowed to keep a pure-read body under the writer lock, each with
+# the reason. Keep this list SHRINKING — never add to it without the same
+# scrutiny a new blocking call would get.
+_ALLOWED_LOCKED_READERS: dict[str, str] = {
+ # get_meta stays on the writer lock BY DESIGN (see its inline comment):
+ # fts_rebuild_step reads rebuild progress before entering a write
+ # transaction, and a pooled WAL reader sees only committed data — the
+ # writer's own just-staged meta updates would be invisible to it.
+ "get_meta": "read-your-writes: rebuild progress read before write txn",
+}
+
+
+def _first_sql_text(call: ast.Call) -> str | None:
+ """Best-effort SQL text from an execute()'s first argument."""
+ if not call.args:
+ return None
+ arg = call.args[0]
+ text = None
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
+ text = arg.value
+ elif isinstance(arg, ast.JoinedStr):
+ parts = [
+ v.value for v in arg.values
+ if isinstance(v, ast.Constant) and isinstance(v.value, str)
+ ]
+ text = "".join(parts)
+ if not text or not text.strip():
+ return None
+ return text.strip()
+
+
+def _is_self_conn_execute(call: ast.Call, aliases: set[str]) -> bool:
+ """Match ``self._conn.execute*`` and ``<alias>.execute*`` where the
+ alias was bound from ``self._conn`` (``conn = self._conn``)."""
+ f = call.func
+ if not (
+ isinstance(f, ast.Attribute)
+ and f.attr in ("execute", "executemany", "executescript")
+ ):
+ return False
+ target = f.value
+ if (
+ isinstance(target, ast.Attribute)
+ and target.attr == "_conn"
+ and isinstance(target.value, ast.Name)
+ and target.value.id == "self"
+ ):
+ return True
+ return isinstance(target, ast.Name) and target.id in aliases
+
+
+def _collect_conn_aliases(method: ast.AST) -> set[str]:
+ """Names bound from ``self._conn`` anywhere in the method body."""
+ aliases: set[str] = set()
+ for node in ast.walk(method):
+ if isinstance(node, ast.Assign) and isinstance(node.value, ast.Attribute):
+ v = node.value
+ if (
+ v.attr == "_conn"
+ and isinstance(v.value, ast.Name)
+ and v.value.id == "self"
+ ):
+ for t in node.targets:
+ if isinstance(t, ast.Name):
+ aliases.add(t.id)
+ return aliases
+
+
+def _is_self_lock_with(item: ast.withitem) -> bool:
+ ctx = item.context_expr
+ return (
+ isinstance(ctx, ast.Attribute)
+ and ctx.attr == "_lock"
+ and isinstance(ctx.value, ast.Name)
+ and ctx.value.id == "self"
+ )
+
+
+def _scan_locked_readers(
+ state_py: "Path | None" = None, class_name: str = "SessionDB"
+) -> list[str]:
+ target = state_py if state_py is not None else _STATE_PY
+ tree = ast.parse(target.read_text(encoding="utf-8"))
+ violations: list[str] = []
+
+ session_db = None
+ for node in tree.body:
+ if isinstance(node, ast.ClassDef) and node.name == class_name:
+ session_db = node
+ break
+ assert session_db is not None, f"{class_name} class not found in {target}"
+
+ for method in session_db.body:
+ if not isinstance(method, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ aliases = _collect_conn_aliases(method)
+ for node in ast.walk(method):
+ if not isinstance(node, ast.With):
+ continue
+ if not any(_is_self_lock_with(i) for i in node.items):
+ continue
+ reads, writes, unknown = 0, 0, 0
+ for inner in ast.walk(node):
+ if isinstance(inner, ast.Call) and _is_self_conn_execute(inner, aliases):
+ word_full = _first_sql_text(inner)
+ word = word_full.split(None, 1)[0].upper() if word_full else None
+ if word is None:
+ # SQL held in a variable or built f-string: the
+ # scanner cannot prove it reads. A lock block whose
+ # ONLY statements are unprovable is still flagged
+ # below — writers name their verbs in literals
+ # throughout this file, so opacity correlates with
+ # composed SELECTs, and silently skipping these is
+ # how 5 readers hid from the first version of this
+ # gate.
+ unknown += 1
+ elif _PRAGMA_WRITE_RE.match(word_full or ""):
+ writes += 1
+ elif _WRITE_RE.match(word):
+ writes += 1
+ elif _READ_RE.match(word):
+ reads += 1
+ else:
+ unknown += 1
+ # Method calls under the lock may write internally
+ # (e.g. self._execute_write, cursor ops) — treat any
+ # self.<something>() as potentially writing.
+ elif isinstance(inner, ast.Call):
+ f = inner.func
+ if (
+ isinstance(f, ast.Attribute)
+ and isinstance(f.value, ast.Name)
+ and f.value.id == "self"
+ and (
+ "write" in f.attr
+ or "commit" in f.attr
+ or f.attr.startswith(("set_", "record_", "insert_",
+ "update_", "delete_", "clear_"))
+ )
+ ):
+ writes += 1
+ if writes == 0 and (reads > 0 or unknown > 0):
+ if method.name not in _ALLOWED_LOCKED_READERS:
+ kind = "pure-read" if unknown == 0 else "no-proven-write"
+ violations.append(
+ f"{method.name} (line {node.lineno}): {kind} "
+ f"body under `with self._lock:` — route through "
+ f"_read_ctx() instead (or add a justified "
+ f"allowlist entry)"
+ )
+ return violations
+
+
+def _scan_all_state_sources() -> list[str]:
+ """Run ``_scan_locked_readers`` over every file that contributes methods
+ to ``SessionDB`` — the class body in ``hermes_state.py`` plus each mixin
+ it inherits from (see module docstring). Violations are prefixed with
+ their source filename since methods can share names across mixins.
+ """
+ violations: list[str] = []
+ for path, class_name in _ALL_STATE_SOURCES:
+ for v in _scan_locked_readers(path, class_name):
+ violations.append(f"{path.name}: {v}")
+ return violations
+
+
+class TestNoPureReadersUnderWriterLock:
+ def test_no_locked_pure_readers(self):
+ violations = _scan_all_state_sources()
+ assert violations == [], (
+ "Pure-read SessionDB methods holding the writer lock "
+ "(Pattern C — every concurrent turn's persistence convoys "
+ "behind these reads):\n " + "\n ".join(violations)
+ )
+
+ def test_gate_detects_a_locked_reader(self, tmp_path):
+ """Sabotage self-check: the scanner must flag a synthetic violation."""
+ sabotage = (
+ "class SessionDB:\n"
+ " def innocent_writer(self):\n"
+ " with self._lock:\n"
+ " self._conn.execute(\"UPDATE t SET x = 1\")\n"
+ " def guilty_reader(self):\n"
+ " with self._lock:\n"
+ " return self._conn.execute(\"SELECT 1\").fetchone()\n"
+ " def guilty_alias_reader(self):\n"
+ " with self._lock:\n"
+ " conn = self._conn\n"
+ " return conn.execute(\"SELECT 2\").fetchone()\n"
+ " def guilty_variable_sql(self, query):\n"
+ " with self._lock:\n"
+ " return self._conn.execute(query).fetchall()\n"
+ " def innocent_variable_writer(self, query):\n"
+ " with self._lock:\n"
+ " self._conn.execute(query)\n"
+ " self._conn.execute(\"UPDATE t SET x = 2\")\n"
+ )
+ p = tmp_path / "fake_state.py"
+ p.write_text(sabotage, encoding="utf-8")
+ violations = _scan_locked_readers(p)
+ flagged = {v.split(" ")[0] for v in violations}
+ assert flagged == {
+ "guilty_reader", "guilty_alias_reader", "guilty_variable_sql"
+ }, violations
+
+ def test_scan_all_state_sources_visits_every_mixin_file(self, tmp_path):
+ """Sabotage self-check for the multi-file scope itself: a locked
+ reader planted in a MIXIN file (not hermes_state.py) must still be
+ caught. Guards against the gate's scope silently narrowing back to
+ one file — exactly how the real 2026-08 gap (9 locked readers across
+ three mixin files, invisible to the single-file scanner) happened.
+ """
+ mixin_sabotage = (
+ "class FakeMixin:\n"
+ " def guilty_mixin_reader(self):\n"
+ " with self._lock:\n"
+ " return self._conn.execute(\"SELECT 1\").fetchone()\n"
+ )
+ p = tmp_path / "fake_mixin.py"
+ p.write_text(mixin_sabotage, encoding="utf-8")
+
+ violations = [
+ f"{p.name}: {v}" for v in _scan_locked_readers(p, "FakeMixin")
+ ]
+ assert any("guilty_mixin_reader" in v for v in violations), violations
diff --git a/website/docs/developer-guide/egress-internals.md b/website/docs/developer-guide/egress-internals.md
index 45ceb8d3ed2..26dddb17dcd 100644
--- a/website/docs/developer-guide/egress-internals.md
+++ b/website/docs/developer-guide/egress-internals.md
@@ -57,9 +57,6 @@ tests/hermes_cli/test_iron_proxy_cli.py CLI handler unit tests (~20).
wire-up, dest='egress_command'
regression guard.
-tests/agent/test_iron_proxy_e2e.py Live E2E (gated on HERMES_RUN_E2E=1).
- Real iron-proxy binary, real curl,
- end-to-end token swap verified.
```
## Lifecycle
@@ -300,9 +297,6 @@ iron-proxy writes line-delimited JSON to `~/.hermes/proxy/iron-proxy.log` on the
# Hermetic suite (no network, no real binary)
scripts/run_tests.sh tests/agent/test_iron_proxy.py tests/hermes_cli/test_iron_proxy_cli.py
-# Live E2E (real binary, real curl, real CONNECT tunnel)
-HERMES_RUN_E2E=1 scripts/run_tests.sh tests/agent/test_iron_proxy_e2e.py
-
# Live PTY smoke against `hermes egress`
HERMES_HOME=$HOME/.hermes/cache/scratch/hermes-egress-test python3 -m hermes_cli.main egress --help
HERMES_HOME=$HOME/.hermes/cache/scratch/hermes-egress-test python3 -m hermes_cli.main egress setup --help
diff --git a/website/docs/developer-guide/provider-runtime.md b/website/docs/developer-guide/provider-runtime.md
index a1718fd3435..7f12e7ddb3d 100644
--- a/website/docs/developer-guide/provider-runtime.md
+++ b/website/docs/developer-guide/provider-runtime.md
@@ -221,7 +221,6 @@ Fallback behavior is exercised across several suites:
- `tests/agent/test_fallback_credential_isolation.py` — credential isolation between primary and fallback
- `tests/hermes_cli/test_fallback_cmd.py` — the `/fallback` CLI command
-- `tests/gateway/test_fallback_eviction.py` — gateway eviction of failed providers
## Related docs