Commit Graph

64 Commits

Author SHA1 Message Date
alt-glitch
e6f7b6732d fix(code-health): a folder made from a root module ships, and the guard needs __init__.py
Two review findings on the folder rule:

- A root module or an acp_adapter/ module turned into a folder drops out
  of setup.py's _root_py_modules and ships only if
  [tool.setuptools.packages.find] include matches it. The FILE_LINES fix
  text now names that step, and
  test_every_package_packaged_code_imports_is_found fails when packaged
  code imports a regular package the wheel would not ship (moving
  toolsets.py to toolsets/__init__.py fails it with ['toolsets']).
- Discovery skips a tool package without __init__.py, so
  check_tool_discovery counts only candidates whose package has one,
  and its message says so. An intent-added tools/newpkg/tool.py with no
  __init__.py now fails the guard.

Both changes are the reviewer's patches as suggested.
2026-11-16 11:52:44 +05:30
alt-glitch
c3bd0bfc53 docs(agents): root AGENTS.md says what a good package looks like
The file-size fix text asks for a <stem>/ folder, but nothing said what
a good folder looks like. Root AGENTS.md's facade section becomes
"Packages and Python shape":

- <stem>/__init__.py is the facade: its docstring names each module's
  job, __all__ is the surface, PEP 562 __getattr__ when eager imports
  would cycle, and it holds no behaviour (tools/connectors/ is the model).
- A family folder keeps its ABC or Protocol, one module per variant and
  a name-to-variant table (tools/environments/).
- Flat <stem>_<topic>.py siblings stay until touched; none are added.
- A Shape bullet: code imports on 3.11; importing has no side effects;
  input is parsed where it enters into a frozen dataclass, Enum or
  Literal; one return shape per function; dispatch by table; objects,
  not mixins; no module constant kept only for tests to patch.

The rules live in AGENTS.md because that is what agents load on every
turn; root stays inside its 12,100-character budget (11,831). The
FILE_LINES fix text and CONTRIBUTING's Code Style section point at the
section.
2026-11-16 11:52:44 +05:30
alt-glitch
e22250cf17 fix(code-health): the file-size fix text asks for a folder, guarded by a discovery test
The FILE_LINES/CC/FUNC_LINES fix text told contributors to split a big file
into a flat `<stem>_<topic>.py` sibling, which is how tools/ grew to 315 flat
files and tests/hermes_cli/ to 1,928. It now says to turn `<stem>.py` into a
`<stem>/` package and move code into a topic module there.

Inside a tools/ package, discovery imports only `<pkg>/tool.py`
(tools/registry.py `_tool_module_candidates`), so a module named anything else
that calls registry.register() at import is dropped without an error. A new
test lists every tracked module under tools/ that registers at import and
fails, naming the module, when discovery would not import it. Root AGENTS.md
and CONTRIBUTING.md carry the same rule.
2026-11-16 11:52:44 +05:30
alt-glitch
c942345770 fix(guards): stop passing truncated AGENTS.md chains and misjudging moved modules
The AGENTS.md chain cap is 30,600 so a chain at the cap still loads whole after the loader's per-file headers.
`from hermes_agent import <moved published module>` is no longer reported as a private import.
Code health pairs a module moved a second time with its last path, not the generated file at its first path.
2026-11-13 20:47:05 +00:00
alt-glitch
bbff53aa2e fix(code-health): spell the base like the head when judging a moved tree
A stacked pull request is judged against the previous chunk, whose files already name earlier-moved modules the new way, while the ratchet renamed only the head back to the old names. So an old violation on such a line, in any file the pull request touches, was reported as new: CI failed chunk 11 with 1 blocking finding and chunk 12 with 5. The base now goes through the same renaming (hit texts and the lines matched to place hits); against main nothing changes, because renaming leaves old names as they are.
2026-11-13 20:47:05 +00:00
alt-glitch
c51c0493c2 fix(move): guards skip generated old-path files; plugin API and packaging tests follow the tree; AGENTS.md caps fit the moved tree 2026-11-13 20:47:05 +00:00
alt-glitch
49b8a37f46 fix(code-health): judge a moved file against its base file, not as new code
A move leaves a generated file at the old path, so `git diff -M` reports an add plus a modify and
the ratchet measured every moved file as new: FILE_LINES on gateway/run.py, and every old
violation in a moved file as new (chunk 11: 25 blocking findings).

- When the head tree's MOVES maps an added file back to a path the base holds, the two are paired;
  the file left at the old path reads as new.
- A line that differs from a base line only by a module name MOVES renamed is the same line, and a
  hit on it keeps the base hit's fingerprint (the codemod rewrote imports that were already F811).

