[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7593EK1TXAEKXBS2BAW7T6R":3,"skill-same:01M7593EK1TXAEKXBS2BAW7T6R":78},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":43,"commitSha":44,"skillDirectory":45,"forksCount":46,"repositoryHtmlUrl":47,"repositoryHomepageUrl":48,"ownerHtmlUrl":49,"ownerBlogUrl":6,"ownerDescription":50,"updatedAt":51,"install":52,"resources":65},"01M7593EK1TXAEKXBS2BAW7T6R","hermetic-python-testing",null,"Write Python modules with hermetic unit-test seams. Covers sandboxed inputs AND live-side-effect output defaults (telegram\u002Fwebhook\u002Fmail routes).","lukemcqueen\u002Fsteadfaste-fleet","lukemcqueen","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F405240?v=4","01M757MHPAGRXTJAT46SKZP98R","Luke McQueen","01M757MHPZ573KP8DT9GB8SBQ7",4,"MIT","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fhermetic-python-testing\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: hermetic-python-testing\ndescription: \"Write Python modules with hermetic unit-test seams. Covers sandboxed inputs AND live-side-effect output defaults (telegram\u002Fwebhook\u002Fmail routes).\"\nversion: 1.0.0\ncategory: software-development\nauthor: Steadfaste Fleet\nlicense: MIT\nplatforms: [linux, macos]\nmetadata:\n  hermes:\n    tags: [testing, python, isolation, hermetic, unit-test, seams]\n    related_skills: [test-driven-development, codebase-design, survey-before-action]\n---\n\n# Hermetic Python Testing\n\nWrite Python modules so their unit tests never touch real state, real\ncredentials, or real network — and prove it. Born from telegram_notify S2\n(2026-08-08): tests silently wrote to `~\u002F.steadfaste-fleet\u002Fstate\u002F` and read the\nreal `~\u002F.hermes\u002F.env` until the module was restructured.\n\n## When to Use\n\n- Writing a new Python module that reads env vars, paths, or config files\n- Adding L0 unit tests to a module that touches files, state, or network\n- A test \"passes\" but you suspect it hit real resources (check the module's\n  log\u002Fstate files for unexpected entries)\n- Refactoring a module to be testable without mocking the whole world\n\n## Core Rules\n\n### 1. Resolve paths LAZILY, never at import time\n\n```python\n# ❌ BAD — frozen at import; tests setting the env var after import hit REAL paths\nSTATE_FILE = Path(os.environ.get(\"MY_STATE_DIR\", Path.home() \u002F \".x\")) \u002F \"state.json\"\n\n# ✅ GOOD — resolved per call; tests point it at tmp_path via monkeypatch.setenv\ndef _state_file() -> Path:\n    return Path(os.environ.get(\"MY_STATE_DIR\", Path.home() \u002F \".x\")) \u002F \"state.json\"\n```\n\nImport-time constants freeze the path for the whole process. Tests that set\nenv vars AFTER import (the standard `monkeypatch.setenv` pattern) silently\nread\u002Fwrite the real location. Symptom to watch for: a module's real log file\nor state JSON appears in `~\u002F.steadfaste-fleet\u002Fstate\u002F` after a test run.\n\n### 2. Expose seams for clock and send, then monkeypatch them\n\n```python\ndef _now() -> float: return time.time()\ndef _sleep(s: float) -> None: time.sleep(s)\ndef _send_once(token, chat_id, text): ...   # the network boundary\n```\n\nTests patch these module attributes:\n```python\nwith patch.object(tn, \"_now\", side_effect=fake_now), \\\n     patch.object(tn, \"_send_once\", side_effect=fake_send):\n    ...\n```\nThis tests coalescing windows, retry budgets, and backoff with a fake clock\nand zero network.\n\n### 3. Hermetic fixture setup — state dir AND env file, both in tmp\n\nEvery test that exercises the module gets its own tmp state dir and a fake\nenv file:\n\n```python\ndef _setup(tmp_path, monkeypatch, chat=\"111222333\", quiet=\"\", mute=\"\"):\n    state_dir = tmp_path \u002F \"state\"; state_dir.mkdir(exist_ok=True)\n    env_file = tmp_path \u002F \"env\"\n    env_file.write_text(f\"TELEGRAM_BOT_TOKEN=123456:TESTTOKEN\\nTELEGRAM_HOME_CHANNEL={chat}\\n\")\n    monkeypatch.setenv(\"MY_STATE_DIR\", str(state_dir))\n    monkeypatch.setenv(\"MY_ENV_FILE\", str(env_file))\n    return state_dir, env_file\n```\n\n### 4. Verify the hermeticity — never trust \"tests passed\"\n\nAfter the suite is green, confirm no real resources were touched:\n- The module's real state\u002Flog\u002Flock files must NOT exist afterward\n- No real credentials were read (check for side effects like real sends)\n- Grep the test file for real identifiers (chat ids, tokens, hostnames,\n  `\u002Fhome\u002F\u003Cuser>\u002F` paths) — placeholder values only\n\n### 5. Override live-side-effect defaults EXPLICITLY — sandboxed inputs are not hermeticity\n\nA test that feeds tmp_path INPUTS can still act on the real world if the tool\nunder test has a default OUTPUT route. Proven 2026-09-30: the bridge-runner\ntest ran `fleet-bus-bridge-run.py` on a tmp echo.py without `--deliver` — the\nrunner's default is Telegram, so every test run sent `cron:test-echo \u002F hello\nfrom test` to the user's real chat (repeated complaints: \"I keep seeing\nthis\"). Before invoking any tool\u002FCLI in a test, grep its args\u002Fenv for defaults\nthat route to a real channel (messenger, webhook, mail, metrics) and pass the\nexplicit safe target (`--deliver local`, `FLEET_DEPLOY_HOME=tmp_path`).\nAssert the live default in a dedicated test — never exercise it by accident.\n\n**Prefer a SUITE-LEVEL kill-switch over per-call flags.** Passing the safe\ntarget into the test you happen to be writing does not protect the suite: the\nnext test someone adds calls the same function with the same dangerous default,\nand the live channel fires again. Put an autouse SESSION fixture in\n`conftest.py` that redirects the module's config away from production for the\nwhole process — point its env-file at a path that does not exist and clear the\ndestination chat\u002Fwebhook variable. The fail-safe direction is \"no credential →\nskip\", never \"no credential → guess\". Tests that genuinely exercise the send\npath set their own values back via `monkeypatch`, so the guard costs them\nnothing.\n\n**Mocking the write does NOT mock the notify.** A post-commit side effect sits\nAFTER the call you patched: a unit test that mocks the DB layer and asserts the\nstored value still runs the notification that write triggers. Verified: a test\nproving a shell payload is stored as a literal — mocking only the query layer —\nalso sent a real message on every run, which surfaced as recurring user noise\n(\"I keep seeing this\") that could never resolve because each run minted a fresh\nid. When you mock a dependency, read the function you are calling through to the\nEND and list every external effect that follows the mocked call.\n\n**A guard needs a control proving the GUARD did the work.** \"notify returned\nFalse\" also passes if the module is simply broken. Pair it: assert the send path\nrefuses under the suite's environment, AND assert that with a valid env file the\nsame probe DOES resolve its credential (a read-only call — no send). Without the\nsecond half, the first half proves nothing.\n\n**A tool you invoke may detect its SUBJECT on the inherited PATH.** When the\ncode under test shells out and probes for a binary (`command -v \u003Ctool>`), passing\nthe ambient `PATH` through means the case asserting \"tool not installed\" can be\nsatisfied by the runner's own install: the audited host is no longer the only\nsource of truth, the assertion flips per machine, and the failure names nothing\nuseful (\"expected exit 1, got 0\"). Scrub the PATH for every case — drop each\ndirectory that actually contains the binary — and put the detected route in the\nfailure DETAIL (`tool_on_PATH=\u003Cwhich(...)>`, `home_tool=\u003Cexists>`), so the next\nred run says which route the tool took instead of only the exit code.\n\n### 6. An imported module must not mutate `os.environ` at import\n\nLoading a module is not a side-effect-free act. A module that parses an env\nfile into `os.environ` at MODULE scope poisons the whole pytest process for\nevery suite that runs after it. Verified 2026-10-01: a deploy script\nexported the canonical env file at import; a metrics suite `exec_module`d it,\nso a var added to that file that day leaked into the process env and the\nnotify suite — which resolves its chat id from `os.environ` FIRST — used the\nreal value and failed only in the full run.\n\nTwo rules follow:\n\n- **The module:** keep env-file parsing in a function called from `main()`\n  (`_source_env_overrides()`), never at module scope. Prove it: `exec_module`\n  the file and assert no var appeared.\n- **The test:** if the code under test reads a process-env var BEFORE its\n  fixture file, `monkeypatch.delenv` that var in the fixture. A fixture that\n  only points its own env file cannot defend against a leaked process value.\n\n### 7. An imported module's LOGGER writes to real state\n\nLoading a module runs its module-level logging setup. A module that attaches a file\nhandler at import (a `RotatingFileHandler` over a real log directory) means every\ntest that imports it APPENDS to that production log, and the entries are\nindistinguishable from real ones — a fabricated cycle number or a `(test)` error line\nlands in the audit trail a reviewer will later read as history. Same family as rule 6:\nimport is not a side-effect-free act.\n\n- **Silence by LEVEL, and leave the handler attached.** Setting the logger above\n  CRITICAL suppresses records. Clearing handlers is stronger but destroys the seam you\n  need to prove the silencing works, and a module that re-attaches handlers later\n  defeats the clear.\n- **Prove the \"it did not write\" assertion is not vacuous.** An assertion that a real\n  file did not grow also passes when the code could never have written to it — e.g.\n  the module resolves its log path from a constant the test redirected. Check both\n  directions, and make the control write NOTHING (writing to prove a file is not\n  written to is self-defeating): first assert the logger carries a handler BOUND to\n  the real target (a `FileHandler`'s `baseFilename`), then detach it, restore the\n  level with a counting handler attached, and assert records ARE emitted — so there\n  was something to suppress — then re-attach and assert the silenced run contributes no\n  FABRICATED line. If the control cannot emit, the test is measuring nothing.\n- **Assert the \"did not write\" property by CONTENT, never by file SIZE.** A byte-equality\n  check on a shared log is racy: any concurrent writer — a cron, a deploy, another\n  agent — appending a legitimate entry during the measurement window fails a test about\n  YOUR code, i.e. a false report of the very thing the test claims to measure. Read the\n  bytes appended in the window and assert none of them carries the test's own markers\n  (its fabricated ids, its session name, its `(test)` strings); if something else wrote\n  meanwhile, report that as non-test growth instead of failing on it.\n- **Know what the module binds at IMPORT vs what you patch afterwards.** A handler\n  built at import keeps the real path even after the test patches the module's HOME; a\n  path resolved per call follows the patch. Assert what is actually bound before\n  trusting either result — a passing one-way size check is a claim about your probe,\n  not about the artifact.\n\n### 8. Once-only initialization must be keyed to the RESOURCE, not to the process\n\nA module-level \"already done\" flag (`_SCHEMA_DONE = False`) makes the FIRST\nresource a process touches the only one that ever gets set up. Any caller that\nswitches resources later — a test repointing the module constant at a tmp file,\na tool opening a second database — receives an un-set-up resource and fails on\nthe first query against it (`no such table: \u003Cname>`). The failure reads as\nflakiness: those tests pass in isolation and fail in a full run, because some\nother test has already opened the first resource.\n\n- **Key the guard to the thing that varies** — the database FILE, the directory\n  being prepared, the fixture identity — a SET of resources rather than a\n  boolean.\n- **Read the key from the connection\u002Fhandle under test, not from the module\n  constant.** The caller may have repointed the constant after the connection was\n  opened, and the question the guard actually answers is \"does THIS resource have\n  its setup\" (`PRAGMA database_list` gives the file a sqlite connection is\n  attached to).\n- **This is a SEAM, not just a test fix.** The process-global flag is untestable\n  by construction: no fixture can prove setup happened for the second resource\n  while the code can only ever answer for the first. Fix the module, then pin it\n  with a test that opens two resources in one process — and a premise test so the\n  guard cannot pass vacuously if the DDL entry point moves.\n- **When the repo's own suite is red, test the claim that it is not your fault.**\n  Re-run the full suite with no lock and no in-flight change and compare the\n  failure LIST, not the count: identical list = pre-existing, and \"passes in\n  isolation, fails in the full run\" points at module state, not at you.\n\n### 9. The caller's environment can change WHICH tests exist — not just what they read\n\nRule 6's family, one level up. An inherited `PYTHONPATH` or `PYTHONHOME` that points at a\nforeign `site-packages` makes some test modules fail to IMPORT, and pytest then reports a\nsmaller suite as a clean run. Measured on one host, same command, only the environment\ndiffering: **1818 collected with 4 collection errors** contaminated vs **1846 with none**\nclean — four whole modules dropped, and the runner printed `N passed` either way. An agent\nshell almost always exports `PYTHONPATH`, so the contaminated case is the DEFAULT case.\n\n- **Run the suite through a wrapper that CLEANSES the environment and resolves the\n  interpreter by CAPABILITY** (never by `PATH` or a bare `python3`): `env -u PYTHONPATH -u\n  PYTHONHOME \"$PY\" -m pytest …`. Copyable shape: `templates\u002Frun-tests.sh`.\n- **The wrapper must not REQUIRE a fleet install.** A repo whose host has no resolver and no fleet\n  venv still needs to run its own suite: probe `python3`\u002F`python` on `PATH` by CAPABILITY (still an\n  import test, never a bare path), ANNOUNCE that you fell back and why, and still exit 3 when nothing\n  can import pytest. A silent fallback is worse than none — it swaps which code decides the interpreter\n  while the run looks identical, and it can make a stub test exercise the real thing and \"pass\".\n- **Pin the wrapper's portability, not only its behaviour.** A source scan asserting no bash-4-only or\n  BSD-hostile construct (the list lives in `shell-scripting`), plus a run of the REAL wrapper in a\n  constructed environment (temp repo, empty HOME, stubbed PATH) for the branches your host cannot\n  reach. Same for the guard's numbers: assert \"more than zero collected\", never a count that is only\n  true of one repo — a shared guard that encodes this repo's size fails a healthy smaller repo.\n- **Guard collection, not just results.** A test that runs the suite's collection in a\n  subprocess and FAILS on `N errors during collection` — while also asserting a non-trivial\n  collected count, so “0 collected” cannot read as clean — is what stops a dropped module\n  from being reported behind a green total. A green run that tests less than it claims is\n  worse than a red one.\n- **A collection error is not a missing dependency.** `ModuleNotFoundError` naming a\n  SUBMODULE of an installed package (`pydantic_core._pydantic_core`) is an ABI mismatch from\n  a shadowed `site-packages`, not something to `pip install`: fix the environment, not the\n  package list, and never record it as “dependency X is broken”.\n- **Check the runner's own default before blaming a test.** pytest with FLAGS but no PATH\n  collects the whole current directory — in a repo that means `.git`, deploy trees and the\n  venv, and it hangs. Always supply a path.\n\n### 10. A module-level ENTRYPOINT makes a script un-importable — and the importer cannot defend itself\n\nRules 6 and 7 are about a module's side effects at import; this is that family one step further:\nthe module's whole JOB runs at module scope. `count = purge()` + `sys.exit(0)` at the bottom of a\nscript means importing it to exercise its shipped logic fires the work against the LIVE resource,\nand the importer cannot prevent it — repointing the module's path constant after `exec_module` is\nalready too late. Observed: a probe importing a purge script removed 780 files from the live state\ndirectory before it could repoint anything. The importer is then left reporting a side effect it\ncaused while measuring something else.\n\n- **Fix the MODULE, not the importer:** `def main() -> int: ...` plus\n  `if __name__ == \"__main__\": sys.exit(main())`. Import becomes inert; only running the file has\n  effects — and the function stays drivable with its path constant repointed.\n- **Check BEFORE importing a file you do not own.** Read the end of the file (or `ast`-walk its\n  module body) for a bare call, a `print`, or `sys.exit` outside a def or the `__main__` guard.\n  If one is there, fix the guard first — do not import it \"just to see\".\n- **Prove the guard in THREE directions**, because \"it did not purge\" also passes when the function\n  is simply broken: (a) with the home directory patched into a temp tree, importing leaves the\n  stale fixture untouched AND the module's path constant really resolves into that temp tree —\n  without that second half, (a) asserts only that the probe aimed somewhere harmless; (b) calling\n  the function DOES remove the fixture; (c) running the file as a SUBPROCESS with `HOME` redirected\n  removes it and reports — the real cron\u002Fsystemd path, which an import test never exercises.\n- **Pin the shape source-level too:** walk the module body with `ast` and assert every top-level\n  statement is an import, an assignment, a def, or the `__main__` guard, so a future edit cannot\n  quietly reintroduce the side effect.\n\n### 11. An end-to-end test drives the REAL path — and must not depend on the DEPLOYED tree\n\nThis user's standard for a non-trivial change is comprehensive unit tests PLUS one end-to-end run\nof the real system path (real argv in, real exit status out), which is the seam that catches what\nunit seams cannot. Two rules keep that test honest and durable:\n\n- **Redirect the deploy\u002Finstall ROOT at a fixture; never let the test read the host's deployed\n  state.** A command that resolves a collaborator from a deploy root (a CLI whose module is copied\n  under the deploy home, a doctor that drives it) passes locally and goes RED on every fresh\n  checkout, because the deployed copy is only current after a deploy — and the first failure a\n  reader meets is the suite, not the change, which is how a suite becomes something people ignore.\n  Point the root variable at `tmp_path` (env\u002Fmonkeypatch: `FLEET_DEPLOY_HOME=\u003Ctmp>`), so the test\n  exercises the repo's own copy and measures the CHECK and the CLI it drives. Then verify the\n  DEPLOYED wiring by RUNNING it in the cycle that changes it (a real invocation against the deployed\n  path, recorded in the committed evidence) — deployment state is verified live, not asserted in a\n  test. Note the consequence for assertions about the run: the exit code then reflects EVERY check\n  the command performs (a pre-deploy tree fails unrelated deploy-sync checks), so assert the\n  property you own (`rc` is a usage-clean code, the JSON parses) and say in a comment why an exact\n  0 would turn the test into a probe of the host.\n- **Build the fixture from the collaborator's REAL output, not from your reading of it.** When the\n  fixture stands in for another tool's machine-readable input (a `--json` inventory, a manifest, a\n  config the code parses), generate it by RUNNING that tool against a fixture directory with its own\n  input path redirected — a hand-written fixture pins your guess at the shape, so it keeps passing\n  after the real output changes and fails only when the guess was wrong. That is the difference from\n  rule 5: the collaborator runs for real, on fixture inputs.\n\n### 12. Real-git test fixtures must sandbox their OWN hooks — the host's global `core.hooksPath` runs inside them\n\nA test that creates a real git repo in `tmp_path` inherits the host's GLOBAL\n`core.hooksPath`. On a governed host that points it at the fleet hooks\n(`~\u002F.steadfaste-fleet\u002Fhooks`), the fleet pre-commit hook runs INSIDE the\nthrowaway repo and refuses the fixture's bare commits (no pathspec) with a\nnon-zero exit. When the fixture's commit helper swallows the return code (the\nstandard `subprocess.run([...]).stdout` pattern), the repo silently stays\nEMPTY and every assertion that needs real commits fails with confusing,\nunrelated symptoms: `base...HEAD HEAD HEAD`, `git log: no commits yet`, the\nprovenance block still empty.\n\n- **Set the throwaway repo's OWN repo-level `core.hooksPath` right after init:**\n  `git config core.hooksPath \u003Crepo>\u002F.git\u002Fhooks`. Repo-level is the sanctioned\n  escape (the enforcer's own message says \"a repo that should NOT have this\n  check sets its own core.hooksPath\"); per-invocation `-c core.hooksPath=` is a\n  BLOCKED bypass.\n- **Assert the fixture commit actually LANDED** (`git rev-list --count HEAD`\n  or the commit returncode) — a swallow-error commit helper hides the refusal\n  and leaves only empty repos. A refused fixture fails the SEED, not the later\n  assertions, so the red run names the real cause.\n\n## Verification\n\n- `pytest tests\u002Ftest_\u003Cmodule>_unit.py -q` → all pass\n- The suite collects the SAME number of tests under your wrapper as with `env -u\n  PYTHONPATH -u PYTHONHOME` (a lower count means modules failed to import)\n- The module's real state dir is clean after the run (no leftover files)\n- `grep -nE \"\u003Creal-chat-id>|\u003Creal-host>|\u002Fhome\u002F\u003Cuser>\u002F\" tests\u002F` → no hits\n- No network calls happened (fake send patched in; check no real HTTP in log)\n\n## Pitfalls\n\n- **NEVER mutate `sys.path` in test files to import the module under test.**\n  A `sys.path.insert(0, \u003Crepo>\u002Fcore)` in one suite SHADOWS same-named\n  modules\u002Fpackages for every sibling suite running later in the same pytest\n  process. Verified 2026-09-02: inserting `\u003Crepo>\u002Fcore` made\n  `import fleet_bus` resolve to the `core\u002Ffleet_bus\u002F` PACKAGE instead of\n  the `lib\u002Ffleet_bus.py` MODULE a sibling suite (test_bus_outbox) expected\n  → ImportErrors in the full run, green in isolation. The suite that\n  \"passes alone but breaks others\" is the culprit — run the pair together\n  to confirm. Fix for pure-stdlib modules under test: load them by FILE\n  PATH with a unique module name, zero path mutation:\n  ```python\n  def _load(name, path):\n      spec = importlib.util.spec_from_file_location(name, os.path.normpath(path))\n      assert spec is not None and spec.loader is not None, f\"cannot load {path}\"\n      mod = importlib.util.module_from_spec(spec)\n      spec.loader.exec_module(mod)\n      return mod\n  validate = _load(\"cortex_bus_validate_test\", \"core\u002Ffleet_bus\u002Fvalidate.py\")\n  ```\n  Works whenever the module has no intra-package imports. If it does, use a\n  `conftest.py` `pythonpath` entry (pytest-managed) instead of hand-rolled\n  inserts.\n- **Import-time path constants** are the #1 hermeticity killer (see rule 1).\n- **Real identifiers in fixtures** — a numeric chat id (e.g. `111222333`)\n  looks like an arbitrary integer and sails through the secret-leak detector;\n  the scanner only flags `\u002Fhome\u002F\u003Cuser>\u002F` paths and emails. Use placeholders\n  (`111222333`) and grep for the real id before committing.\n- **State leakage across tests** — every test needs its OWN tmp state dir;\n  sharing one makes tests order-dependent.\n- **The module's own `if __name__ == \"__main__\"` self-test** should also go\n  through the same seams, or it will hit real resources when run manually.\n- **Queue mock returns for EVERY caller of a seam, not just the call site you\n  are testing.** Before writing the mock, grep the function under test's full\n  call tree for uses of the seam — a sibling helper (e.g. a probe that queries\n  the same LLM\u002FAPI function) silently consumes the queued responses, and the\n  code under test receives the wrong fixture or runs dry. The failure looks\n  like a parsing bug in the function under test; the real bug is the mock\n  budget. Count the seam's call sites first, then size the queue.\n- **Import repo packages at MODULE level in the test file, not inside test\n  functions.** A `from pkg.sub import X` written inside a test function\n  re-reads `sys.path` at call time; when a sibling suite (or a conftest\n  fixture) restores\u002Fsnapshots `sys.path` between tests, the function-level\n  import fails with `ModuleNotFoundError` even though the suite passes in\n  isolation. Symptom: green alone, `No module named 'pkg.sub'` only in the\n  full run. Import the package at module top (after any `sys.path.insert`) so\n  it is cached in `sys.modules` — the cached module resolves from memory and\n  is immune to path resets. This is the complement of the shadowing rule\n  above: that rule is \"your insert breaks siblings\"; this is \"siblings'\n  restore breaks you.\"\n- **Keep fixtures free of long digit runs.** The repo PII guard\n  pattern-matches digit sequences as phone numbers and REFUSES the write — a\n  10-digit unix timestamp (`1700000000`) and an all-zeros UUID both tripped\n  it as \"phone number\". Use small ints for ids\u002Ftimestamps (chat id `7`,\n  `ts=1`), hex-letter UUIDs (`aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee`), and\n  `example.com` for URLs in shared-surface test files. (The flip side of the\n  numeric-chat-id rule above: that one is the detector missing a real id;\n  this one is the detector flagging a fake one.)\n- **A package module that imports cleanly can still crash when run as a\n  script.** Relative imports (`from .transport import X`) need a parent\n  package, so `python3 daemon.py` \u002F systemd `ExecStart` fails with\n  \"attempted relative import with no known parent package\" even though\n  `from pkg.daemon import main` works. Verify the REAL invocation path, not\n  just the import. Make one file work both ways with the run-as-script\n  bootstrap:\n  ```python\n  if __package__ in (None, \"\"):\n      import sys\n      from pathlib import Path\n      sys.path.insert(0, str(Path(__file__).resolve().parent.parent))\n      __package__ = \"\u003Cpkg_name>\"\n  ```\n- **Do not replace a monkeypatchable module constant with a hardcoded path.**\n  Repointing a reader from `SOME_HOME \u002F \".env\"` to a literal\n  `Path.home() \u002F \"x\" \u002F \".env\"` silently broke the test that redirects it with\n  `monkeypatch.setattr(mod, \"SOME_HOME\", tmp)` — it read the real host path and\n  failed. Keep a module-level constant (e.g. `FLEET_ENV_FILE`) and let tests\n  patch THAT; a hardcoded path has no seam.\n- **To find WHICH test pollutes `os.environ`, hook pytest — and run with `-s`.**\n  A throwaway plugin (`-p \u003Cname>`, module on `PYTHONPATH`) that prints at\n  `pytest_runtest_setup` when the leaked var is present, plus the previous test\n  id, pinpoints the leaker in one full run. Without `-s` pytest CAPTURES and\n  DISCARDS a passing test's output, so the print never appears and you wrongly\n  conclude \"no leak\". Check the var at SETUP, not teardown — fixtures undo\n  their own patches during teardown, so a teardown probe misses real leaks.\n - **A flaky test is not evidence the artifact is broken — probe the artifact\n OUT-OF-BAND before \"fixing\" it.** Identical code that fails 2 runs in 3 is a\n RACE, and the race is often in the TEST. Before touching the module under\n test, drive it directly by hand (same request, outside pytest); if it answers\n correctly, the fault is the harness you wrote, not the code you were about to\n \"fixing\" it. Re-run the single test 3x first — deterministic vs flaky selects\n completely different fixes, and guessing wrong means rewriting working code.\n- **A git-gate test is an ambient-state test in disguise.** An assertion that a hook\n  (pre-push, pre-commit) REFUSES a range only holds while the repo is ahead of its\n  upstream: it passes while work is in flight and fails the moment the tip is level,\n  which teaches readers to ignore it. Make the range a PRECONDITION — compute\n  `merge-base \u003Cupstream> HEAD`, and when it equals HEAD print an explicit SKIP with the\n  reason — then assert the refusal only where a range exists. Asserting into the ambient\n  condition instead is how a gate test turns red on a healthy tree.\n **If the flake stops reproducing, STOP bisecting and bank what you proved.** A\n failure that vanishes after N runs was a WINDOW, not an ordering: further\n bisect rounds buy nothing and cost the session. Record the MECHANISM you\n demonstrated with a control (a stub that reproduces it on demand), make the\n test hermetic against that mechanism, and leave the discriminator in the\n failure detail so a recurrence names its own route. \"Mechanism proven, trigger\n unidentified, guarded and diagnosed\" is a complete result — report it that way\n instead of widening the search.\n- **Asserting on SOURCE TEXT? Strip comments and docstrings first — the file\n  legitimately names the thing you are asserting is absent.** A guard written as\n  `assert \"addSystemPrompt\" not in src` failed against correct code, because the\n  file's own comment explained *why there is no `addSystemPrompt()`*. Grep the\n  raw text and you flag your own documentation; strip comment lines (and\n  preferably match the CALL, `addSystemPrompt(`, not the bare word) before\n  asserting. Same family as any probe that is wrong rather than the code:\n  a failing assertion is a claim about your probe first and the artifact\n  second.\n- **A guard that asserts a DETECTOR must assert the real one, not a plausible\n  one.** `assert \"sys.platform\" in src` failed against a store that correctly\n  detects macOS via `os.uname().sysname == \"Darwin\"`. Read the implementation\n  and assert what it actually does — or better, make the test\n  BEHAVIOURAL: force the branch (set the flag) and assert the built command,\n  instead of grepping for a string that merely resembles the mechanism.\n- **Whitespace-normalise before asserting a PHRASE against source text.** The\n  same family as the rule above: asserting a multi-word phrase failed because\n  the prose wrapped across a line break, so the substring never appeared\n  contiguously. Assert against `\" \".join(text.split())`, or drop the phrase\n  assertion for a structural one.\n- **Test the code you CHANGED — a neighbouring green suite is not evidence.**\n  Reporting \"24 passed\" from a test file that never imports either modified\n  module verifies nothing about the change; it is reassurance shaped like\n  proof, and it is the finding a reviewer will (correctly) raise. Before citing\n  a test run as evidence, check the path: does any test in that file FAIL if you\n  revert the change? If not, write one that does — a behavioural test on the\n  changed code path, not a broader suite that happens to be nearby.\n- **A fallback\u002Fshim only defined when a dependency is ABSENT cannot be tested\n  from the machine that has the dependency.** A guard asserting on the\n  conditional-shim class passed everywhere it was run and tested nothing: on a\n  host with the real package installed, the shim is never defined, so the\n  assertion inspected the real library instead. Drive the absent case for real\n  in a subprocess, by making the import fail:\n  ```python\n  # a None entry in sys.modules makes `import pkg` raise ImportError\n  script = \"import sys; sys.modules['pkg'] = None; sys.modules['pkg.sub'] = None\\n\"\n  script += \"...load the module by path, assert the fallback engaged...\"\n  subprocess.run([sys.executable, \"-c\", script], ...)\n  ```\n  A custom `find_spec` that RAISES ImportError is the wrong tool: the import\n  machinery does not catch it, so it aborts instead of falling through to your\n  guard. This case is worth a real test because it is the whole point of the\n  fallback — and it is exactly where a pre-existing hard exit or an\n  unreachable guard hides.\n- **A test that reads AMBIENT state tests the machine, not the code.** A refusal\n  case passed for as long as an unrelated stale lock file happened to exist in the\n  host's state dir, and went red the moment it was cleared — it had never once\n  exercised the branch it claimed to cover. Anything a test reads from a shared\n  location (locks, journals, session markers, live DB rows, **and inherited\n  environment variables**) is an accidental fixture: point it at a temp\n  `HOME`\u002F`ROOT`, inject the value, or `monkeypatch.delenv(\u003CVAR>, raising=False)` in\n  the shared runner when the test asserts the VAR-ABSENT branch. An agent shell\n  commonly exports identity vars (`AGENT_NAME`) — a test that passes `--agent`\n  explicitly still silently depends on the caller NOT exporting one, so it goes\n  green in a bare CI shell and red on a real host. Keep the real-resource assertion\n  as ONE explicitly-labelled case. Clearing unrelated state is the cheapest way to\n  discover tests that were passing by accident.\n  **The same trap fires when the subject reads a WELL-KNOWN HOST PATH, not an env var.**\n  Code that merges several registries (`~\u002F.pi\u002Fagent\u002Fmcp.json`, `~\u002F.claude.json`, the\n  Hermes `config.yaml`) reads the LIVE files even when you substituted the fixture for\n  one of them — the first two failing tests in a new suite both reported the host's\n  real server name from the OTHER registry. A runner that submits fixtures to the\n  subject must neutralise EVERY known path it reads (point them at a non-existent path\n  in the runner's default, opt-in per test for the one under test), or the real files'\n  content bleeds into every fixture.\n- **A fake path standing in for a real resource silently selects the FALLBACK branch.** Pointing the\n  code under test at `\u002Ftmp` (or any path holding no repository, no config, no service) is not a\n  neutral stand-in once the code gains an environment-derived branch: a probe like \"is there a git\n  repo here? a remote? a resolvable base?\" answers NO at that path, so the test that meant to drive\n  the NORMAL path drives the newly added fallback instead — green, and asserting about the wrong\n  branch. It bites hardest immediately after adding such a branch, and it surfaces in several\n  unrelated files at once (the same new predicate was reached by two different suites). Stub the\n  predicate explicitly in every test that describes the normal case (`m._is_fallback = lambda repo:\n  False`), give the fallback its OWN test asserting the fallback-specific behaviour, and name in the\n  docstring which case the file is about — otherwise the next environment branch added reaches in\n  again.\n- **A test that repoints a SHARED module attribute (a module it does not own)\n  must restore it in `finally`.** `setattr(doctor_checks, \"HOME\", tmp)` looks\n  like ordinary fixture setup and is not: the value outlives the test, survives\n  into every later file in the process, and points at a temporary directory the\n  harness then deletes. Every later test that reads that module silently\n  produces nothing. The signature is worth memorising: **the failures appear in a\n  DIFFERENT file from the culprit, and the culprit's own tests are green** — so\n  the file you are staring at is the symptom, not the cause. Restore on the way\n  out whether the body succeeded or raised, and add a regression test in the\n  mutating file asserting the attribute is unchanged after the call.\n  **The same trap fires INSIDE one file, across sections.** A test that installs a stub for\n  section A and never puts the real function back leaves every later section asserting against the\n  stub — and because a stub returns plausible values, the red run points at the code under test\n  instead of at the test (a `None` lock returned by the stub made three \"must still fail closed\"\n  assertions look like the guard had been removed). Save the real attribute before patching and\n  re-install it at the section boundary (`real = m.fn` … `m.fn = real`), or scope the stub to the\n  section that needs it;  when a whole block of assertions fails together in a fresh file, suspect\n  the stub before the code.\n- **POISON the collaborators the unit must NOT touch, rather than only restoring the ones it patches.**\n  Restoring in `finally` protects LATER tests; it does not protect THIS one from depending on an\n  earlier test's teardown, or on a patch it never made. For every module attribute the function under\n  test is not supposed to consult, install a stub that RAISES:\n  ```python\n  def _poison(*a, **k):\n      raise AssertionError(\"must not call the store\u002Frange helpers\")\n  ```\n  Two things come out of it: the test becomes deterministic under any ordering (a leaked or\n  not-yet-restored patch fails LOUDLY and names the offending call instead of returning a plausible\n  value that makes the assertions point at the code under test), and the unit's real dependency set\n  is asserted rather than assumed. Restore EVERY attribute the test set in `finally` — the poisoned\n  ones included, since a poison left behind breaks the next test exactly as a leak does. Prefer a\n  `with`-scoped helper that saves and restores them together when a file has several such tests.\n- **Finding WHICH test pollutes shared state is a pairing search, not a reading\n  exercise.** See `references\u002Forder-dependent-failure-bisect.md` for the recipe\n  — run the victim alone, pair it with each candidate that touches the module,\n  then bisect the failing group — and for what to do when the failure will not\n  reproduce at all.\n- **A test that references a DELIBERATELY-REMOVED symbol is stale, not a bug in the\n  feature.** When a sibling suite fails on a constant that no longer exists in code\n  (e.g. a reviewer-model constant the operator reversed out of existence), the test\n  asserts the OLD contract — rewrite it to assert the CURRENT behavior (default →\n  canonical model; env override → cheaper), do NOT \"repair\" it by re-adding the\n  constant. Re-adding a constant a reversal deleted is how a reverted decision creeps\n  back in. Confirm via `git log -S '\u003Csymbol>' -- \u003Cfile>` that the removal was\n  deliberate before concluding it is stale drain rather than a live regression.\n- **A regression test whose SEED stage fails silently passes trivially — guard the seed\n  before the exercise step.** A rename test that seeded the legacy entry by cloning a key\n  that a prior stage had already deleted died with KeyError, and the assertions that\n  followed passed against the UNSEDED fixture: the check was green without ever exercising\n  the rename. Any multi-stage test where later stages depend on an earlier stage's write\n  must assert the fixture landed (`grep -q '\"key\"' \u003Cfixture>` \u002F `assert marker in\n  fixture`) between seed and exercise, so a dead seed fails the test instead of passing it\n  for the wrong reason. A check that reads \"PASS\" while its setup raised is a false green,\n  not a flake.\n- **Derive a state-machine test's cases from the module's OWN table, not from your\n  memory of it.** A test that hardcodes \"advance X → completed\" fails when the\n  machine does not allow that edge, and the red run blames the transition instead\n  of the assumption. Read the permitted set out of the module\n  (`for src, allowed in m.VALID_TRANSITIONS.items()`) and drive a pair it actually\n  allows, skipping with a printed reason when there is none — then assert BOTH\n  directions (the permitted edge behaves, the forbidden one is refused) so the\n  so the table, not the fixture, decides what is legal.\n  - **Before adding a helper to a test module, grep it for one that already exists — a hand-rolled\n    duplicate SHADOWS the original, and your new tests silently call the wrong signature.** A second\n    `_run()` added to a suite whose first `_run` is `(*args, env=None)` made three new tests pass a\n    dict positionally: they failed with argument-shaped errors that point at the assertions, not at\n    the helper, so the red run reads like a bug in the code under test. Check first\n    (`grep -n \"^def \" tests\u002Ftest_\u003Cmodule>.py`), then use the existing seam. Read    its semantics too:\n    a helper that merges `{**os.environ, **env}` can ADD or override a variable but cannot REMOVE\n    one, so a VAR-ABSENT branch is only reachable through it by passing an EMPTY value (which a\n    `[[ -n \"$VAR\" ]]` guard treats as unset) — pass a sentinel and the branch you think you are\n    testing is the VAR-SET one.\n- **'The newest \u003Cfile>' is the definition only when it DEFINES the construct.** A guard that\n  reads `_migrations()[-1]` (or any 'latest config \u002F schema \u002F script') fails against a newer\n  file that only USES the thing — a later migration that CALLS a function whose body an\n  earlier one defines. Scan the set for the record that DEFINES the construct, newest-first,\n  and match the exact definition (the function signature, not the file containing a mention),\n  or the guard reads the wrong file and goes red on healthy code.\n- **A 'skip if \u003Clib> not importable' check can be defeated by importable-but-broken libraries\n  under contamination.** `import reportlab` succeeds on a polluted heap while its real\n  dependency (PIL's `_imaging` C extension) fails at build time, so a test that skips only on\n  ImportError runs instead and fails mid-build. Widen the skip to import the ACTUAL dependency\n  the exercised path needs and catch the broken-load exception — the point of the skip is 'the\n  libs are usable here', not 'the top-level name resolves'.\n- **A standalone test that loads its collaborator by path must check it AS A TEST, never at\n  import.** Script-style suites that are each run directly (`python3 tests\u002Ftest_\u003Cname>.py`, no\n  framework) make a module-scope precondition (`if not hasattr(mod, \"fn\"): raise SystemExit(...)`)\n  fatal: the run dies before any test reports, the failure names no test, and a reader — including\n  an automated reviewer of the diff — files it as a crash rather than as a guard, which is the\n  opposite of what a precondition is for. Put the checks in a function the runner reaches FIRST\n  (a name-sorted runner reaches `test_00_preconditions` before any behaviour test) and ASSERT\n  rather than raise: the collaborator exists, it carries the parameters this file calls it with\n  (`inspect.signature`), and any module-level fact the test depends on is real — e.g. the logger it\n  silences is the logger the module actually uses, otherwise the silencing is decorative and test\n  output reaches production state. A genuine import failure stays an import error; a MISSING\n  CAPABILITY becomes a named failing test.\n","# Hermetic Python Testing\n\nWrite Python modules so their unit tests never touch real state, real\ncredentials, or real network — and prove it. Born from telegram_notify S2\n(2026-08-08): tests silently wrote to `~\u002F.steadfaste-fleet\u002Fstate\u002F` and read the\nreal `~\u002F.hermes\u002F.env` until the module was restructured.\n\n## When to Use\n\n- Writing a new Python module that reads env vars, paths, or config files\n- Adding L0 unit tests to a module that touches files, state, or network\n- A test \"passes\" but you suspect it hit real resources (check the module's\n  log\u002Fstate files for unexpected entries)\n- Refactoring a module to be testable without mocking the whole world\n\n## Core Rules\n\n### 1. Resolve paths LAZILY, never at import time\n\n```python\n# ❌ BAD — frozen at import; tests setting the env var after import hit REAL paths\nSTATE_FILE = Path(os.environ.get(\"MY_STATE_DIR\", Path.home() \u002F \".x\")) \u002F \"state.json\"\n\n# ✅ GOOD — resolved per call; tests point it at tmp_path via monkeypatch.setenv\ndef _state_file() -> Path:\n    return Path(os.environ.get(\"MY_STATE_DIR\", Path.home() \u002F \".x\")) \u002F \"state.json\"\n```\n\nImport-time constants freeze the path for the whole process. Tests that set\nenv vars AFTER import (the standard `monkeypatch.setenv` pattern) silently\nread\u002Fwrite the real location. Symptom to watch for: a module's real log file\nor state JSON appears in `~\u002F.steadfaste-fleet\u002Fstate\u002F` after a test run.\n\n### 2. Expose seams for clock and send, then monkeypatch them\n\n```python\ndef _now() -> float: return time.time()\ndef _sleep(s: float) -> None: time.sleep(s)\ndef _send_once(token, chat_id, text): ...   # the network boundary\n```\n\nTests patch these module attributes:\n```python\nwith patch.object(tn, \"_now\", side_effect=fake_now), \\\n     patch.object(tn, \"_send_once\", side_effect=fake_send):\n    ...\n```\nThis tests coalescing windows, retry budgets, and backoff with a fake clock\nand zero network.\n\n### 3. Hermetic fixture setup — state dir AND env file, both in tmp\n\nEvery test that exercises the module gets its own tmp state dir and a fake\nenv file:\n\n```python\ndef _setup(tmp_path, monkeypatch, chat=\"111222333\", quiet=\"\", mute=\"\"):\n    state_dir = tmp_path \u002F \"state\"; state_dir.mkdir(exist_ok=True)\n    env_file = tmp_path \u002F \"env\"\n    env_file.write_text(f\"TELEGRAM_BOT_TOKEN=123456:TESTTOKEN\\nTELEGRAM_HOME_CHANNEL={chat}\\n\")\n    monkeypatch.setenv(\"MY_STATE_DIR\", str(state_dir))\n    monkeypatch.setenv(\"MY_ENV_FILE\", str(env_file))\n    return state_dir, env_file\n```\n\n### 4. Verify the hermeticity — never trust \"tests passed\"\n\nAfter the suite is green, confirm no real resources were touched:\n- The module's real state\u002Flog\u002Flock files must NOT exist afterward\n- No real credentials were read (check for side effects like real sends)\n- Grep the test file for real identifiers (chat ids, tokens, hostnames,\n  `\u002Fhome\u002F\u003Cuser>\u002F` paths) — placeholder values only\n\n### 5. Override live-side-effect defaults EXPLICITLY — sandboxed inputs are not hermeticity\n\nA test that feeds tmp_path INPUTS can still act on the real world if the tool\nunder test has a default OUTPUT route. Proven 2026-09-30: the bridge-runner\ntest ran `fleet-bus-bridge-run.py` on a tmp echo.py without `--deliver` — the\nrunner's default is Telegram, so every test run sent `cron:test-echo \u002F hello\nfrom test` to the user's real chat (repeated complaints: \"I keep seeing\nthis\"). Before invoking any tool\u002FCLI in a test, grep its args\u002Fenv for defaults\nthat route to a real channel (messenger, webhook, mail, metrics) and pass the\nexplicit safe target (`--deliver local`, `FLEET_DEPLOY_HOME=tmp_path`).\nAssert the live default in a dedicated test — never exercise it by accident.\n\n**Prefer a SUITE-LEVEL kill-switch over per-call flags.** Passing the safe\ntarget into the test you happen to be writing does not protect the suite: the\nnext test someone adds calls the same function with the same dangerous default,\nand the live channel fires again. Put an autouse SESSION fixture in\n`conftest.py` that redirects the module's config away from production for the\nwhole process — point its env-file at a path that does not exist and clear the\ndestination chat\u002Fwebhook variable. The fail-safe direction is \"no credential →\nskip\", never \"no credential → guess\". Tests that genuinely exercise the send\npath set their own values back via `monkeypatch`, so the guard costs them\nnothing.\n\n**Mocking the write does NOT mock the notify.** A post-commit side effect sits\nAFTER the call you patched: a unit test that mocks the DB layer and asserts the\nstored value still runs the notification that write triggers. Verified: a test\nproving a shell payload is stored as a literal — mocking only the query layer —\nalso sent a real message on every run, which surfaced as recurring user noise\n(\"I keep seeing this\") that could never resolve because each run minted a fresh\nid. When you mock a dependency, read the function you are calling through to the\nEND and list every external effect that follows the mocked call.\n\n**A guard needs a control proving the GUARD did the work.** \"notify returned\nFalse\" also passes if the module is simply broken. Pair it: assert the send path\nrefuses under the suite's environment, AND assert that with a valid env file the\nsame probe DOES resolve its credential (a read-only call — no send). Without the\nsecond half, the first half proves nothing.\n\n**A tool you invoke may detect its SUBJECT on the inherited PATH.** When the\ncode under test shells out and probes for a binary (`command -v \u003Ctool>`), passing\nthe ambient `PATH` through means the case asserting \"tool not installed\" can be\nsatisfied by the runner's own install: the audited host is no longer the only\nsource of truth, the assertion flips per machine, and the failure names nothing\nuseful (\"expected exit 1, got 0\"). Scrub the PATH for every case — drop each\ndirectory that actually contains the binary — and put the detected route in the\nfailure DETAIL (`tool_on_PATH=\u003Cwhich(...)>`, `home_tool=\u003Cexists>`), so the next\nred run says which route the tool took instead of only the exit code.\n\n### 6. An imported module must not mutate `os.environ` at import\n\nLoading a module is not a side-effect-free act. A module that parses an env\nfile into `os.environ` at MODULE scope poisons the whole pytest process for\nevery suite that runs after it. Verified 2026-10-01: a deploy script\nexported the canonical env file at import; a metrics suite `exec_module`d it,\nso a var added to that file that day leaked into the process env and the\nnotify suite — which resolves its chat id from `os.environ` FIRST — used the\nreal value and failed only in the full run.\n\nTwo rules follow:\n\n- **The module:** keep env-file parsing in a function called from `main()`\n  (`_source_env_overrides()`), never at module scope. Prove it: `exec_module`\n  the file and assert no var appeared.\n- **The test:** if the code under test reads a process-env var BEFORE its\n  fixture file, `monkeypatch.delenv` that var in the fixture. A fixture that\n  only points its own env file cannot defend against a leaked process value.\n\n### 7. An imported module's LOGGER writes to real state\n\nLoading a module runs its module-level logging setup. A module that attaches a file\nhandler at import (a `RotatingFileHandler` over a real log directory) means every\ntest that imports it APPENDS to that production log, and the entries are\nindistinguishable from real ones — a fabricated cycle number or a `(test)` error line\nlands in the audit trail a reviewer will later read as history. Same family as rule 6:\nimport is not a side-effect-free act.\n\n- **Silence by LEVEL, and leave the handler attached.** Setting the logger above\n  CRITICAL suppresses records. Clearing handlers is stronger but destroys the seam you\n  need to prove the silencing works, and a module that re-attaches handlers later\n  defeats the clear.\n- **Prove the \"it did not write\" assertion is not vacuous.** An assertion that a real\n  file did not grow also passes when the code could never have written to it — e.g.\n  the module resolves its log path from a constant the test redirected. Check both\n  directions, and make the control write NOTHING (writing to prove a file is not\n  written to is self-defeating): first assert the logger carries a handler BOUND to\n  the real target (a `FileHandler`'s `baseFilename`), then detach it, restore the\n  level with a counting handler attached, and assert records ARE emitted — so there\n  was something to suppress — then re-attach and assert the silenced run contributes no\n  FABRICATED line. If the control cannot emit, the test is measuring nothing.\n- **Assert the \"did not write\" property by CONTENT, never by file SIZE.** A byte-equality\n  check on a shared log is racy: any concurrent writer — a cron, a deploy, another\n  agent — appending a legitimate entry during the measurement window fails a test about\n  YOUR code, i.e. a false report of the very thing the test claims to measure. Read the\n  bytes appended in the window and assert none of them carries the test's own markers\n  (its fabricated ids, its session name, its `(test)` strings); if something else wrote\n  meanwhile, report that as non-test growth instead of failing on it.\n- **Know what the module binds at IMPORT vs what you patch afterwards.** A handler\n  built at import keeps the real path even after the test patches the module's HOME; a\n  path resolved per call follows the patch. Assert what is actually bound before\n  trusting either result — a passing one-way size check is a claim about your probe,\n  not about the artifact.\n\n### 8. Once-only initialization must be keyed to the RESOURCE, not to the process\n\nA module-level \"already done\" flag (`_SCHEMA_DONE = False`) makes the FIRST\nresource a process touches the only one that ever gets set up. Any caller that\nswitches resources later — a test repointing the module constant at a tmp file,\na tool opening a second database — receives an un-set-up resource and fails on\nthe first query against it (`no such table: \u003Cname>`). The failure reads as\nflakiness: those tests pass in isolation and fail in a full run, because some\nother test has already opened the first resource.\n\n- **Key the guard to the thing that varies** — the database FILE, the directory\n  being prepared, the fixture identity — a SET of resources rather than a\n  boolean.\n- **Read the key from the connection\u002Fhandle under test, not from the module\n  constant.** The caller may have repointed the constant after the connection was\n  opened, and the question the guard actually answers is \"does THIS resource have\n  its setup\" (`PRAGMA database_list` gives the file a sqlite connection is\n  attached to).\n- **This is a SEAM, not just a test fix.** The process-global flag is untestable\n  by construction: no fixture can prove setup happened for the second resource\n  while the code can only ever answer for the first. Fix the module, then pin it\n  with a test that opens two resources in one process — and a premise test so the\n  guard cannot pass vacuously if the DDL entry point moves.\n- **When the repo's own suite is red, test the claim that it is not your fault.**\n  Re-run the full suite with no lock and no in-flight change and compare the\n  failure LIST, not the count: identical list = pre-existing, and \"passes in\n  isolation, fails in the full run\" points at module state, not at you.\n\n### 9. The caller's environment can change WHICH tests exist — not just what they read\n\nRule 6's family, one level up. An inherited `PYTHONPATH` or `PYTHONHOME` that points at a\nforeign `site-packages` makes some test modules fail to IMPORT, and pytest then reports a\nsmaller suite as a clean run. Measured on one host, same command, only the environment\ndiffering: **1818 collected with 4 collection errors** contaminated vs **1846 with none**\nclean — four whole modules dropped, and the runner printed `N passed` either way. An agent\nshell almost always exports `PYTHONPATH`, so the contaminated case is the DEFAULT case.\n\n- **Run the suite through a wrapper that CLEANSES the environment and resolves the\n  interpreter by CAPABILITY** (never by `PATH` or a bare `python3`): `env -u PYTHONPATH -u\n  PYTHONHOME \"$PY\" -m pytest …`. Copyable shape: `templates\u002Frun-tests.sh`.\n- **The wrapper must not REQUIRE a fleet install.** A repo whose host has no resolver and no fleet\n  venv still needs to run its own suite: probe `python3`\u002F`python` on `PATH` by CAPABILITY (still an\n  import test, never a bare path), ANNOUNCE that you fell back and why, and still exit 3 when nothing\n  can import pytest. A silent fallback is worse than none — it swaps which code decides the interpreter\n  while the run looks identical, and it can make a stub test exercise the real thing and \"pass\".\n- **Pin the wrapper's portability, not only its behaviour.** A source scan asserting no bash-4-only or\n  BSD-hostile construct (the list lives in `shell-scripting`), plus a run of the REAL wrapper in a\n  constructed environment (temp repo, empty HOME, stubbed PATH) for the branches your host cannot\n  reach. Same for the guard's numbers: assert \"more than zero collected\", never a count that is only\n  true of one repo — a shared guard that encodes this repo's size fails a healthy smaller repo.\n- **Guard collection, not just results.** A test that runs the suite's collection in a\n  subprocess and FAILS on `N errors during collection` — while also asserting a non-trivial\n  collected count, so “0 collected” cannot read as clean — is what stops a dropped module\n  from being reported behind a green total. A green run that tests less than it claims is\n  worse than a red one.\n- **A collection error is not a missing dependency.** `ModuleNotFoundError` naming a\n  SUBMODULE of an installed package (`pydantic_core._pydantic_core`) is an ABI mismatch from\n  a shadowed `site-packages`, not something to `pip install`: fix the environment, not the\n  package list, and never record it as “dependency X is broken”.\n- **Check the runner's own default before blaming a test.** pytest with FLAGS but no PATH\n  collects the whole current directory — in a repo that means `.git`, deploy trees and the\n  venv, and it hangs. Always supply a path.\n\n### 10. A module-level ENTRYPOINT makes a script un-importable — and the importer cannot defend itself\n\nRules 6 and 7 are about a module's side effects at import; this is that family one step further:\nthe module's whole JOB runs at module scope. `count = purge()` + `sys.exit(0)` at the bottom of a\nscript means importing it to exercise its shipped logic fires the work against the LIVE resource,\nand the importer cannot prevent it — repointing the module's path constant after `exec_module` is\nalready too late. Observed: a probe importing a purge script removed 780 files from the live state\ndirectory before it could repoint anything. The importer is then left reporting a side effect it\ncaused while measuring something else.\n\n- **Fix the MODULE, not the importer:** `def main() -> int: ...` plus\n  `if __name__ == \"__main__\": sys.exit(main())`. Import becomes inert; only running the file has\n  effects — and the function stays drivable with its path constant repointed.\n- **Check BEFORE importing a file you do not own.** Read the end of the file (or `ast`-walk its\n  module body) for a bare call, a `print`, or `sys.exit` outside a def or the `__main__` guard.\n  If one is there, fix the guard first — do not import it \"just to see\".\n- **Prove the guard in THREE directions**, because \"it did not purge\" also passes when the function\n  is simply broken: (a) with the home directory patched into a temp tree, importing leaves the\n  stale fixture untouched AND the module's path constant really resolves into that temp tree —\n  without that second half, (a) asserts only that the probe aimed somewhere harmless; (b) calling\n  the function DOES remove the fixture; (c) running the file as a SUBPROCESS with `HOME` redirected\n  removes it and reports — the real cron\u002Fsystemd path, which an import test never exercises.\n- **Pin the shape source-level too:** walk the module body with `ast` and assert every top-level\n  statement is an import, an assignment, a def, or the `__main__` guard, so a future edit cannot\n  quietly reintroduce the side effect.\n\n### 11. An end-to-end test drives the REAL path — and must not depend on the DEPLOYED tree\n\nThis user's standard for a non-trivial change is comprehensive unit tests PLUS one end-to-end run\nof the real system path (real argv in, real exit status out), which is the seam that catches what\nunit seams cannot. Two rules keep that test honest and durable:\n\n- **Redirect the deploy\u002Finstall ROOT at a fixture; never let the test read the host's deployed\n  state.** A command that resolves a collaborator from a deploy root (a CLI whose module is copied\n  under the deploy home, a doctor that drives it) passes locally and goes RED on every fresh\n  checkout, because the deployed copy is only current after a deploy — and the first failure a\n  reader meets is the suite, not the change, which is how a suite becomes something people ignore.\n  Point the root variable at `tmp_path` (env\u002Fmonkeypatch: `FLEET_DEPLOY_HOME=\u003Ctmp>`), so the test\n  exercises the repo's own copy and measures the CHECK and the CLI it drives. Then verify the\n  DEPLOYED wiring by RUNNING it in the cycle that changes it (a real invocation against the deployed\n  path, recorded in the committed evidence) — deployment state is verified live, not asserted in a\n  test. Note the consequence for assertions about the run: the exit code then reflects EVERY check\n  the command performs (a pre-deploy tree fails unrelated deploy-sync checks), so assert the\n  property you own (`rc` is a usage-clean code, the JSON parses) and say in a comment why an exact\n  0 would turn the test into a probe of the host.\n- **Build the fixture from the collaborator's REAL output, not from your reading of it.** When the\n  fixture stands in for another tool's machine-readable input (a `--json` inventory, a manifest, a\n  config the code parses), generate it by RUNNING that tool against a fixture directory with its own\n  input path redirected — a hand-written fixture pins your guess at the shape, so it keeps passing\n  after the real output changes and fails only when the guess was wrong. That is the difference from\n  rule 5: the collaborator runs for real, on fixture inputs.\n\n### 12. Real-git test fixtures must sandbox their OWN hooks — the host's global `core.hooksPath` runs inside them\n\nA test that creates a real git repo in `tmp_path` inherits the host's GLOBAL\n`core.hooksPath`. On a governed host that points it at the fleet hooks\n(`~\u002F.steadfaste-fleet\u002Fhooks`), the fleet pre-commit hook runs INSIDE the\nthrowaway repo and refuses the fixture's bare commits (no pathspec) with a\nnon-zero exit. When the fixture's commit helper swallows the return code (the\nstandard `subprocess.run([...]).stdout` pattern), the repo silently stays\nEMPTY and every assertion that needs real commits fails with confusing,\nunrelated symptoms: `base...HEAD HEAD HEAD`, `git log: no commits yet`, the\nprovenance block still empty.\n\n- **Set the throwaway repo's OWN repo-level `core.hooksPath` right after init:**\n  `git config core.hooksPath \u003Crepo>\u002F.git\u002Fhooks`. Repo-level is the sanctioned\n  escape (the enforcer's own message says \"a repo that should NOT have this\n  check sets its own core.hooksPath\"); per-invocation `-c core.hooksPath=` is a\n  BLOCKED bypass.\n- **Assert the fixture commit actually LANDED** (`git rev-list --count HEAD`\n  or the commit returncode) — a swallow-error commit helper hides the refusal\n  and leaves only empty repos. A refused fixture fails the SEED, not the later\n  assertions, so the red run names the real cause.\n\n## Verification\n\n- `pytest tests\u002Ftest_\u003Cmodule>_unit.py -q` → all pass\n- The suite collects the SAME number of tests under your wrapper as with `env -u\n  PYTHONPATH -u PYTHONHOME` (a lower count means modules failed to import)\n- The module's real state dir is clean after the run (no leftover files)\n- `grep -nE \"\u003Creal-chat-id>|\u003Creal-host>|\u002Fhome\u002F\u003Cuser>\u002F\" tests\u002F` → no hits\n- No network calls happened (fake send patched in; check no real HTTP in log)\n\n## Pitfalls\n\n- **NEVER mutate `sys.path` in test files to import the module under test.**\n  A `sys.path.insert(0, \u003Crepo>\u002Fcore)` in one suite SHADOWS same-named\n  modules\u002Fpackages for every sibling suite running later in the same pytest\n  process. Verified 2026-09-02: inserting `\u003Crepo>\u002Fcore` made\n  `import fleet_bus` resolve to the `core\u002Ffleet_bus\u002F` PACKAGE instead of\n  the `lib\u002Ffleet_bus.py` MODULE a sibling suite (test_bus_outbox) expected\n  → ImportErrors in the full run, green in isolation. The suite that\n  \"passes alone but breaks others\" is the culprit — run the pair together\n  to confirm. Fix for pure-stdlib modules under test: load them by FILE\n  PATH with a unique module name, zero path mutation:\n  ```python\n  def _load(name, path):\n      spec = importlib.util.spec_from_file_location(name, os.path.normpath(path))\n      assert spec is not None and spec.loader is not None, f\"cannot load {path}\"\n      mod = importlib.util.module_from_spec(spec)\n      spec.loader.exec_module(mod)\n      return mod\n  validate = _load(\"cortex_bus_validate_test\", \"core\u002Ffleet_bus\u002Fvalidate.py\")\n  ```\n  Works whenever the module has no intra-package imports. If it does, use a\n  `conftest.py` `pythonpath` entry (pytest-managed) instead of hand-rolled\n  inserts.\n- **Import-time path constants** are the #1 hermeticity killer (see rule 1).\n- **Real identifiers in fixtures** — a numeric chat id (e.g. `111222333`)\n  looks like an arbitrary integer and sails through the secret-leak detector;\n  the scanner only flags `\u002Fhome\u002F\u003Cuser>\u002F` paths and emails. Use placeholders\n  (`111222333`) and grep for the real id before committing.\n- **State leakage across tests** — every test needs its OWN tmp state dir;\n  sharing one makes tests order-dependent.\n- **The module's own `if __name__ == \"__main__\"` self-test** should also go\n  through the same seams, or it will hit real resources when run manually.\n- **Queue mock returns for EVERY caller of a seam, not just the call site you\n  are testing.** Before writing the mock, grep the function under test's full\n  call tree for uses of the seam — a sibling helper (e.g. a probe that queries\n  the same LLM\u002FAPI function) silently consumes the queued responses, and the\n  code under test receives the wrong fixture or runs dry. The failure looks\n  like a parsing bug in the function under test; the real bug is the mock\n  budget. Count the seam's call sites first, then size the queue.\n- **Import repo packages at MODULE level in the test file, not inside test\n  functions.** A `from pkg.sub import X` written inside a test function\n  re-reads `sys.path` at call time; when a sibling suite (or a conftest\n  fixture) restores\u002Fsnapshots `sys.path` between tests, the function-level\n  import fails with `ModuleNotFoundError` even though the suite passes in\n  isolation. Symptom: green alone, `No module named 'pkg.sub'` only in the\n  full run. Import the package at module top (after any `sys.path.insert`) so\n  it is cached in `sys.modules` — the cached module resolves from memory and\n  is immune to path resets. This is the complement of the shadowing rule\n  above: that rule is \"your insert breaks siblings\"; this is \"siblings'\n  restore breaks you.\"\n- **Keep fixtures free of long digit runs.** The repo PII guard\n  pattern-matches digit sequences as phone numbers and REFUSES the write — a\n  10-digit unix timestamp (`1700000000`) and an all-zeros UUID both tripped\n  it as \"phone number\". Use small ints for ids\u002Ftimestamps (chat id `7`,\n  `ts=1`), hex-letter UUIDs (`aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee`), and\n  `example.com` for URLs in shared-surface test files. (The flip side of the\n  numeric-chat-id rule above: that one is the detector missing a real id;\n  this one is the detector flagging a fake one.)\n- **A package module that imports cleanly can still crash when run as a\n  script.** Relative imports (`from .transport import X`) need a parent\n  package, so `python3 daemon.py` \u002F systemd `ExecStart` fails with\n  \"attempted relative import with no known parent package\" even though\n  `from pkg.daemon import main` works. Verify the REAL invocation path, not\n  just the import. Make one file work both ways with the run-as-script\n  bootstrap:\n  ```python\n  if __package__ in (None, \"\"):\n      import sys\n      from pathlib import Path\n      sys.path.insert(0, str(Path(__file__).resolve().parent.parent))\n      __package__ = \"\u003Cpkg_name>\"\n  ```\n- **Do not replace a monkeypatchable module constant with a hardcoded path.**\n  Repointing a reader from `SOME_HOME \u002F \".env\"` to a literal\n  `Path.home() \u002F \"x\" \u002F \".env\"` silently broke the test that redirects it with\n  `monkeypatch.setattr(mod, \"SOME_HOME\", tmp)` — it read the real host path and\n  failed. Keep a module-level constant (e.g. `FLEET_ENV_FILE`) and let tests\n  patch THAT; a hardcoded path has no seam.\n- **To find WHICH test pollutes `os.environ`, hook pytest — and run with `-s`.**\n  A throwaway plugin (`-p \u003Cname>`, module on `PYTHONPATH`) that prints at\n  `pytest_runtest_setup` when the leaked var is present, plus the previous test\n  id, pinpoints the leaker in one full run. Without `-s` pytest CAPTURES and\n  DISCARDS a passing test's output, so the print never appears and you wrongly\n  conclude \"no leak\". Check the var at SETUP, not teardown — fixtures undo\n  their own patches during teardown, so a teardown probe misses real leaks.\n - **A flaky test is not evidence the artifact is broken — probe the artifact\n OUT-OF-BAND before \"fixing\" it.** Identical code that fails 2 runs in 3 is a\n RACE, and the race is often in the TEST. Before touching the module under\n test, drive it directly by hand (same request, outside pytest); if it answers\n correctly, the fault is the harness you wrote, not the code you were about to\n \"fixing\" it. Re-run the single test 3x first — deterministic vs flaky selects\n completely different fixes, and guessing wrong means rewriting working code.\n- **A git-gate test is an ambient-state test in disguise.** An assertion that a hook\n  (pre-push, pre-commit) REFUSES a range only holds while the repo is ahead of its\n  upstream: it passes while work is in flight and fails the moment the tip is level,\n  which teaches readers to ignore it. Make the range a PRECONDITION — compute\n  `merge-base \u003Cupstream> HEAD`, and when it equals HEAD print an explicit SKIP with the\n  reason — then assert the refusal only where a range exists. Asserting into the ambient\n  condition instead is how a gate test turns red on a healthy tree.\n **If the flake stops reproducing, STOP bisecting and bank what you proved.** A\n failure that vanishes after N runs was a WINDOW, not an ordering: further\n bisect rounds buy nothing and cost the session. Record the MECHANISM you\n demonstrated with a control (a stub that reproduces it on demand), make the\n test hermetic against that mechanism, and leave the discriminator in the\n failure detail so a recurrence names its own route. \"Mechanism proven, trigger\n unidentified, guarded and diagnosed\" is a complete result — report it that way\n instead of widening the search.\n- **Asserting on SOURCE TEXT? Strip comments and docstrings first — the file\n  legitimately names the thing you are asserting is absent.** A guard written as\n  `assert \"addSystemPrompt\" not in src` failed against correct code, because the\n  file's own comment explained *why there is no `addSystemPrompt()`*. Grep the\n  raw text and you flag your own documentation; strip comment lines (and\n  preferably match the CALL, `addSystemPrompt(`, not the bare word) before\n  asserting. Same family as any probe that is wrong rather than the code:\n  a failing assertion is a claim about your probe first and the artifact\n  second.\n- **A guard that asserts a DETECTOR must assert the real one, not a plausible\n  one.** `assert \"sys.platform\" in src` failed against a store that correctly\n  detects macOS via `os.uname().sysname == \"Darwin\"`. Read the implementation\n  and assert what it actually does — or better, make the test\n  BEHAVIOURAL: force the branch (set the flag) and assert the built command,\n  instead of grepping for a string that merely resembles the mechanism.\n- **Whitespace-normalise before asserting a PHRASE against source text.** The\n  same family as the rule above: asserting a multi-word phrase failed because\n  the prose wrapped across a line break, so the substring never appeared\n  contiguously. Assert against `\" \".join(text.split())`, or drop the phrase\n  assertion for a structural one.\n- **Test the code you CHANGED — a neighbouring green suite is not evidence.**\n  Reporting \"24 passed\" from a test file that never imports either modified\n  module verifies nothing about the change; it is reassurance shaped like\n  proof, and it is the finding a reviewer will (correctly) raise. Before citing\n  a test run as evidence, check the path: does any test in that file FAIL if you\n  revert the change? If not, write one that does — a behavioural test on the\n  changed code path, not a broader suite that happens to be nearby.\n- **A fallback\u002Fshim only defined when a dependency is ABSENT cannot be tested\n  from the machine that has the dependency.** A guard asserting on the\n  conditional-shim class passed everywhere it was run and tested nothing: on a\n  host with the real package installed, the shim is never defined, so the\n  assertion inspected the real library instead. Drive the absent case for real\n  in a subprocess, by making the import fail:\n  ```python\n  # a None entry in sys.modules makes `import pkg` raise ImportError\n  script = \"import sys; sys.modules['pkg'] = None; sys.modules['pkg.sub'] = None\\n\"\n  script += \"...load the module by path, assert the fallback engaged...\"\n  subprocess.run([sys.executable, \"-c\", script], ...)\n  ```\n  A custom `find_spec` that RAISES ImportError is the wrong tool: the import\n  machinery does not catch it, so it aborts instead of falling through to your\n  guard. This case is worth a real test because it is the whole point of the\n  fallback — and it is exactly where a pre-existing hard exit or an\n  unreachable guard hides.\n- **A test that reads AMBIENT state tests the machine, not the code.** A refusal\n  case passed for as long as an unrelated stale lock file happened to exist in the\n  host's state dir, and went red the moment it was cleared — it had never once\n  exercised the branch it claimed to cover. Anything a test reads from a shared\n  location (locks, journals, session markers, live DB rows, **and inherited\n  environment variables**) is an accidental fixture: point it at a temp\n  `HOME`\u002F`ROOT`, inject the value, or `monkeypatch.delenv(\u003CVAR>, raising=False)` in\n  the shared runner when the test asserts the VAR-ABSENT branch. An agent shell\n  commonly exports identity vars (`AGENT_NAME`) — a test that passes `--agent`\n  explicitly still silently depends on the caller NOT exporting one, so it goes\n  green in a bare CI shell and red on a real host. Keep the real-resource assertion\n  as ONE explicitly-labelled case. Clearing unrelated state is the cheapest way to\n  discover tests that were passing by accident.\n  **The same trap fires when the subject reads a WELL-KNOWN HOST PATH, not an env var.**\n  Code that merges several registries (`~\u002F.pi\u002Fagent\u002Fmcp.json`, `~\u002F.claude.json`, the\n  Hermes `config.yaml`) reads the LIVE files even when you substituted the fixture for\n  one of them — the first two failing tests in a new suite both reported the host's\n  real server name from the OTHER registry. A runner that submits fixtures to the\n  subject must neutralise EVERY known path it reads (point them at a non-existent path\n  in the runner's default, opt-in per test for the one under test), or the real files'\n  content bleeds into every fixture.\n- **A fake path standing in for a real resource silently selects the FALLBACK branch.** Pointing the\n  code under test at `\u002Ftmp` (or any path holding no repository, no config, no service) is not a\n  neutral stand-in once the code gains an environment-derived branch: a probe like \"is there a git\n  repo here? a remote? a resolvable base?\" answers NO at that path, so the test that meant to drive\n  the NORMAL path drives the newly added fallback instead — green, and asserting about the wrong\n  branch. It bites hardest immediately after adding such a branch, and it surfaces in several\n  unrelated files at once (the same new predicate was reached by two different suites). Stub the\n  predicate explicitly in every test that describes the normal case (`m._is_fallback = lambda repo:\n  False`), give the fallback its OWN test asserting the fallback-specific behaviour, and name in the\n  docstring which case the file is about — otherwise the next environment branch added reaches in\n  again.\n- **A test that repoints a SHARED module attribute (a module it does not own)\n  must restore it in `finally`.** `setattr(doctor_checks, \"HOME\", tmp)` looks\n  like ordinary fixture setup and is not: the value outlives the test, survives\n  into every later file in the process, and points at a temporary directory the\n  harness then deletes. Every later test that reads that module silently\n  produces nothing. The signature is worth memorising: **the failures appear in a\n  DIFFERENT file from the culprit, and the culprit's own tests are green** — so\n  the file you are staring at is the symptom, not the cause. Restore on the way\n  out whether the body succeeded or raised, and add a regression test in the\n  mutating file asserting the attribute is unchanged after the call.\n  **The same trap fires INSIDE one file, across sections.** A test that installs a stub for\n  section A and never puts the real function back leaves every later section asserting against the\n  stub — and because a stub returns plausible values, the red run points at the code under test\n  instead of at the test (a `None` lock returned by the stub made three \"must still fail closed\"\n  assertions look like the guard had been removed). Save the real attribute before patching and\n  re-install it at the section boundary (`real = m.fn` … `m.fn = real`), or scope the stub to the\n  section that needs it;  when a whole block of assertions fails together in a fresh file, suspect\n  the stub before the code.\n- **POISON the collaborators the unit must NOT touch, rather than only restoring the ones it patches.**\n  Restoring in `finally` protects LATER tests; it does not protect THIS one from depending on an\n  earlier test's teardown, or on a patch it never made. For every module attribute the function under\n  test is not supposed to consult, install a stub that RAISES:\n  ```python\n  def _poison(*a, **k):\n      raise AssertionError(\"must not call the store\u002Frange helpers\")\n  ```\n  Two things come out of it: the test becomes deterministic under any ordering (a leaked or\n  not-yet-restored patch fails LOUDLY and names the offending call instead of returning a plausible\n  value that makes the assertions point at the code under test), and the unit's real dependency set\n  is asserted rather than assumed. Restore EVERY attribute the test set in `finally` — the poisoned\n  ones included, since a poison left behind breaks the next test exactly as a leak does. Prefer a\n  `with`-scoped helper that saves and restores them together when a file has several such tests.\n- **Finding WHICH test pollutes shared state is a pairing search, not a reading\n  exercise.** See `references\u002Forder-dependent-failure-bisect.md` for the recipe\n  — run the victim alone, pair it with each candidate that touches the module,\n  then bisect the failing group — and for what to do when the failure will not\n  reproduce at all.\n- **A test that references a DELIBERATELY-REMOVED symbol is stale, not a bug in the\n  feature.** When a sibling suite fails on a constant that no longer exists in code\n  (e.g. a reviewer-model constant the operator reversed out of existence), the test\n  asserts the OLD contract — rewrite it to assert the CURRENT behavior (default →\n  canonical model; env override → cheaper), do NOT \"repair\" it by re-adding the\n  constant. Re-adding a constant a reversal deleted is how a reverted decision creeps\n  back in. Confirm via `git log -S '\u003Csymbol>' -- \u003Cfile>` that the removal was\n  deliberate before concluding it is stale drain rather than a live regression.\n- **A regression test whose SEED stage fails silently passes trivially — guard the seed\n  before the exercise step.** A rename test that seeded the legacy entry by cloning a key\n  that a prior stage had already deleted died with KeyError, and the assertions that\n  followed passed against the UNSEDED fixture: the check was green without ever exercising\n  the rename. Any multi-stage test where later stages depend on an earlier stage's write\n  must assert the fixture landed (`grep -q '\"key\"' \u003Cfixture>` \u002F `assert marker in\n  fixture`) between seed and exercise, so a dead seed fails the test instead of passing it\n  for the wrong reason. A check that reads \"PASS\" while its setup raised is a false green,\n  not a flake.\n- **Derive a state-machine test's cases from the module's OWN table, not from your\n  memory of it.** A test that hardcodes \"advance X → completed\" fails when the\n  machine does not allow that edge, and the red run blames the transition instead\n  of the assumption. Read the permitted set out of the module\n  (`for src, allowed in m.VALID_TRANSITIONS.items()`) and drive a pair it actually\n  allows, skipping with a printed reason when there is none — then assert BOTH\n  directions (the permitted edge behaves, the forbidden one is refused) so the\n  so the table, not the fixture, decides what is legal.\n  - **Before adding a helper to a test module, grep it for one that already exists — a hand-rolled\n    duplicate SHADOWS the original, and your new tests silently call the wrong signature.** A second\n    `_run()` added to a suite whose first `_run` is `(*args, env=None)` made three new tests pass a\n    dict positionally: they failed with argument-shaped errors that point at the assertions, not at\n    the helper, so the red run reads like a bug in the code under test. Check first\n    (`grep -n \"^def \" tests\u002Ftest_\u003Cmodule>.py`), then use the existing seam. Read    its semantics too:\n    a helper that merges `{**os.environ, **env}` can ADD or override a variable but cannot REMOVE\n    one, so a VAR-ABSENT branch is only reachable through it by passing an EMPTY value (which a\n    `[[ -n \"$VAR\" ]]` guard treats as unset) — pass a sentinel and the branch you think you are\n    testing is the VAR-SET one.\n- **'The newest \u003Cfile>' is the definition only when it DEFINES the construct.** A guard that\n  reads `_migrations()[-1]` (or any 'latest config \u002F schema \u002F script') fails against a newer\n  file that only USES the thing — a later migration that CALLS a function whose body an\n  earlier one defines. Scan the set for the record that DEFINES the construct, newest-first,\n  and match the exact definition (the function signature, not the file containing a mention),\n  or the guard reads the wrong file and goes red on healthy code.\n- **A 'skip if \u003Clib> not importable' check can be defeated by importable-but-broken libraries\n  under contamination.** `import reportlab` succeeds on a polluted heap while its real\n  dependency (PIL's `_imaging` C extension) fails at build time, so a test that skips only on\n  ImportError runs instead and fails mid-build. Widen the skip to import the ACTUAL dependency\n  the exercised path needs and catch the broken-load exception — the point of the skip is 'the\n  libs are usable here', not 'the top-level name resolves'.\n- **A standalone test that loads its collaborator by path must check it AS A TEST, never at\n  import.** Script-style suites that are each run directly (`python3 tests\u002Ftest_\u003Cname>.py`, no\n  framework) make a module-scope precondition (`if not hasattr(mod, \"fn\"): raise SystemExit(...)`)\n  fatal: the run dies before any test reports, the failure names no test, and a reader — including\n  an automated reviewer of the diff — files it as a crash rather than as a guard, which is the\n  opposite of what a precondition is for. Put the checks in a function the runner reaches FIRST\n  (a name-sorted runner reaches `test_00_preconditions` before any behaviour test) and ASSERT\n  rather than raise: the collaborator exists, it carries the parameters this file calls it with\n  (`inspect.signature`), and any module-level fact the test depends on is real — e.g. the logger it\n  silences is the logger the module actually uses, otherwise the silencing is decorative and test\n  output reaches production state. A genuine import failure stays an import error; a MISSING\n  CAPABILITY becomes a named failing test.\n",{"name":5,"author":24,"license":15,"version":25,"category":26,"metadata":27,"platforms":40,"description":7},"Steadfaste Fleet","1.0.0","software-development",{"hermes":28},{"tags":29,"related_skills":36},[30,31,32,33,34,35],"testing","python","isolation","hermetic","unit-test","seams",[37,38,39],"test-driven-development","codebase-design","survey-before-action",[41,42],"linux","macos","main","9dc0e92c5fa81d4db5292b205716e8ea0c00d10e","skills\u002Fsoftware-development\u002Fhermetic-python-testing",1,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet","steadfaste.com","https:\u002F\u002Fgithub.com\u002Flukemcqueen","AI Architect | Building Hermes Cortex: governed multi-agent AI for autonomous software engineering | Enterprise Tech Consultant","2026-11-14 22:33:34",{"source":8,"skillName":5,"commands":53,"prompt":63,"zipAvailable":64},[54,57,60],{"tool":55,"command":56},"npx","npx skills add lukemcqueen\u002Fsteadfaste-fleet --skill hermetic-python-testing",{"tool":58,"command":59},"bunx","bunx skills add lukemcqueen\u002Fsteadfaste-fleet --skill hermetic-python-testing",{"tool":61,"command":62},"pnpm","pnpm dlx skills add lukemcqueen\u002Fsteadfaste-fleet --skill hermetic-python-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fhermetic-python-testing\u002FSKILL.md",true,[66,72],{"path":67,"resourceType":68,"resourceTypeDesc":69,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Forder-dependent-failure-bisect.md","REFERENCE","参考文档",3076,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fhermetic-python-testing\u002Freferences\u002Forder-dependent-failure-bisect.md",{"path":73,"resourceType":74,"resourceTypeDesc":75,"sizeBytes":76,"sourceHtmlUrl":77},"templates\u002Frun-tests.sh","SCRIPT","脚本",3307,"https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fsoftware-development\u002Fhermetic-python-testing\u002Ftemplates\u002Frun-tests.sh",[79,87,94,101,108,115],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":86},"01M7DXY4G8NSVB59K8B6S2AQNP","macbook-linux-maintenance","Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fmacbook-linux-maintenance\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":86},"01M7DXXYJCXFJ3TGB84ZQ8KFE6","governance-regression-triage","Triage a host's governance issues: what changed.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fgovernance-regression-triage\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":86},"01M7DXXSAP1G8FDRJAMXQGBBMK","enforcement-immutability","Use when enforcement files lose their immutable flag.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fenforcement-immutability\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":86},"01M78SSDQVRYX64Y16X32TC0NS","steadfaste-fleet-repo-deploy","Use when committing to the steadfaste-fleet repo.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-repo-deploy\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":86},"01M78SS928F3R2RJAYVW4E30CE","steadfaste-fleet-maintenance","Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Fsteadfaste-fleet-maintenance\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":86},"01M78SP1CHW0T0BWE5ZT6JBPX8","fleet-preflight","DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its \"Repo-Specific Pre-Flight\" section covers git search, Hermes boundary, and deployment verification.","https:\u002F\u002Fgithub.com\u002Flukemcqueen\u002Fsteadfaste-fleet\u002Fblob\u002Fmain\u002Fskills\u002Fdevops\u002Ffleet-preflight\u002FSKILL.md",[],[]]