PR #14 adds fr.json and a key-parity test; record the rule so agents write the French string instead of relaxing the test. Co-authored-by: Cursor <cursoragent@cursor.com>
20 KiB
PROJECT_HYGIENE.md - Provenance, Project Context, Development/QA Hygiene, and Learnings
Drop-in operating instructions for coding agents. Read this file before every task.
Working code only. Finish the job. Plausibility is not correctness.
This file follows the AGENTS.md open standard (Linux Foundation / Agentic AI Foundation). Claude Code, Codex, Cursor, Windsurf, Copilot, Aider, Devin, Amp read it natively. For tools that look elsewhere, symlink:
ln -s AGENTS.md CLAUDE.md
ln -s AGENTS.md GEMINI.md
0. Non-negotiables
These rules override everything else in this file when in conflict:
- No flattery, no filler. Skip openers like "Great question", "You're absolutely right", "Excellent idea", "I'd be happy to". Start with the answer or the action.
- Disagree when you disagree. If the user's premise is wrong, say so before doing the work. Agreeing with false premises to be polite is the single worst failure mode in coding agents.
- Never fabricate. Not file paths, not commit hashes, not API names, not test results, not library functions. If you don't know, read the file, run the command, or say "I don't know, let me check."
- Stop when confused. If the task has two plausible interpretations, ask. Do not pick silently and proceed.
- Touch only what you must. Every changed line must trace directly to the user's request. No drive-by refactors, reformatting, or "while I was in there" cleanups.
1. Before writing code
Goal: understand the problem and the codebase before producing a diff.
- State your plan in one or two sentences before editing. For anything non-trivial, produce a numbered list of steps with a verification check for each.
- Read the files you will touch. Read the files that call the files you will touch. Claude Code: use subagents for exploration so the main context stays clean.
- Match existing patterns in the codebase. If the project uses pattern X, use pattern X, even if you'd do it differently in a greenfield repo.
- Surface assumptions out loud: "I'm assuming you want X, Y, Z. If that's wrong, say so." Do not bury assumptions inside the implementation.
- If two approaches exist, present both with tradeoffs. Do not pick one silently. Exception: trivial tasks (typo, rename, log line) where the diff fits in one sentence.
2. Writing code: simplicity first
Goal: the minimum code that solves the stated problem. Nothing speculative.
- No features beyond what was asked.
- No abstractions for single-use code. No configurability, flexibility, or hooks that were not requested.
- No error handling for impossible scenarios. Handle the failures that can actually happen.
- If the solution runs 200 lines and could be 50, rewrite it before showing it.
- If you find yourself adding "for future extensibility", stop. Future extensibility is a future decision.
- Bias toward deleting code over adding code. Shipping less is almost always better.
The test: would a senior engineer reading the diff call this overcomplicated? If yes, simplify.
3. Surgical changes
Goal: clean, reviewable diffs. Change only what the request requires.
- Do not "improve" adjacent code, comments, formatting, or imports that are not part of the task.
- Do not refactor code that works just because you are in the file.
- Do not delete pre-existing dead code unless asked. If you notice it, mention it in the summary.
- Do clean up orphans created by your own changes (unused imports, variables, functions your edit made obsolete).
- Match the project's existing style exactly: indentation, quotes, naming, file layout.
The test: every changed line traces directly to the user's request. If a line fails that test, revert it.
4. Goal-driven execution
Goal: define success as something you can verify, then loop until verified.
Rewrite vague asks into verifiable goals before starting:
- "Add validation" becomes "Write tests for invalid inputs (empty, malformed, oversized), then make them pass."
- "Fix the bug" becomes "Write a failing test that reproduces the reported symptom, then make it pass."
- "Refactor X" becomes "Ensure the existing test suite passes before and after, and no public API changes."
- "Make it faster" becomes "Benchmark the current hot path, identify the bottleneck with profiling, change it, show the benchmark is faster."
For every task:
- State the success criteria before writing code.
- Write the verification (test, script, benchmark, screenshot diff) where practical.
- Run the verification. Read the output. Do not claim success without checking.
- If the verification fails, fix the cause, not the test.
5. Tool use and verification
- Prefer running the code to guessing about the code. If a test suite exists, run it. If a linter exists, run it. If a type checker exists, run it.
- Never report "done" based on a plausible-looking diff alone. Plausibility is not correctness.
- When debugging, address root causes, not symptoms. Suppressing the error is not fixing the error.
- For UI changes, verify visually: screenshot before, screenshot after, describe the diff.
- Use CLI tools (gh, aws, gcloud, kubectl) when they exist. They are more context-efficient than reading docs or hitting APIs unauthenticated.
- When reading logs, errors, or stack traces, read the whole thing. Half-read traces produce wrong fixes.
6. Session hygiene
- Context is the constraint. Long sessions with accumulated failed attempts perform worse than fresh sessions with a better prompt.
- After two failed corrections on the same issue, stop. Summarize what you learned and ask the user to reset the session with a sharper prompt.
- Use subagents (Claude Code: "use subagents to investigate X") for exploration tasks that would otherwise pollute the main context with dozens of file reads.
- When committing, write descriptive commit messages (subject under 72 chars, body explains the why). No "update file" or "fix bug" commits. No "Co-Authored-By: Claude" attribution unless the project explicitly wants it.
7. Communication style
- Direct, not diplomatic. "This won't scale because X" beats "That's an interesting approach, but have you considered...".
- Concise by default. Two or three short paragraphs unless the user asks for depth. No padding, no restating the question, no ceremonial closings.
- When a question has a clear answer, give it. When it does not, say so and give your best read on the tradeoffs.
- Celebrate only what matters: shipping, solving genuinely hard problems, metrics that moved. Not feature ideas, not scope creep, not "wouldn't it be cool if".
- No excessive bullet points, no unprompted headers, no emoji. Prose is usually clearer than structure for short answers.
8. When to ask, when to proceed
Ask before proceeding when:
- The request has two plausible interpretations and the choice materially affects the output.
- The change touches something you've been told is load-bearing, versioned, or has a migration path.
- You need a credential, a secret, or a production resource you don't have access to.
- The user's stated goal and the literal request appear to conflict.
Proceed without asking when:
- The task is trivial and reversible (typo, rename a local variable, add a log line).
- The ambiguity can be resolved by reading the code or running a command.
- The user has already answered the question once in this session.
9. Self-improvement loop
This file is living. Keep it short by keeping it honest.
After every session where the agent did something wrong:
- Ask: was the mistake because this file lacks a rule, or because the agent ignored a rule?
- If lacking: add the rule under "Project Learnings" below, written as concretely as possible ("Always use X for Y" not "be careful with Y").
- If ignored: the rule may be too long, too vague, or buried. Tighten it or move it up.
- Every few weeks, prune. For each line, ask: "Would removing this cause the agent to make a mistake?" If no, delete. Bloated AGENTS.md files get ignored wholesale.
Boris Cherny (creator of Claude Code) keeps his team's file around 100 lines. Under 300 is a good ceiling. Over 500 and you are fighting your own config.
10. Project context
Fill this in per project. Keep it specific. Delete sections that don't apply.
Stack
- Language and version:
- Framework(s):
- Package manager:
- Runtime / deployment target:
Commands
- Install:
TODO - Build:
TODO - Test (all):
TODO - Test (single file):
TODO - Lint:
TODO - Typecheck:
TODO - Run locally:
TODO
Prefer single-file or single-test runs during iteration. Full suites are for the final verification pass.
Layout
- Source lives in:
TODO - Tests live in:
TODO - Do not modify:
TODO(generated code, vendored deps, legacy areas)
Conventions specific to this repo
- Naming:
TODO - Import style:
TODO - Error handling pattern:
TODO - Testing pattern and framework:
TODO
Forbidden
TODO: things that look reasonable but will break this project.
11. Project Learnings
Accumulated corrections. This section is for the agent to maintain, not just the human.
When the user corrects your approach, append a one-line rule here before ending the session. Write it concretely ("Always use X for Y"), never abstractly ("be careful with Y"). If an existing line already covers the correction, tighten it instead of adding a new one. Remove lines when the underlying issue goes away (model upgrades, refactors, process changes).
numberOfPoursSinceStartupresets to 0 on a machine power cycle (confirmed 2026-06-01: power-cycled the machine at pours=16, reloaded the integration, Pours read 0). It counts since machine startup, NOT since keg insertion. Do not base keg-change detection on the pour counter — a power cycle (outage, unplug, firmware update) would false-trigger it.kegVolume(Keg Remaining) was confirmed unchanged across the same power cycle/reload, so a power cycle produces no spurious volume jump — volume-jump signals (b/c) and the manual button are the power-cycle-safe detectors; prefer them.- TODO — verification debt, do this when the next keg is fitted: confirm the keg-freshness baseline survives a reauth.
fix-reauth-flow(archived 2026-09-06) was verified on-device for the reauth flow itself, but the machine had no keg in the tap, so there was no freshness countdown to preserve and task 6.6 could not be checked. The fix usesasync_update_reload_and_abort, which reloads the config entry — the exact moment aRestoreEntitybaseline could be lost. After the next keg change, trigger a reauth (or reload the integration) and confirm Keg Freshness keeps its countdown instead of resetting to unknown. If it resets, that is a real regression inPerfectDraftKegFreshnessSensor's restore path, not in the config flow. - Never add a non-numeric key to
keg_catalog.json._load_keg_cataloginsensor.pybuilds{int(k): v for k, v in raw.items()}and catchesValueErrorby returning{}. A single_metaor_sourcekey therefore disables the entire catalog — every keg reports no name — and says so only at debug level. Recording provenance or attribution inside that file requires changing the loader first.tests/test_keg_catalog.py::test_keys_are_numericguards this. - Every UI string change needs English and French (since 0.4.6, 2026-11-07). When you add, rename or remove a key in
strings.json, make the same change totranslations/en.jsonandtranslations/fr.jsonin the same commit, keeping each{placeholder}name. Write a real French string: no English placeholder, and do not relaxtests/test_translations.py, which fails on any key mismatch. The maintainer chose strict parity over Home Assistant's English fallback so French never silently falls behind. Keep button and entity names short; they display in narrow UI space. - A new integration catalog ID is not done until the card maps it. The companion card joins on
kegIdagainstscripts/keg-catalog.reference.json. Adding a row tokeg_catalog.jsonwithout binding the card entry (and re-syncing that snapshot) ships a named Keg sensor that the card still treats as unknown. The card may already have the beer under a slug with nokegId— check before adding a duplicate entry. - TODO — verification debt from
backport-keg-catalog(archived 2026-09-06), clear this after installing v0.3.2 via HACS: confirm theKegsensor still resolves the fitted keg. The catalog file was replaced wholesale (86 → 114 entries) and verified statically only: exact diff shape, 114 int keys through the loader, and format guards intests/test_keg_catalog.py. What was never exercised is the live path. On-device checks were impossible at the time — no HA on the dev host, and.credentials.json's refresh token had expired (NotAuthorizedException: Refresh Token has expired), so eventest_harness.pycould not reach the API. Task group 5 in the archived change lists the four checks. test_harness.pyis stale: it readsuser_idfrom.credentials.json, which now holdsemail/access_token/id_token/refresh_token. It exits before doing anything useful. Fix the key names (and refresh the token per the README's reCAPTCHA step) before relying on it.- All five files in
openspec/specs/failopenspec validate --specsfor a missing## Purposesection. Pre-existing and repo-wide as of 2026-09-06, so a failing spec validation is not necessarily caused by your change — check whether the error is only the Purpose one before chasing it. - TODO — verification debt from
fix-cognito-signin(v0.4.4 shipped without on-device checks, maintainer decision 2026-11-07). The Cognito direct sign-in was verified only by the automated suite (stdlib API tests and pytest config-flow tests) and the README token was checked in Firefox and Chromium; no sign-in reached the live service from Home Assistant. When there is time for a reinstall: (1) add the integration from scratch with a README token and confirm sensors populate; (2) a wrong password must return to the email/password form withinvalid_credentialsand Cognito's reason, and a token older than 2 minutes must stay on the token step withtoken_rejected; (3) trigger a reauth and confirm it succeeds (with a keg fitted, this also clears the Keg Freshness TODO above). Details in the archived change'stasks.md, section "Deferred". - TODO — verification debt from
add-keg-48180andadd-oktoberfest-keg-art(card 0.4.4 and 0.4.5 shipped without on-device checks, maintainer decisions 2026-11-07). Do it together with thefix-cognito-signinchecks above, on integration and card 0.4.5 or later: confirm the card editor's beer picker shows artwork for Camden Stout, Löwenbräu Oktoberfestbier and Spaten Oktoberfestbier, and that the two Oktoberfest images are sharp in theherolayout. With a 48180 keg fitted, confirm the Keg sensor reads "Camden Stout" and the card brands it. With a 29745 keg fitted, the sensor must read "Löwenbräu Oktoberfestbier" (with umlauts). - TODO — main specs fail
openspec validate --specs --strict(all 5, pre-existing; seen 2026-11-07). None ofopenspec/specs/*/spec.mdhas the## Purpose/## Requirementsheaders the current CLI requires; requirements start directly at### Requirement:. Archiving still works, but sync tooling and validation expect the headers. Fix in one housekeeping commit: add a short## Purposeand a## Requirementsheading to each spec, then re-run strict validation. - TODO — own OpenSpec change: persist Cognito-refreshed tokens back to the config entry.
PerfectDraftApiClient.refresh_access_token()updates_access_token/_id_tokenin memory only, so every HA restart reloads the stale access token and burns a wasted 401-plus-refresh round trip before the first successful poll. Harmless today because the refresh token is what actually gates reauth and Cognito'sREFRESH_TOKEN_AUTHnever issues a new one, so nothing is lost — just wasteful. Deferred out offix-reauth-flowto keep that diff surgical. - TODO — housekeeping, after
fix-cognito-signin/add-keg-48180ship: take the GitHub token out of thegithubremote URLs in both this repo andHassio-PerfectDraftPro-Component. Not a leak (never committed;.git/is untracked), butgit remote -vprints it. Order matters: first changecredential.helperto an absolute path (store --file=/home/rick/Lab/Dev/<repo>/.git/credentials) — the current relative.git/credentialsresolves against the worktree root, where.gitis a file, so pushes from.worktree/<topic>only reachgithub(whose URL carries the token); pushing tooriginfrom a worktree fails with "unable to open .git/credentials: Not a directory". Until fixed, push agent branches from the main checkout:git push origin agent/<topic>(no branch switch needed). Then strip the URL, rungit ls-remote githubfrom a worktree to prove auth, and update theAGENTS.mdhelper command to the absolute form. - Config-flow tests run in
.venv-test(main checkout) on the system Python 3.14 withpytest-homeassistant-custom-component==0.13.375(core 2026.10.4). Run them from a worktree as../../.venv-test/bin/pytest tests/. Do not pin a harness that needs Python 3.12: there is no 3.12 and no C compiler on the dev host, so old numpy cannot build. - DevTools
copy()cannot copy an async result in any browser. Chromium removescopyonce the typed command returns (undefinedin.then/afterawait); Firefox'scopy()only sets ahelperResultread when evaluation returns, so a later call silently copies nothing — and a capturedcopyreference "works" in Chromium tests while failing in Firefox. Do not useprompt(msg, value)either: Chromium cuts the default value off at 2,000 chars, and reCAPTCHA tokens are ~2,450–2,700. For user-facing snippets, keep one command that adds a page button whose click callsnavigator.clipboard.writeText(value). Test console snippets in Firefox too, not only via CDP/Chromium. - Cursor's embedded browser replaces
alert/confirm/promptwith logging stubs ([CursorBrowser] Dialog suppressed, history inwindow.__cursorDialogConfig.dialogHistory). A missing dialog there says nothing about real browsers; read the history to check the arguments, and have a human check the native dialog. - Version numbering (since 0.4.4, 2026-11-07): integration and card share major.minor; patch may diverge. A fix to one package bumps only its patch (card 0.4.5 next to integration 0.4.4); a joint release brings both to the same number again. Never use letter suffixes (
0.4.4b): HACS (PEP 440) and npm (SemVer) treat them as pre-releases that sort before 0.4.4, so HACS would not offer the update. ghis not installed; use the GitHub REST API withcurl. Get the token withprintf 'protocol=https\nhost=github.com\n\n' | git credential fill. The token is fine-grained: since 2026-11-07 it has Issues and Pull requests read/write in addition to admin/push. A403 Resource not accessible by personal access tokenmeans a permission is missing on the token, not a bad token.- TODO — own OpenSpec change + release: remove pour-count-based keg detection from
PerfectDraftKegFreshnessSensorinsensor.py: trigger (a)pours == 0 && kegVolume > 5.5 && last_pours != 0, plus the_last_poursfield and its restore/exposure/rebaseline. It can false-fire on a power cycle while the keg is above ~92% full, and adds nothing the volume triggers (b/c) and the Mark Keg Changed button don't already cover.
12. How this file was built
This boilerplate synthesizes:
- Sean Donahoe's IJFW ("It Just F*cking Works") principles: one install, working code, no ceremony.
- Andrej Karpathy's observations on LLM coding pitfalls (the four principles: think-first, simplicity, surgical changes, goal-driven execution).
- Boris Cherny's public Claude Code workflow (reactive pruning, keep it ~100 lines, only rules that fix real mistakes).
- Anthropic's official Claude Code best practices (explore-plan-code-commit, verification loops, context as the scarce resource).
- Community anti-sycophancy patterns (explicit banned phrases, direct-not-diplomatic).
- The AGENTS.md open standard (cross-tool portability via symlinks).
Read once. Edit sections 10 and 11 for your project. Prune the rest over time. This file gets better the more you use it.