With MOVES empty nothing changes. New code in a moved file is still judged: 30 lines added to the
moved hermes_cli/main.py report FILE_LINES, BLE001 and S110.
2026-11-13 20:47:04 +00:00
alt-glitch
66261fe348 fix(profile-scope): match pattern path regexes against the original path
P32 and P33 restrict themselves with regexes anchored at old top-level names (gateway/, plugins/,
hermes_cli/, ...), matched against the raw path in the advisory lint and the code-health regex
rules. Once those trees move both patterns stop matching. Both now match original_path(path).
2026-11-13 20:47:04 +00:00
alt-glitch
8ace916abd fix: make path-keyed guards follow MOVES so a chunk need not edit them
Scan roots and lists go through current_path (footguns --all roots, config reader/writer trees,
detached-spawn trees and root files, subprocess-stdin dirs, the gateway parity scan root, the
plugin validator's core-handle source globs). Keys written in old paths (install-root baseline
and its depth test, detached-spawn helper and baseline, stdin KNOWN_SAFE, config-reader foreign
files, boundary-lint baseline, code-health rule globs, CI lane tables, public-surface source
dirs, plugin public-API names) are looked up by original_path/original_module of the file or
import under inspection, so they stay valid and a moved file is not judged new.
Root-name sets gain hermes_agent and the old names in MOVES; the plugin audit's registry-call
table follows MOVES; update_downgrade_guard drops the stale src/ path (its test and the
code-health CLI fixture follow). With MOVES empty every guard is unchanged.
2026-11-13 20:47:04 +00:00
Maciej Lisiewski
46e6db2892 fix(gateway): HX017 sees transcripts, user_display and getattr names; persist salt without link()
Extend HX017 to transcript/user_display and getattr(obj, "<name>", ...) and move the five INFO
sites it then flags (Discord/run_voice transcript, Discord mention-only display name, Telegram
approval/clarify first name + choice text) to lengths/ids. The Discord expired-interaction
WARNING logs only the slash verb. Where link() is refused the salt is created with O_EXCL, and
a failed salt read is cached per home so log calls stop retrying file I/O.

Refs #46006
2026-11-13 13:59:40 +01:00
Maciej Lisiewski
53a5c32f18 fix(gateway): keep user content and identities out of INFO+ logs
Gateway and adapter logs reach `hermes debug share` uploads, whose redaction covers
secrets only, so message bodies, subjects, display names, e-mail addresses and the
inbound-message preview were being published verbatim. INFO+ lines now carry lengths,
platform ids or a short `hash_for_log` digest; the raw value moves to DEBUG.

HX017 (scripts/code_health/py_rules_log_content.py) flags INFO+ log calls in gateway/
and plugins/platforms/ whose args are content-named values (text, body, subject,
user_name, display_name, sender_addr, ...). It is name-based on purpose: ids are not
matched, and transport payloads (resp.text, error_text) are skipped. Every existing
hit is fixed or waived with a reason, none baselined. Policy documented in
gateway/AGENTS.md and ADDING_A_PLATFORM.md.

Refs #46006
2026-11-13 13:59:39 +01:00
Anthony Holten
8f12eb61fd fix(read_file): drop the SQLite extractor change; production never opens a live store
read_file fetches document bytes through the file backend (a `base64 <
path` subprocess) and extract_document_bytes runs _extract_sqlite on a
private temp copy, so the extractor never opens a live database. The
guarded header read cost more than it protected: it held _live_lock
across the open (a FIFO named *.db would stall every tracked open/close)
and folded missing-file, directory and permission errors into one
message. Restore tools/read_extract.py and drop its tests.

Also name DEFAULT_DB_PATH, _default_db_path() and session_db.db_path
among HX015's documented misses.
2026-11-11 17:20:00 +01:00
Anthony Holten
c50101e5f5 fix(state): route in-process state.db opens through connect_tracked
has_live_connection() and offline_file_access() decide when raw byte I/O
on a live database is safe (closing any raw fd cancels the process's
POSIX locks on the file; #100519). They only see connections opened
through connect_tracked, and several in-process readers used a bare
sqlite3.connect. The read_file SQLite extractor also open()/close()d the
file to check its magic bytes, which cancels the gateway writer's locks
when the agent reads its own state.db.

Route those opens through connect_tracked with tracking_path (same
URIs, timeouts and flags): gateway readiness, the lifecycle ledger's
integrity and journal-mode reads, the API server response store, the
spillover reference scan, install state, doctor, the repair damage
check, shared metrics, the worktree liveness reads cron's sweep runs in
the gateway, backup verification, the restore destination and epoch
reads, the downgrade guard, approvals suggest (whose hand-built URI also
skipped percent-encoding) and the journal-mode switch. The read_file
magic check goes through read_header_bytes_preopen. Offline opens
(snapshots, staging copies, the stdlib-only backup copier) take a
documented HX015 waiver.

Add HX015, "untracked sqlite3.connect on state.db", an advisory
heuristic rule until a replay shows it can block.

Fixes #149276
2026-11-11 17:20:00 +01:00
Ben Barclay
1bd13ebac8 feat(scope): the scope names the agent's owner and role; a turn carries its fence
A Scope now says who owns the agent and what the activity may do on it, and a TurnScope says
which claim the turn runs under:

- Scope gains keyword-only owner (Principal for a personal agent, Group for a shared one) and
  role ("owner" | "manager" | "member"). A personal agent is used only by its owner, so its only
  role is "owner"; a group agent's roles are "manager" and "member". can_administer is true for
  owners and managers. A hosted scope must name both; a local scope defaults to the local person
  as owner with role "owner", so every local caller is unchanged.
- TurnScope gains fence: Fence(epoch, generation), the owner epoch and runtime generation the
  admission claim stamped. bind_turn(session, turn, fence) requires it; claim_fence(row) reads it
  off a claimed session_admissions row. The authority's turn path, the owner-side cron run and
  the managed worker bind the real fence.
- Inside a hosted scope a bind must keep tenant, agent, actor, owner and role; changing any of
  them raises ScopeSwitchRefused.
- bind_profile_scope / scope_for_profile drop the unused turn= tuple: a turn is marked only with
  bind_turn, which has the fence.

Tests that executed a never-claimed admission row now claim it first, as the drain does
(tests/gateway/session_claims.py); hand-built cron rows carry the claim's columns.
2026-11-11 09:54:19 -05:00
Ben Barclay
b738747fe8 docs(code-health): HX016 grandfathers an existing setter call even when its function changes
The rule text promised migration when a function is next edited; the ratchet compares lines, so an
edit around an old call never required it. Say what it does, and pin it with a test.
2026-11-11 09:44:33 -05:00
Ben Barclay
ad90be9b08 fix(scope): terminal policies name their owner; binds copy what they keep
Round-2 review findings:

- A raw terminal mapping could still replace the bound profile's policy with
  another profile's. Raw policies now go through bind_terminal_policy(policy,
  profile_home=...): inside a bound scope only the bound agent's own policy is
  accepted. The four callers pass the session's owning profile.
