The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
ci: advisory profile-scope pattern lint on the lines a PR adds
teknium1f13a87e61061
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex ff6e60781e0..8d25f08db77 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -185,6 +185,24 @@ jobs:- name: Forbid in-tree use of plugin-compat pointersrun: python scripts/check_compat_pointers.py+ # Advisory: profile-scope hazard shapes on the lines this PR adds (child env from os.environ,+ # raw os.getenv of a platform credential, HOME-only RPC binding, bare-PID liveness). One+ # process serves many profiles; every pattern leaked the launch profile at least once. Printed+ # into the log for the reviewer; never fails the job (root AGENTS.md § Code Shape Rules).+ - name: Profile-scope patterns on added lines (advisory)+ if: github.event_name == 'pull_request'+ continue-on-error: true+ timeout-minutes: 3+ env:+ PR_HEAD: "+refs/pull/${{ github.event.pull_request.number }}/head:refs/remotes/origin/pr-head"+ run: |+ git fetch --no-tags --deepen=200 origin "${{ github.base_ref }}" "$PR_HEAD"+ for i in 1 2 3; do+ git merge-base "origin/${{ github.base_ref }}" origin/pr-head >/dev/null 2>&1 && break+ git fetch --no-tags --deepen=1000 origin "${{ github.base_ref }}" "$PR_HEAD"+ done+ python scripts/check_profile_scope_patterns.py --base "origin/${{ github.base_ref }}" --head origin/pr-head+# Advisory: dropped public names / methods / test defs vs the PR base, printed into the log.# A refactor that silently removes a public symbol breaks plugins that import it; the Sep 2026# decomposition opened with 1,703 such drops that reviewers had to find by hand.diff --git a/scripts/check_profile_scope_patterns.py b/scripts/check_profile_scope_patterns.pynew file mode 100644index 00000000000..dc7e7f38214--- /dev/null+++ b/scripts/check_profile_scope_patterns.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+"""Advisory lint: profile-scope hazard patterns on the lines a change adds.++One Hermes process may serve many profiles (multiplex gateway, Desktop/dashboard ``serve``), and+``os.environ`` / module globals hold only the LAUNCH profile's values. Every pattern in+``scripts/ci/profile_scope_patterns.json`` is a call-site shape that turned out to be+profile-sensitive at least once — a child env built from ``os.environ``, a raw ``os.getenv`` of a+platform credential, an RPC decorator that binds the home but not the secret scope, a bare PID+liveness check. The invariant itself is in the root ``AGENTS.md`` (§ Code Shape Rules).++Advisory by construction: it prints ``file:line <id>/<class> why`` for every hit and ALWAYS+exits 0, because most patterns have legitimate sites (a standalone ``hermes -p x`` process where+environ IS the profile). The reviewer reads each finding against its ``scope_hint``.++Usage:+ python scripts/check_profile_scope_patterns.py [--base origin/main] [--head HEAD]+ python scripts/check_profile_scope_patterns.py --files tools/bot_relay.py ... # whole files+ python scripts/check_profile_scope_patterns.py --base origin/main --json out.json+"""+from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+from dataclasses import asdict, dataclass+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+PATTERNS = ROOT / "scripts" / "ci" / "profile_scope_patterns.json"+SUFFIXES = (".py", ".ts", ".tsx")+SKIP_PREFIXES = ("tests/", "website/", "skills/", "optional-skills/", "evals/", "scripts/", ".worktrees/")+_HUNK_RE = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@")+++@dataclass(frozen=True)+class Finding:+ path: str+ line: int+ pattern_id: str+ pattern_class: str+ why: str+ scope_hint: str+ text: str+++def load_patterns(path: Path = PATTERNS) -> list[dict]:+ data = json.loads(path.read_text(encoding="utf-8"))+ out = []+ for p in data["patterns"]:+ out.append({**p, "_rx": re.compile(p["pattern_regex"], re.M)})+ return out+++def _lint_path(rel: str) -> bool:+ return rel.endswith(SUFFIXES) and not rel.startswith(SKIP_PREFIXES) and "/tests/" not in rel and "node_modules" not in rel+++def scan_text(rel: str, text: str, patterns: list[dict], lines: set[int] | None = None) -> list[Finding]:+ """Findings for *text*; ``lines`` restricts to those 1-based line numbers (None = whole file).+ Multi-line patterns are anchored on the line where the match starts."""+ findings: list[Finding] = []+ src_lines = text.split("\n")+ for p in patterns:+ for m in p["_rx"].finditer(text):+ line_no = text.count("\n", 0, m.start()) + 1+ if lines is not None and line_no not in lines:+ continue+ findings.append(Finding(rel, line_no, p["id"], p["class"], p["why"], p["scope_hint"],+ src_lines[line_no - 1].strip()[:160]))+ return findings+++def _git(*args: str) -> str:+ proc = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace")+ return proc.stdout+++def added_lines_vs_base(base: str, head: str | None) -> dict[str, set[int]]:+ """``{path: {added line numbers in head}}`` for lint-able files changed between *base* and *head*+ (working tree when *head* is None)."""+ rev = [base, head] if head else [base]+ diff = _git("diff", "--no-color", "-U0", "--diff-filter=AM", *rev, "--")+ out: dict[str, set[int]] = {}+ current: str | None = None+ for raw in diff.split("\n"):+ if raw.startswith("+++ "):+ name = raw[4:]+ current = name[2:] if name.startswith("b/") else None+ if current is not None and not _lint_path(current):+ current = None+ continue+ if current is None:+ continue+ m = _HUNK_RE.match(raw)+ if m:+ start, count = int(m.group(1)), int(m.group(2) or "1")+ out.setdefault(current, set()).update(range(start, start + count))+ return out+++def _read(rel: str, head: str | None) -> str | None:+ if head:+ cmd = ["git", "show", f"{head}:{rel}"]+ r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace")+ return r.stdout if r.returncode == 0 else None+ path = ROOT / rel+ return path.read_text(encoding="utf-8", errors="replace") if path.is_file() else None+++def run(base: str | None, head: str | None, files: list[str], patterns: list[dict]) -> list[Finding]:+ findings: list[Finding] = []+ if files:+ for f in files:+ path = Path(f)+ text = path.read_text(encoding="utf-8", errors="replace") if path.is_file() else None+ if text is None:+ continue+ resolved = path.resolve()+ rel = str(resolved.relative_to(ROOT)) if resolved.is_relative_to(ROOT) else str(path)+ findings.extend(scan_text(rel, text, patterns))+ return findings+ for rel, lines in sorted(added_lines_vs_base(base or "origin/main", head).items()):+ text = _read(rel, head)+ if text is not None:+ findings.extend(scan_text(rel, text, patterns, lines))+ return findings+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--base", default="origin/main", help="base ref for the added-lines diff")+ ap.add_argument("--head", default=None, help="head ref (default: working tree)")+ ap.add_argument("--files", nargs="*", default=[], help="scan these whole files instead of a diff")+ ap.add_argument("--json", default=None, help="also write findings as JSON to this path")+ args = ap.parse_args(argv)++ patterns = load_patterns()+ findings = run(args.base, args.head, args.files, patterns)+ if args.json:+ Path(args.json).write_text(json.dumps([asdict(f) for f in findings], indent=2) + "\n", encoding="utf-8")+ if not findings:+ print("profile-scope patterns: 0 findings")+ return 0+ print(f"profile-scope patterns: {len(findings)} finding(s) — ADVISORY, read each against its scope hint "+ f"(root AGENTS.md § Code Shape Rules; scripts/ci/profile_scope_patterns.json)")+ for f in findings:+ print(f"{f.path}:{f.line} {f.pattern_id}/{f.pattern_class} {f.why}")+ print(f" | {f.text}")+ print(f" hint: {f.scope_hint}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/ci/profile_scope_patterns.json b/scripts/ci/profile_scope_patterns.jsonnew file mode 100644index 00000000000..50baf25932b--- /dev/null+++ b/scripts/ci/profile_scope_patterns.json@@ -0,0 +1,165 @@+{+ "meta": {+ "source": "hermes-agent-dev skill, cross-cutting-profile-scope-patterns.json (validated pattern set)",+ "selection": "patterns with a scope_hint that hit <= 50 sites on main; the >50 ones are review greps, not lint",+ "class_legend": {+ "C1": "secret/home read outside the turn scope",+ "C2": "child-process env built from os.environ",+ "C3": "side-worker / secondary entrypoint binds home only",+ "C4": "per-profile key introduced, consumer reads raw name/id",+ "C5": "adapter setting precedence & raw os.getenv fallback",+ "C6": "launch-profile / reserved-name asymmetry",+ "C7": "process identity by bare PID or argv substring",+ "C8": "config key registry vs runtime reader",+ "C9": "systemd/launchd unit variants & migration transactionality",+ "C10": "profile lifecycle ops under a live multiplexer",+ "C11": "bare thread lifecycle / supervision",+ "C12": "Desktop topology / surface parity (CLI vs REST vs RPC)",+ "C13": "kanban notifier routing / silent fail-closed"+ },+ "dropped": [+ "P01: 296 hits on main",+ "P02: 378 hits on main",+ "P03: 222 hits on main",+ "P04: 613 hits on main",+ "P07: 115 hits on main",+ "P09: 78 hits on main",+ "P12: 73 hits on main",+ "P14: 102 hits on main",+ "P15: 212 hits on main",+ "P16: 100 hits on main",+ "P20: 81 hits on main",+ "P24: 62 hits on main",+ "P26: 252 hits on main"+ ],+ "usage": "scripts/check_profile_scope_patterns.py --base origin/main [--head HEAD] | --files <paths>"+ },+ "patterns": [+ {+ "id": "P05",+ "class": "C2",+ "pattern_regex": "subprocess\\.(Popen|run|check_output)\\([^)]*env\\s*=\\s*(os\\.environ|dict\\(os\\.environ|\\{\\*\\*os\\.environ)|env\\s*=\\s*os\\.environ\\.copy\\(\\)|spawn\\([^)]*env:\\s*process\\.env|env\\s*=\\s*dict\\(os\\.environ\\)|\\{\\*\\*os\\.environ\\}",+ "scope_hint": "Also grep the named builders: _build_child_env, _bridge_env, _brv_child_env, build_subprocess_env( without scrub/scope. Assert HERMES_HOME and profile-varying vars from INSIDE a real child.",+ "why": "Children inherit the launch process's HERMES_HOME and secrets: MCP stdio servers got the default vault, WhatsApp bridge.js ran the default's dm_policy, brv curated into the default's cloud account, execute_code skill scripts read the default's OAuth tokens. Four spawn sites fixed one at a time."+ },+ {+ "id": "P06",+ "class": "C5",+ "pattern_regex": "os\\.getenv\\(\\s*[\"'](DISCORD|TELEGRAM|SLACK|MATRIX|WHATSAPP|FEISHU|SIGNAL|TEAMS|LINE|WECOM|YUANBAO|HINDSIGHT|BRV|A2A|WEIXIN)_|os\\.environ\\.get\\(\\s*[\"'](DISCORD|TELEGRAM|SLACK|MATRIX|WHATSAPP|FEISHU|SIGNAL|TEAMS|LINE|WECOM|YUANBAO|HINDSIGHT|BRV|A2A|WEIXIN)_",+ "scope_hint": "plugins/platforms/*, plugins/memory/*, gateway/run_config_loaders.py, gateway/platforms/*. Replace with gateway.platforms._shared.extra_or_secret(extra, key, ENV, default) or get_scoped_secret.",+ "why": "Raw env is the launch profile's. A secondary that omits a key must get the adapter default, not the launch profile's value (Matrix notices/session_scope, Discord everyone-mentions, Slack ignored channels all inherited). MindDragon probe still lists TELEGRAM_WEBHOOK_HOST and run_config_loaders.py:64,93 as open."+ },+ {+ "id": "P08",+ "class": "C5",+ "pattern_regex": "configured\\s*=\\s*extra\\.get\\(|if\\s+configured\\s+is\\s+not\\s+None:\\s*return|extra\\.get\\([\"'][a-z_]+[\"']\\)\\s*(if|or)\\s*.*os\\.getenv",+ "scope_hint": "Any 'YAML first, env fallback' reader in an adapter. Order must be explicit scoped env -> own YAML -> default; add the single-profile control test (env=false beats materialized YAML true).",+ "why": "Materialized defaults (telegram.reactions: false) are always present in YAML, so a YAML-first reader makes the documented env switch a permanent no-op."+ },+ {+ "id": "P10",+ "class": "C6",+ "pattern_regex": "if\\s+not\\s+(get_hermes_home_override|current_secret_scope|_served_profile_homes)\\b|profile\\s*(==|!=)\\s*[\"']main[\"']|agent:main\\b",+ "scope_hint": "Launch-profile branches that treat 'no override' as 'no scope needed'; reserved-name checks.",+ "why": "The launch profile has its own contract (env-only TERMINAL_ENV=ssh, root files writable, a profile literally named 'main'); tests only asserted secondary isolation and the launch turn collapsed to file-only policy / the default namespace."+ },+ {+ "id": "P11",+ "class": "C4",+ "pattern_regex": "^(_active_sessions|_DB_CACHE|_servers|_backends|_session_owner_homes|_trust[a-z_]*|_parallel[a-z_]*|_cooldown[a-z_]*)\\s*[:=]\\s*(\\{\\}|dict\\(|\\{\\s*$)|\\.setdefault\\((task_id|session_id|server_name|name)\\b",+ "scope_hint": "Module-level dicts keyed by session_id / task_id / server_name / display alone. Key must include hermes_home_key() or (scope, name) when a profile override is active; release must use the same key.",+ "why": "Two profiles legitimately share session names, DISPLAY numbers and MCP server names; the first profile's entry wins and B's release stops A's driver. #108935 keyed 36 caches and still missed browser_exec/computer_use."+ },+ {+ "id": "P13",+ "class": "C4",+ "pattern_regex": "def _connection_identity\\(|def _same_server_route\\(|config_fingerprint\\(",+ "scope_hint": "MCP connection sharing across profiles: identity must include every credential source, including ones stored outside the config dict (OAuth token files under <profile>/mcp-tokens, client_cert/client_key).",+ "why": "Identical-looking configs authenticated as different accounts were adopted across profiles; whoami flipped between two Google accounts inside one WhatsApp session."+ },+ {+ "id": "P17",+ "class": "C8",+ "pattern_regex": "DEFAULT_CONFIG\\[[\"']\\w+[\"']\\]\\[[\"']\\w+[\"']\\]|\\.get\\([\"'](auto_migrate|auto_multiplex_migration|notify_in_gateway|dispatch_in_gateway)[\"']",+ "scope_hint": "For every new DEFAULT_CONFIG key, one test: the effective config exposes exactly the key the reader consumes (grep the reader's .get() spelling). Also: a runtime that requires a key (webhook route 'profile') needs the CLI that writes the file to expose it.",+ "why": "DEFAULT_CONFIG declared gateway.auto_migrate while the guard read gateway.auto_multiplex_migration, and 'hermes config set' pointed operators at the dead spelling; hermes webhook subscribe never wrote the 'profile' key the runtime required (100% 404 on /p/<profile>/)."+ },+ {+ "id": "P18",+ "class": "C9",+ "pattern_regex": "systemd_install\\(|_installed_service\\(|_service_op\\(|launchd_install\\(|User=",+ "scope_hint": "Pass run_as_user read from the unit being replaced; represent every installed unit (user AND system) not a scalar; unresolved User= stays None and blocks the unattended path; wrap install/start after destructive steps in rollback via the manifest; treat flag-on + manifest + no live default as 'interrupted', not 'already multiplexing'.",+ "why": "Migration passed preflight, uninstalled the secondaries, then raised 'Refusing to install ... as root' with nothing catching it: host left with no gateway and the flag on. Unattended hermes update folded per-UNIX-user system units into one process."+ },+ {+ "id": "P19",+ "class": "C10",+ "pattern_regex": "copytree\\([^)]*symlinks\\s*=\\s*True|shutil\\.copytree\\(.*profiles|old_dir\\.rename\\(|_check_gateway_running\\(\\s*old_dir",+ "scope_hint": "Profile create/clone/rename/delete: materialize symlinked .env/config.yaml/auth.json before editing; build in profiles/.<name>.staging-<pid> and publish with one rename; under a live multiplexer unroute before mutating (a served secondary has no gateway.pid of its own).",+ "why": "--clone-all stripped the SOURCE's Telegram token through a preserved symlink; the hot-serve rescan adopted a half-copied clone with the source's bots; rename left a ghost the multiplexer re-scaffolded and served."+ },+ {+ "id": "P21",+ "class": "C3",+ "pattern_regex": "def _spawn_side_agent\\(|def _profile_build_scope\\(|prompt\\.(background|btw)|preview\\.restart|_build_branch_agent\\(",+ "scope_hint": "Every secondary entrypoint must enter _session_profile_runtime_scope (home -> secrets -> terminal, same composition as a prompt turn) and hold its own registry reference on the DB.",+ "why": "Side workers bound HERMES_HOME only: they picked the launch terminal backend (local instead of the secondary's docker) and shared the parent's state.db handle so parent close() closed it under a running background turn."+ },+ {+ "id": "P22",+ "class": "C3",+ "pattern_regex": "scan_skill_commands\\(|get_skill_bundles\\(|resolve_bundle_command_key\\(|_is_profile_skill_command\\(|def _dispatch_(skill|bundle)\\(",+ "scope_hint": "command.dispatch's whole stage loop (quick -> plugin -> bundle -> skill) and slash.exec bundle routing must run under the session's profile home; use the home-keyed get_skill_commands().",+ "why": "The router bound the profile and said 'skill exists', the dispatcher scanned the launch home and answered 4018 'not a skill command' for every secondary-only skill."+ },+ {+ "id": "P23",+ "class": "C1",+ "pattern_regex": "@_profile_scoped_rpc|@_profile_scoped\\b|def _profile_scoped_rpc\\(|_profile_home\\(\\s*profile",+ "scope_hint": "A decorator that only sets the HERMES_HOME override is insufficient for anything that expands ${VAR} refs, builds MCP clients, or spawns terminals; bind secret scope (after hydrating external secret sources) and terminal scope too.",+ "why": "Desktop 'Test connection' and the REST MCP list/test/auth sites resolved ${GITHUB_PERSONAL_ACCESS_TOKEN} from the launch process, sending the default's bearer to a secondary's server (HTTP 400 loop, tools missing)."+ },+ {+ "id": "P25",+ "class": "C12",+ "pattern_regex": "fetch\\(\\s*[`'\"]/api/(gateway|status|mcp|cron|sessions)[^`'\"]*[`'\"]\\s*[,)]|apiFetch\\([^)]*\\)(?!.*profile)|profilePickConnectionId\\(|resolveNewChatOwnerRoute\\(",+ "scope_hint": "apps/desktop/src and web/src: every lifecycle/status/settings request against a pooled local backend must carry ?profile= (or the profile param) and every new-session tile must record an owner route.",+ "why": "A pooled local backend routed lifecycle to the ambient profile (served profiles showed stopped); tab-strip + on a named local profile minted a session with no owner metadata so session.control.read failed closed."+ },+ {+ "id": "P27",+ "class": "C11",+ "pattern_regex": "def start\\(self\\).*\\n(?:.*\\n){0,15}?.*(recover_interrupted|record_ticker_heartbeat)|record_ticker_heartbeat\\(",+ "scope_hint": "cron/scheduler_provider.py and the Desktop desktop-cron-ticker: all pre-loop work inside the BaseException guard; publish the profile list only after the gate filtered it; housekeeping respawns a dead ticker.",+ "why": "A corrupt executions.db killed the ticker thread before the guarded loop; gateway stayed up, heartbeat frozen, no jobs, no error marker."+ },+ {+ "id": "P28",+ "class": "C1",+ "pattern_regex": "filter_media_delivery_paths\\(|_extract_response_content\\(|_docker_sandbox_dir_candidates\\(|_parse_docker_volume_mounts\\(",+ "scope_hint": "Delivery-side call sites run AFTER the turn's _profile_scope_for_source exited; wrap them in _media_delivery_scope (home + terminal policy).",+ "why": "A secondary's MEDIA:/output/x.png was validated against the default's Docker mounts and dropped (or the default's same-named decoy delivered)."+ },+ {+ "id": "P29",+ "class": "C1",+ "pattern_regex": "no_cache_check_fn\\(|_run_check_fn_uncached\\(|unresolved_scope\\s*=",+ "scope_hint": "tools/registry.py: classify UnscopedSecretError from current_secret_scope() at the catch site, never from a branch hint; boot-time probes with no scope are DEBUG, not WARNING+traceback.",+ "why": "The uncached check_fn branch passed unresolved_scope=False at gateway boot under multiplex, logging a traceback that tripped a deployment's post-update health gate and rolled it back."+ },+ {+ "id": "P30",+ "class": "C1",+ "pattern_regex": "_hydrate_profile_secret_sources\\(|_applied_homes|secrets\\.command",+ "scope_hint": "Mark a home hydrated only when every source succeeded; each attempt replaces the prior snapshot; revoke stale snapshots.",+ "why": "One failing secrets.command helper pinned an empty snapshot for the gateway lifetime, so the secondary ran credential-less until restart."+ },+ {+ "id": "P31",+ "class": "C6",+ "pattern_regex": "f\"agent:\\{|[\"']agent:[\"']\\s*\\+|session_key\\s*=\\s*f\"[a-z]+:",+ "scope_hint": "Every adapter-built session key carries the agent:<profile>: namespace (profile 'main' is 'agent:main~'); yuanbao still builds keys with no profile component per the MindDragon probe.",+ "why": "Rows for a served profile land in the root store; browser/computer_use caches never saw the namespace because turns pass the bare session id."+ }+ ]+}diff --git a/tests/scripts/test_check_profile_scope_patterns.py b/tests/scripts/test_check_profile_scope_patterns.pynew file mode 100644index 00000000000..7e5bb663224--- /dev/null+++ b/tests/scripts/test_check_profile_scope_patterns.py@@ -0,0 +1,68 @@+"""scripts/check_profile_scope_patterns.py flags a known profile-scope hazard and stays silent on clean code.++Advisory lint over the validated pattern set (``scripts/ci/profile_scope_patterns.json``): a child env+built from ``os.environ`` is the shape that leaked the launch profile's secrets into served-profile+children; the same spawn through ``served_profile_child_env`` is the fix and must not be flagged.+"""+import importlib.util+import sys+import textwrap+from pathlib import Path++SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "check_profile_scope_patterns.py"+++def _load():+ spec = importlib.util.spec_from_file_location("check_profile_scope_patterns", SCRIPT)+ mod = importlib.util.module_from_spec(spec)+ # dataclasses resolve string annotations through sys.modules[cls.__module__] (3.11).+ sys.modules[spec.name] = mod+ spec.loader.exec_module(mod)+ return mod+++def test_child_env_from_environ_is_flagged_and_the_scoped_builder_is_not():+ mod = _load()+ patterns = mod.load_patterns()+ assert patterns and all(p["scope_hint"] and p["why"] for p in patterns)++ hazard = textwrap.dedent('''+ import os, subprocess++ def delivery_env(author):+ env = dict(os.environ)+ env["HERMES_TURN_AUTHOR"] = author+ return env++ def run(cmd):+ return subprocess.Popen(cmd, env=os.environ.copy())+ ''')+ clean = textwrap.dedent('''+ import subprocess+ from tools.environments.local import served_profile_child_env++ def delivery_env(author, profile_home):+ env = served_profile_child_env(target_home=profile_home, inherit_credentials=True)+ env["HERMES_TURN_AUTHOR"] = author+ return env++ def run(cmd, env):+ return subprocess.Popen(cmd, env=env)+ ''')+ flagged = mod.scan_text("tools/x.py", hazard, patterns)+ assert {(f.line, f.pattern_id) for f in flagged} >= {(5, "P05"), (10, "P05")}+ assert all(f.pattern_class == "C2" and f.why for f in flagged if f.pattern_id == "P05")+ assert mod.scan_text("tools/x.py", clean, patterns) == []++ # Diff mode only reports lines the change added: restricting to the untouched line hides the hit.+ assert mod.scan_text("tools/x.py", hazard, patterns, lines={6}) == []+ assert [f.line for f in mod.scan_text("tools/x.py", hazard, patterns, lines={5})] == [5]+++def test_lint_is_advisory_and_exits_zero_with_findings(tmp_path, capsys):+ mod = _load()+ bad = tmp_path / "bad.py"+ bad.write_text("import os\nenv = os.environ.copy()\n", encoding="utf-8")+ assert mod.main(["--files", str(bad)]) == 0+ out = capsys.readouterr().out+ assert "P05/C2" in out and ":2 " in out and "ADVISORY" in out