- A partial bind (home_override=False) inherited the home override from an
  earlier change, so resetting that change took it away. A bind now copies the
  pieces it keeps, so it is whole on its own.
- bind_state switched directly between hosted agents and tenants. Inside a
  hosted scope only a bind of the same tenant and agent is allowed.
- Setters whose tokens are discarded grew the state chain without bound. Changes
  that can no longer be reset fold together on the next push.
- A cross-profile install_profile_terminal_scope dropped its env_overlay.
- HX016 flagged a bare 'from . import set_secret_scope', whose module it cannot
  know.
- The TUI heap-trim ordering test observes the whole-profile release.
2026-11-11 09:44:33 -05:00
Ben Barclay
f09f83088a fix(scope): hold scope, home, secrets and terminal policy as one value
Review found three ways around the guards in the first commit: set_terminal_scope
was unguarded (four production callers), set_secret_scope(None) cleared secrets
alone so get_secret fell back to the launch profile, and a stale or out-of-order
reset token moved one piece back while the others stayed. Guards around three
separate context variables leave every unguarded path able to split them.

The four pieces are now one immutable ScopeState in one context variable. Every
setter is a change to that value; a reset removes its own change and replays the
later ones, dropping those made inside a scope the result no longer has, so any
reset sequence lands on a state whole binds produce. Leaving a hosted agent by
any reset other than the bind that entered it refuses.

- set_terminal_scope narrows a bound local scope's own policy; clearing it, or
  setting it in a hosted scope, refuses. set_secret_scope(None) inside a scope
  refuses.
- bind_profile_scope and bind_state refuse a local bind inside a hosted scope.
- The TUI turn holds one token instead of four; housekeeping still runs under
  the session's whole profile scope and the release resets it at once.
- HX016 sees relative imports and no longer flags a local object named like a
  setter's module.
- The historical updater reads the override through get_hermes_home_override
  when hermes_constants no longer exposes the raw context variable.
2026-11-11 09:44:33 -05:00
Ben Barclay
151dc5fc3e feat(scope): one Scope value for home, secrets and terminal policy
Profile state lived in three independent globals (home override, secret
scope, terminal policy) that every entry point set separately, so they could
describe different profiles. 85 call sites set them by hand.

hermes_scope.Scope(tenant, agent, actor) is now the single value, in one
contextvar; actor is Principal(id) or System(reason), and TurnScope adds
session and turn. agent/runtime_scope.py is the one module that turns a scope
into profile state: bind_profile_scope binds and restores all of it together.
The process's own home keeps its launch semantics; any other home is hydrated
from that profile's sources and stamped as routed.

The legacy setters keep their signatures. Inside a bound scope, a call naming
another profile moves the whole scope (local) or raises ScopeSwitchRefused
(hosted). Gateway turns, cron, the TUI, model switch, kanban spawn and the
managed worker bind once at entry. HX016 blocks new direct setter calls;
existing ones migrate when their function is next edited.
2026-11-11 09:44:33 -05:00
alt-glitch
ec7c695d4c feat(dev): just lists the developer commands; lefthook calls its recipes
The justfile held per-workspace eslint recipes that duplicated lefthook and
ran whatever ruff was on PATH. It is now one menu of developer commands:
setup, check, fix, test, the JS workspace checks, the desktop and TUI dev
servers, the website build and the PM re-lock. Each recipe calls an existing
script or tool. Python recipes go through scripts/run-in-hermes-env, so they
work in a shell that never ran `source ./activate`.

`just test` requires at least one path, because scripts/run_tests.sh with no
arguments starts the full suite; `just test-all` is that explicit form.

`python -m scripts.code_health.ruff_runner ARGS` runs the pyproject-pinned ruff
that scripts/check resolves. `just fix` and the pre-commit `just ruff` recipe
use it, so the hook no longer depends on the ruff version on PATH.

lefthook.yml keeps its jobs, globs and roots; each job now runs `just ruff` or
`just eslint`. A shell without `just` on PATH fails the hook with "command not
found" rather than skipping the lint.

CONTRIBUTING.md, the developer guide, the package-management reference and the
desktop and TUI READMEs name the recipes beside the commands they run.
2026-11-09 16:34:44 +05:30
kshitijk4poor
171038d4bc feat(code-health): HX014 ratchet against private API-error predicates
The aux, compressor and turn paths each grew "is this a <kind> error?"
helpers that read an exception's status_code or grep its text; every
copy drifted from classify_api_error until the previous commit moved
the aux decisions onto the shared classifier. HX014 keeps new copies
out.

What it flags: a def or lambda with an exception parameter (exc/err/
error/e/ex/exception, *_err/*_error/*_exc, or an *Exception/*Error
annotation; a ClassifiedError parameter is not one) whose own body reads
<param>.status_code (also via getattr or .response) or probes the
exception's text (`in str(exc)`, a local bound to that text,
startswith/endswith, re.search/match/fullmatch, _contains_any). Scope:
agent/auxiliary*.py, agent/context_compressor*.py, agent/turn_*.py,
tests excluded.

Like the other HX rules it ratchets base vs head, so existing hits are
grandfathered. Waiver: `# health: allow HX014 -- <why>`.

Tests: tests/scripts/test_code_health_error_predicate_rule.py covers
flagged and passing shapes, scope and the base-vs-head verdict.

Part of the Code Health plan.
2026-11-08 13:18:54 +05:30
Maciej Lisiewski
7062229090 chore(js): switch the workspaces from npm to pnpm
pnpm 12.15.0 (native executable) installs every JS workspace from one
pnpm-lock.yaml, imported from package-lock.json with the same resolved
versions. website/, the WhatsApp bridge and the photon sidecar stay separate
npm projects.

Configuration moves from .npmrc and the root manifest into
pnpm-workspace.yaml: the 14-day minimumReleaseAge and its excludes,
overrides, allowBuilds (the old allowScripts set, with strictDepBuilds
failing any unlisted build script), engineStrict, sideEffectsCache: false
(in-place rebuilds must not write into the store) and
verifyDepsBeforeRun: false (a `pnpm run` never installs).

The pnpm version is pinned in pm/lock.json and in root devEngines.
pmOnFail: ignore keeps that pin out of pnpm-lock.yaml: a leading pin
document makes osv-scanner read zero packages. scripts/build/node-deps.mjs
enforces the exact version instead, and every lock reader refuses a
multi-document lock. A root preinstall refuses `npm install`; devEngines
onFail is warn so npx (MCP servers, the tsc linter) keeps working inside
the checkout.

User-machine installs run --frozen-lockfile --trust-lockfile (release age is
checked when locking, in CI, not per user). node-deps removes npm-era
node_modules trees before the first pnpm install. Nix builds the store with
fetchPnpmDeps and a hash file that CI checks.
2026-11-06 04:08:24 +01:00
Teknium
74f77ab9b0 Code health blocks new wall-clock sleeps in tests (HX013), adds a shared wait_until helper (#136644)
* feat(code-health): HX013 blocks new wall-clock sleeps in tests

A fixed time.sleep()/asyncio.sleep() is a bet that the code under test finishes
in time; on a loaded runner it loses and the test flakes. Main has ~1,470 of
them in tests/ and nothing stopped new ones (HX rules exclude tests).

HX013 runs only on test paths (Rule.include) and flags time/asyncio/anyio/trio
sleeps with a delay that is not a literal 0, plus a fresh threading.Event().wait(x).
Existing sleeps are grandfathered by the ratchet's base-relative compare; moved
code keeps its debt; '# health: allow HX013 -- <why>' waives a deliberate delay.

The fix text points at tests/waiting.py (wait_until / async_wait_until), a shared
poll-with-deadline helper replacing the ~60 private copies across the suite.

* fix(code-health): HX013 passes the interval of a poll under a deadline

The frozen replay (PRs merged 2026-10-08..09) hit three private poll helpers
(while not done and monotonic() < end: sleep(x)): that is the compliant shape the
fix text recommends, not a fixed delay. A while loop that reads a clock and can
end on a non-clock condition now exempts its sleep; a loop that only waits out
the clock, or polls with no deadline, still counts. tests/waiting.py needs no
waiver any more; tests/AGENTS.md names the rule and the helper.

* fix(code-health): HX013 passes a round-bounded poll loop

The second frozen window (2026-10-06..07) hit 'for _ in range(200): await
asyncio.sleep(0.01); if idle: return', a poll bounded by its round count: load
stretches it but cannot make it return early. A for-range loop whose body can
leave on a non-clock condition now exempts its sleep; a range loop of fixed
delays, or a poll over arbitrary items, still counts.

* fix(code-health): HX013 exempts only a real poll's own interval

Review fixes for the HX013 poll-loop exemption, plus a file split:

- Split: the HX013 checker moves to scripts/code_health/py_rules_sleep.py,
  and the AST helpers it shares with py_rules (Ctx, _FUNCS, _dotted,
  _call_name, _deferred_parts, _eager) move to a leaf module py_ast.py.
  py_rules.py drops from 1,034 to 877 lines (928 on main); CHECKERS still
  registers HX013.
- Clock-only conditions: only a test operand that reads something other
  than the clock counts as a condition. Combined clock checks
  (`monotonic() < a and monotonic() < b`), `not`/constant operands, and
  locals assigned only from clock arithmetic (`now < end`) no longer
  exempt the sleep. `and`/`or`/`not` follow their logic, so `while not
  done() or monotonic() < end` still waits out the clock.
- Loop ownership: a `break` ends only the loop whose body holds it (a
  nested loop's break does not count for the outer loop; one in the
  nested loop's `else:` does). Nested defs, lambdas and classes are
  skipped. A sleep in a loop's `else:`, `while` test or `for` iterable is
  not that loop's interval.
- Retry polls: a `try` body's return/break counts as conditional when the
  body calls something that can raise (`try: return probe() except
  OSError: sleep`). A body that only sleeps still counts as a fixed delay.

On origin/main this flags 2 more grandfathered sleeps and exempts 12 retry
polls the old rule missed, so the count goes from 923 to 913.
2026-10-11 11:27:22 -07:00
Maciej Lisiewski
4ee5e8e0f3 ci: RUF007 2026-10-08 21:35:58 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
6cc7d4a570 fix(code-health): TS recursive rename ignores nested-scope bindings
bodyWithoutSelf treated a declaration of the function's name at any depth as a rebind,
so a renamed recursive function containing an unchanged `.map((legacy) => legacy)` kept
its old self-call text, no longer matched its base body, and lost its cap ("CC 22 >
target 20 (new code)"). Only the function's own scope (parameters, a named function
expression's name, declarations outside nested functions and classes) now stops the
normalization, and nested functions that bind the name keep their own reads, as the
Python measurer already does.
2026-10-04 22:35:16 -07:00
Teknium
16fba82ce3 fix(code-health): global/nonlocal no longer hide an import alias
_Binder.visit_Global marked the name ambiguous in the module, so `global execute` in a
function hid `from subprocess import run as execute` and HX006 (missing timeout) never
fired on `execute(cmd)`; nonlocal did the same for an enclosing function's import. A
declaration selects the outer binding, it does not rebind it: declared names now resolve
in the scope they point at, and only an assignment (or import) through the declaration
rebinds that outer name.
2026-10-04 22:35:16 -07:00
Teknium
791dc63c05 fix(code-health): CRLF blobs measure like LF on Windows
Measurer.measure wrote each blob's decoded text into the temp tree with write_text's
default newline translation. On Windows that turns a CRLF blob into CR CR LF, so ruff
counted lines differently from the AST and comment tables: hits moved to <module>,
their `# health: allow` waivers were missed, and valid code blocked. Writing with
newline="" keeps the blob's own line endings. The test forces the Windows write
translation so it also runs on Linux.
2026-10-04 22:35:16 -07:00
Teknium
0017264c02 fix(code-health): replay stops counting unmeasured PRs as clean
A manifest row whose range could not be built (base "", head "error: ...") or replayed
(an OID the clone does not have) was counted in the "N of M PRs had a blocking finding"
denominator with no findings, and the run exited 0, so a replay that measured nothing
read as evidence that a rule never fires. Such rows now carry an "error" in replay.jsonl,
stay out of the totals and the denominator, are listed by number, and fail the run.
2026-10-04 22:35:16 -07:00
Teknium
df81f543f8 fix(code-health): oversized-file fix text names the cheap way to comply
Files past 2,000 lines stay strictly no-growth (tests included). The message now says how
to offset growth in the same PR: move an existing function into a topical sibling (moved
code keeps its cap) or put new tests in a new test file. Probed on a 2,128-line file: plain
growth blocks; the same growth plus moving a CC-22 function out passes; a new test file
passes; growing the old test file blocks.
2026-10-04 21:29:39 -07:00
Teknium
00361a69ce fix(code-health): read replay manifests BOM-tolerantly 2026-10-04 21:29:39 -07:00
Teknium
baa07694a8 feat(code-health): heuristic rules warn until a frozen replay shows precision
HX001, HX003, HX010, HX012 and PS-P05/P06 now print as advisory findings instead of
blocking. Reviewers' samples put them between ~12% and ~60% precision, and the plan
ships weak rules as warnings first. Promote one by flipping it to blocking with replay
evidence in the PR. The ENFORCEMENT comment now says where the switch is read from.
Tests that used PS-P05 as a stand-in blocking violation now use a blind except.
2026-10-04 21:29:39 -07:00
Teknium
fccb46ac48 fix(code-health): measure every Python unit's real end line
compare.py's cross-file move matching slices the origin function by its end line;
without it the engine estimated the end from the line count. Pass ast's end_lineno through.
2026-10-04 21:29:39 -07:00
Teknium
7ceedd731a style(code-health): wrap the long lines added by the lane-C fixes
No behaviour change: line wrapping in the hook text, parse_switch docstring,
commit_or_none and the new tests; the test helpers lose an unused env parameter.
2026-10-04 21:29:39 -07:00
Teknium
a6274687fd fix(code-health): parse ENFORCEMENT with ast and read it from the main tip locally
unsupportedpastels m3: (a) the switch was found by a regex that accepted only the
exact `ENFORCEMENT = "..."` spelling, so `ENFORCEMENT: str = "off"` silently stayed
blocking; (b) local runs and both hooks read it from the merge-base with
origin/main, so a flip on main reached a branch only after a rebase, contrary to
"CI and local hooks alike".

(a) parse_switch() reads the module-level plain or annotated assignment with ast
(last one wins, as at runtime); missing, unparseable or unknown values are
blocking. (b) Without --base, the base is still the merge-base of the head (a
--head commit, else HEAD) but the switch comes from origin/main when it resolves,
falling back to the base. An explicit --base pins both (CI passes HEAD^1, the
target tip). scripts/check --commit now hands the commit itself to the ratchet so
it derives that commit's merge-base. The head under test never supplies the switch.
(c) A test pins enforcement() on this tree to config.ENFORCEMENT.
2026-10-04 21:29:39 -07:00
Teknium
b76c3facdf fix(code-health): profile regex rules match executable code, not prose
F21 (andrexibiza): PS-P05/PS-P06 ran their regexes over raw source lines, so a
comment such as `# Avoid env = os.environ.copy(); use the scoped builder.`, the same
sentence in a docstring, or a comment warning against `os.getenv("DISCORD_TOKEN")`
produced a blocking hit although nothing builds an env or reads a credential.

Before the regexes run, comment tokens (tokenize) and string statements (ast:
docstrings and bare string examples) are blanked in place, preserving every line
number and line break. Ordinary string literals inside code are kept, so the
env-key argument of `os.getenv("DISCORD_TOKEN")` still matches; the real
`env = os.environ.copy()` / `dict(os.environ)` / platform getenv stay flagged. If
tokenizing fails, the raw lines are used (more hits, never fewer).
2026-10-04 21:29:39 -07:00
Teknium
7ef5f0e1f9 fix(code-health): an allow comment may separate its rules with spaces
banditburai (inline report.py:36): `# health: allow BLE001 S110 -- boundary` waived
neither rule and reported "allow comment ignored: it needs a reason", although the
reason is there. _ALLOW accepts spaces in the rule list, but apply_allows split it
on commas only, so "BLE001 S110" was looked up as one rule name.

The rule list is now split on commas and whitespace, so `BLE001 S110`,
`BLE001, S110` and `BLE001,S110` all waive both rules. A reason is still required.
2026-10-04 21:29:39 -07:00
Teknium
f970c226f3 fix(code-health): a failing measurement tool exits 2, not with a traceback
unsupportedpastels m5: when the pinned TypeScript is not cached, ts_measure runs
`npm install`; a failed or timed-out install raised CalledProcessError /
TimeoutExpired, which cli.main did not catch (it caught RuntimeError only). The run
then died with a traceback and exit 1, which reads like a finding.

cli.main now reports those as a broken run: one `code health: measurement tooling
failed: ...` line on stderr and exit 2, like every other environment error.
2026-10-04 21:29:39 -07:00
Teknium
15274dfb41 fix(code-health): --json prints JSON on every return path
JoaoMarcos44 (inline cli.py:64): the ENFORCEMENT="off" and "no measured files
changed" branches returned before the --json formatter, so
`python -m scripts.code_health --base HEAD --head HEAD --json` succeeded with prose
on stdout and json.loads() raised.

Both early successes now print the empty findings list `[]` on stdout and move
the human explanation to stderr; findings and zero-finding measured diffs were
already JSON. Exit codes are unchanged on all four paths.
2026-10-04 21:29:39 -07:00
Teknium
6b4deabadb fix(code-health): bound the cost of same-name pairing
Why (cost, same concern as Adolanium's line-matching note): pairing repeated names by body is
all-pairs within a group, and the per-group lookup of base units scanned the whole base file,
so a codemod touching every function of a big file was quadratic (5,000 edited unique names:
5.4 s -> 0.04 s with a per-file name index). A group whose all-pairs check would exceed
250,000 pairs (e.g. hundreds of edited `it(...)` callbacks in one scope) falls back to the
ordinal pairing, which is bounded; measured 2,000-callback group: 0.05 s.
2026-10-04 21:29:39 -07:00
Teknium
ae59e08534 fix(code-health): hits in a function moved and edited are placed by its origin's lines
Why (M2 follow-up; invariant 4, no trading): the previous commit let a moved+edited unit's
new-looking hits spend any departed occurrence of its origin unit by line text, so a swallow
dropped at the top of `legacy` paid for one added at the bottom of the moved copy (exit 0;
red on the previous commit), while the same relocation in place blocks. A unit matched
across files (pass 5) now compares its lines with its origin unit's (SequenceMatcher, code
only), exactly like an edit in place: hits on unchanged lines are old, the rest are new.
The departed-occurrence pool is now module-level only.
2026-10-04 21:29:39 -07:00
Teknium
fe6b559d11 fix(code-health): a module-level hit moves only with its whole statement
Why (M1 follow-up; invariant 4, no trading): matching a departed module-level occurrence by
its line alone let `except Exception:` stand for any guard, so deleting
`try: import json / except Exception: pass` from one file paid for a new
`try: import yaml / except Exception: pass` in another (exit 0; red on the previous commit).
A module-level occurrence now moves only with its whole top-level statement unchanged
(found by indentation: a whole try/except block, or a one-line constant). Moving an unchanged
HX005 module constant to another file passes; a different constant still blocks.
Hits inside a unit matched across files keep line matching: only that unit's own departed
occurrences can pay.
2026-10-04 21:29:39 -07:00
Teknium
e5a6b1f746 fix(code-health): pair repeated names by body; keep the cap of a function moved and edited
Why:
- banditburai (inline, py_structure.py:97) and unsupportedpastels M3: repeated names (Python
  `@method(...) def _`, `f#2`; TS `<anon>#n`) were paired by source-order ordinal, so a new
  CC-22 `_` inserted above a trimmed one took its cap (exit 0), and inserting a small `_`
  above an unchanged CC-22 one made the old one "new" (exit 1). Same-file name matching now
  groups units by name without the ordinal and pairs the most similar bodies first
  (difflib ratio >= 0.6 over code lines, comments/whitespace dropped); the last unit left
  with a name is that name's unit, exactly as a unique name was before. Exact-hash passes
  still run first. If a body span is unknown, the group falls back to the ordinal.
- unsupportedpastels M2: cross-file matching was body-hash only, so a function moved to
  another file with one constant changed lost its cap (P1 exit 1; same edit in place exit 0).
  New last pass: another file, same name, similar body (>= 0.6), only when the name is gone
  from its origin file and exactly one unit of that name left and exactly one arrived
  unmatched. A copy (origin keeps it), two arrivals, or an unrelated body reusing a deleted
  name stay new code (andrexibiza: never arbitrary same-name credit). Its existing hits
  follow it through the departed-occurrence pool (one-to-one), a second swallow is new.
Unit gains an optional end_line; until the measurers report it (py_structure: lane A,
measure.py: lane C) the span is estimated from the unit's own FUNC_LINES. Tests pass both ways.
2026-10-04 21:29:39 -07:00
Teknium
35951f8fa4 fix(code-health): module-level hits follow code moved to another file; skip idle line matching
Why (round-5 review, unsupportedpastels M1; Adolanium cost note):
- M1: code outside any unit is not a unit, so its hits could survive only through the line
  diff of a file against its own base (or git-detected rename). Moving an unchanged
  module-level `try/except Exception: pass` into pkg/a_compat.py reported S110 + BLE001 as new
  (exit 1). Now a base occurrence whose line LEFT its file may pay, once, for an identical
  occurrence (same rule, same normalized code) arriving in another file in the same diff, at
  module level or inside the unit its own unit was matched to. One-to-one: the spent
  occurrence no longer counts as credit at its origin. A copy (origin line survives) still
  blocks; two arrivals for one departure block; a re-add in the same file stays new; a
  module-level hit never pays for one inside a function.
- Adolanium §3: SequenceMatcher ran for every changed file, TS included (1.66 s on desktop
  main.ts for a one-line change); line matching is now skipped when neither side has hits.
2026-10-04 21:29:39 -07:00
Teknium
142bcd133d fix(code-health): TypeScript install honours the repo .npmrc; npm failures exit 2
Why (round-5 review, unsupportedpastels m5, D4): `npm install --prefix <cache>` makes the
cache dir the npm project, so the repo's .npmrc (min-release-age=14) was ignored: `npm config
get min-release-age` from the prefix was undefined. The repo .npmrc is now copied into the
prefix before installing (verified: `npm config get min-release-age --prefix <cache>` -> 14).
A failed or hung install raised CalledProcessError/TimeoutExpired, which cli.main does not
catch, so the run exited 1 with a traceback that read like a finding; both now raise
RuntimeError with npm's stderr, which cli.main maps to exit 2.
2026-10-04 21:29:39 -07:00
Teknium
cf7dc01a37 fix(code-health): TypeScript identity by object, token hash, fail closed on syntax errors
Why (round-5 review, unsupportedpastels M3/m1/m6 + §3; Adolanium, helix4u):
- M3: methods of object literals were named `f`, `f#2` and paired by position, so swapping
  two objects gave b.f a.f's cap of 31 (V9a). They are now named by the variable/property
  that holds the object (`a.f`, `b.f`). Overload signatures (and `declare`/abstract
  signatures) have no body and are no longer units, so adding an overload no longer shifts
  the implementation to `old#4` and makes it new code (V10a).
- m1: the body hash covered raw text, comments included, so rename + one comment line was new
  code in TS (not in Python). It now hashes the parser's token stream (no comments, no
  whitespace, no JSDoc), collected once per file.
- §3 (Adolanium, helix4u): `export function f(x: number {` exited 0 because the parser
  recovers and sf.parseDiagnostics was never read. A file with parse diagnostics is now an
  error -> MEASURE (fails closed), like unparseable Python. No tracked TS file in the tree
  has parse diagnostics (4191 files checked).
- m6: the header documents exactly where the CC count deviates from ESLint's complexity
  (optional chaining, &&=/||=/??=, default parameters are not counted).
Units also carry their end line (`end`), for body-similarity pairing.
2026-10-04 21:29:39 -07:00
Teknium
8a0e27697c fix(code-health): a parameter annotated as a process is an HX006 handle
Follow-up to the per-scope handle tracking (Adolanium §4): a repo-wide sweep
of the old vs new engine showed one lost hit,
tui_gateway/host_supervisor.py `_wait_for_exit(self, proc:
subprocess.Popen[str])` -> `proc.wait()`. The old module-wide map flagged it
only because another function happened to bind `proc` to a Popen; scoping
correctly treats a parameter as unknown, which also drops the case where the
type says exactly what it is.

A parameter annotated `subprocess.Popen[...]` (sync) or
`asyncio.subprocess.Process` (async) now starts as a handle of that kind;
unannotated parameters still clear the name.
2026-10-04 21:29:39 -07:00
Teknium
66cd3efacc fix(code-health): fix texts for HX010, HX001 and BLE001 say what is accepted
unsupportedpastels M4 (review 5408300628 §2.3) and m7: the printed fixes would
break code or did not match the engine.

- HX010 led with `is_truthy_value`, which returns False for every real key,
  while most hits are "is it set" checks (`bool(os.getenv("..._API_KEY"))`).
  It now offers `is not None` / `!= ""` for presence and `is_truthy_value`
  only for boolean flags.
- HX001 only said `get_hermes_home()`, which would move a path that lives
  under the user's home on purpose (the profiles root); such a path takes an
  allow with a reason.
- BLE001: the ratchet runs ruff with --ignore-noqa, so `# noqa: BLE001`
  waives nothing, and a message-only `logger.warning(..., e)` still fails.
  Verified with pinned ruff 0.15.10 through the real comparison path
  (test_ble001_fix_text_matches_the_engine): logger.exception, any log call
  with exc_info=True, and re-raise pass; `% e` logging and `# noqa` block;
  `# health: allow BLE001 -- why` waives.

Text only: no rule's blocking flag or ENFORCEMENT changed.
2026-10-04 21:29:39 -07:00
Teknium
b1b1f0694c fix(code-health): HX001/HX003/HX012 stop rejecting correct code (M4)
unsupportedpastels M4 (review 5408300628 §2.3), each fixture a new file that
exited 1 at 96bb97a:

- HX001 matched any name starting with ".hermes", so
  `Path.home() / ".hermes-profile-exports"` (hermes_cli/profiles.py) was a
  "hardcoded Hermes home". It now matches only the exact `.hermes` path
  component (`.hermes`, `.hermes/x`, `~/.hermes/...`).
- HX003 matched every string containing `ps aux` / `pgrep -f`, including
  docstrings that explain why not to use them. Expr-statement string
  constants (docstrings, bare string statements) are prose and skipped; real
  command strings, assignments and f-string parts stay flagged.
- HX012 flagged `threading.Thread(target=copy_context().run, ...)`, the
  context-preserving form the plan lists as a fix (agent/auxiliary_client.py
  uses it). A target of `<ctx>.run` is accepted when ctx is
  `contextvars.copy_context()` itself or a name this same scope binds only to
  `copy_context()` (keyword or positional target). A ctx from another scope,
  a rebound name, or any other target stays flagged.
2026-10-04 21:29:39 -07:00
Teknium
6ca1395ee0 fix(code-health): NESTING counts else: + indented if as nesting
JoaoMarcos44 (inline py_structure.py:49, review 5408439923; reproduced by
andrexibiza): nesting_depth() treated any If that sits alone in an orelse as
an `elif`, but `else:\n    if b:` produces the same AST. Seven physical
`else: if` levels measured 1 (adding an inert `pass` made them measure 7), so
the gate depended on an irrelevant statement rather than on indentation.

A real `elif` If node starts at the `elif` keyword, i.e. at its `if`'s
column; an `if` nested under `else:` must be indented deeper (a compound
statement cannot follow `else:` on the same line). Only the former keeps the
depth. Seven physical levels now measure 7 with or without the inert pass
and block; a genuine seven-arm elif chain stays at 1 and passes.
2026-10-04 21:29:39 -07:00
Teknium
ae60f7ccc1 fix(code-health): recursive-rename normalization honours nested scopes (F15)
andrexibiza's F15 (changed form, inline on py_rules.py:250): body_hash()
disabled self-reference normalization whenever the textual dump contained
`arg('<name>'` or `Name('<name>', Store())` anywhere in the subtree, so an
unrelated nested `def identity(legacy)` made a pure recursive rename of
`legacy` lose its cap (FUNC_LINES 302 > target 300 as new code). Even with
the check removed, the string replace would also have blanked the nested
function's own `return legacy`, which refers to its parameter.

References are now resolved lexically: only bindings in the function's own
scope (params, assignments, nested def/class names, imports, global/nonlocal,
except/match captures) disable normalization, and a nested def/lambda/class/
comprehension that binds the name keeps its own reads. The matched Name /
Attribute nodes are blanked in place for the dump and restored. Controls: a
rename that leaves the old self-call is different code, an own-scope rebinding
is not a self-reference, a closure's call to its enclosing function is.
2026-10-04 21:29:39 -07:00