Code Conventions
[[[appendices.code-conventions]]]
Overview
[[[appendices.code-conventions#overview]]]
Conventions for writing code and docs in this repo, for any contributor — not just Claude Code sessions.
CLAUDE.md at the repo root covers how to work with the AI assistant; this page covers how the codebase
itself is written.
1. Python
[[[appendices.code-conventions#python]]]
- Imports: relative within a package's library code (
from .field import Field); absolute only in tests and the app's entry file (from rehuco_agent.fields.field import Field). Relative keeps intra-package imports stable when a package is published or moved between depths. The codebase is mid-migration to this rule; therehuco-coresweep is a follow-up. - Module filenames: match their main class (
rehu_document.py→RehuDocument,field_registry.py→FieldRegistry), unless the file deliberately groups several related classes (properties.py→TypedProperty+SimpleProperty,fields/field.py→Field+FieldBinding+FieldModel). - Visibility: public or private (
__); no protected (_) unless the class is designed for inheritance. This holds at module level too — no_-prefixed module globals or classes. A helper used by only one class belongs inside that class (a__-private member, or a public classmethod if it's API — even the sentinel-in-signature case works, verified against 3.14's lazy annotations); anything that must stay at module level is a plain public name, kept out of the package API by what the package__init__exports (name mangling doesn't exist outside a class body, so a module-level_would be convention-only anyway). - Constants:
Finalwithout an explicit type when it can be inferred. - Naming: don't bake development-methodology/process labels into identifiers (e.g. a bare
TRACER_prefix naming a constant after "this was built during the tracer-bullet slice") — that context rots once the slice ends; put it in a docstring, not the name. - Overrides:
@overrideon every method that overrides a base-class method. - Docstrings: Sphinx-style on all functions, including private ones — one-line summary +
:param:/:returns:/:raises:as needed; no multi-paragraph docstrings for routine code. Closing"""on its own line for multi-line docstrings, on the same line for single-line ones. Constructor:param:entries go on the class docstring (IDE hover shows them);__init__gets no docstring. - Comments: only when the why is non-obvious (hidden constraint, subtle invariant, bug workaround). No narration of what the code does.
- Line length: 120 (ruff enforced).
- Size caps: a source module past a pylint cap splits along a cohesive seam (
RootsChecksumVerbs,RootsRowActions), never by inlining or a pragma; a pragma is right only for a module that is one cohesive thing (CatalogCache), and says why.too-many-localsis cured by a helper. A test module past 1000 lines is split, importing helpers from its sibling (#457, #458, #469, #395).
2. PySide6 UI
[[[appendices.code-conventions#pyside-ui]]]
- Window/widget layouts live in
.uifiles, not built up in Python. For a custom widget, prefer a.uitoo, unless it's trivial (simple layout, or the class only overrides/adds behavior on an existing widget rather than composing a new layout). - Collocate a
.uiwith its controller class:foo_widget.ui,foo_widget.pynext to each other; the generatedfoo_widget_ui.pyis gitignored and rebuilt viamake uis— never hand-edit it. - A custom widget used inside a
.uiis placed as a base/QWidgetplaceholder and promoted to the real class, not embedded as literal custom XML. - Assets go through
.qrc. Icons are authored in an Affinity Designer master file and exported as.svg;make qrcsregenerates the gitignored_rc.py. A.uireferencing a qrc-managed resource (e.g.windowIcon) must declare<resources><include location="....qrc"/></resources>somake uisemits the matching resource import — verify the generated file after adding one. - Ask before adding a new asset-conversion pipeline (e.g. deriving
.icofrom the.svgmaster) rather than improvising one inline. - Every property/attribute in a
.uifile must be one Qt Designer's own Property Editor can display and edit. Don't hand-add XML that's schema-valid and works at runtime but isn't something Designer surfaces — a developer opening the file in Designer needs to be able to find and change it there. Anything Designer can't set belongs in the controller class's Python code aftersetupUi(), not in the.ui. - Name widgets in
.uifilessnake_case, not Qt Designer's defaultcamelCase— this is a recommendation, not a hard rule; usecamelCasewhere justified (e.g. overriding a name Qt itself expects). A widget name that's already a single dictionary word a spell checker recognizes (checkbox,toolbar) doesn't need splitting; a compound default that isn't a real single word (centralwidget,statusbar,menubar) becomescentral_widget,status_bar,menu_bar. - A new list or tree looks like the others (#572):
RowBandDelegate,BandTreeView,allColumnsShowFocusoff, a header when it has columns,QtAdsTitleBarActionVisibilitywhere title-bar actions hide. Seed its tests with every record shape: a standalone.rehu's content key is the extension alone (.mp4), its name the file's stem.
Command surfaces
[[[appendices.code-conventions#command-surfaces]]]
A command can be reached from several places; each has one job.
- The menu bar is the complete index. Every command is in a menu, whatever else shows it, so a command is findable without knowing which widget owns it.
- A button goes at the narrowest widget containing everything it affects. Scan affects every browser of a
catalog, so it is on the catalog shell's toolbar; Add Roots and Remove Root affect only the Roots view, so
they are on its sub-dock's title bar (
CDockWidget.setTitleBarActions). A command on one item — a root, a row — goes on that item's context menu. - A sub-dock earns a toolbar only past about three frequent actions. Up to that, its title-bar actions are enough.
- One
QActionserves every surface, so enabled state, text and shortcut are decided once, by the widget that owns it.
Worker threads
[[[appendices.code-conventions#worker-threads]]]
Two kinds of background work, two kinds of thread. The reasoning, and the measurements behind it, are in the module
docstring of borco_core.path_presence — read it there, where the code is.
- Bounded work whose answer goes back to a widget runs on a
QThreadPool(QThreadPool.globalInstance(), aQRunnableposting its answer, judged on the GUI thread so a stale one is dropped — [[appendices.task-queue#serial]] explains why the task queue is not one). This is the default, and nearly all of the agent's background work. - Work that can block on storage or a network the app does not control, and so must never hold up quitting, runs on
a Python
threading.Thread(daemon=True)with athreading.Eventto stop it. Qt joins its pools at exit, so a worker stuck in a call to a switched-off server keeps the process alive for as long as the call takes (21 s measured for an SMB host); a daemon thread is simply left behind. Nothing is killed:QThread.terminate()is unsafe, and aQThreaddestroyed while running aborts the process. - A pool job never lets a reader's exception escape (#480): the pool swallows it and no answer ever arrives. Catch broadly with a reasoned pragma, log it, and answer unreadable.
- A pool job answers through
PoolRelay, never by emitting on its owner. The GUI thread can delete the owner (a document closed mid-listing) while the pool thread is inside the emit, which crashes the process; atry/except RuntimeErroraround the emit catches only an owner deleted before it.PoolRelay.instance()is taken on the GUI thread, handed to the job, and the job callsrelay.post(owner, self.__deliver, ...): the relay is the application's child, so it outlives every job, and it makes the call on the GUI thread only while the owner is still valid. Hand it a plain bound method, notself.signal.emit, which touches the owner on the pool thread. - A worker holds the GIL inside every Qt call PySide does not release it for, so it never makes one that can take a
signal-slot mutex (#529). A
QImageReaderleft to find its format asks every plugin to look at the bytes, and the SVG plugin's look connects a signal, so a reader on a pool thread is aformat_reader, told its format up front with detection off. So noQMediaPlayeron a worker (#522): PySide holds the GIL across its constructor, which connects the backend's signals (#653, PYSIDE-3513); a player has to live on the GUI thread, which is what made a Qt Multimedia duration probe not worth its keep ([[appendices.post-mortem#ui-and-deployment]]). - Qt's own threads can wait for the GIL under a signal-slot mutex too (#573, #654, PYSIDE-3514): Qt Multimedia's FFmpeg
backend destroys, on a thread of its own, objects it had connected to the Python-built
QAudioOutput, and the output's wrapper asks for the GIL the first time that happens to it (PySide caches the answer per object). The GUI thread deadlocks against it in any call that takes a signal-slot mutex with the GIL held: a connection, theQMediaPlayerconstructor,setAudioOutput. No rule of ours keeps Qt's thread away, so the rules keep the moments few. A player keeps oneQAudioOutputfor its life, changed withsetDeviceandsetVolume, never replaced, and an engine is not built anew where the one built will do (PlayerEnginekeeps Qt's while it stands in for an unusable VLC). And aQToolButtonnever holds an action that changes: its default action is applied again, with a new connection, at every change of icon or text, so the player's buttons are connected once (clicked→trigger) and copy what the action shows. - A
QObjectgets a parent, usuallyself, or an explicit delete (#529). One held only in an attribute, once in a reference cycle, is destroyed by the cyclic collector on whichever thread allocates next, and on a pool thread~QObjecttakes a signal-slot mutex and then waits for the GIL the GUI thread may hold. With no natural parent, the owner deletes it when done (FieldsForm.delete_later,LogBridge.close,ScraperExecutor.shutdown); a test hands what it builds bare to thedelete_at_teardownfixture. - Work that runs again and again reports through one
QObjectits caller owns, never one per run (#529): a per-run child stays on its parent until the parent goes — a leak in an app that runs for days, on a node for weeks — and deleting each after it relayed proved fragile.ScrapeJob.Relaycarries every job's outcome with the job as its first argument; a page reuses onePersonaAction; a measurement's runner is its row's child. - A daemon thread holds no Qt object and delivers nothing after
stop(). Its callback runs on its own thread and only emits a signal, which Qt queues to the GUI thread; the owner stops it first thing when the window closes. - Building many objects on a worker pauses the cyclic collector (#455, #500) — and only for that build, never
gc.freeze(). - First users: the task queue's worker ([[appendices.task-queue#teardown]], daemon for the same reason) and
borco_core.PresenceScan(#464). - The queue never calls an idle job it cancels or removes: one that left something behind has
abandon()(AbandonableTaskJob, #339). A rename through the barrier runs on the GUI thread, since the player's listener is a widget: a job hands it over byRecordMoveHost.run_step, holding no lock while it waits.
Qt and PySide behavior
[[[appendices.code-conventions#qt-behavior]]]
Facts about Qt and PySide that cost time to find, beyond the thread rules above. QtAds' own are in [[appendices.qt-ads]]; driving these in tests, in [[appendices.testing#offscreen-qt]].
- Never keep the wrapper of an object Qt owns when its parent can hand it back (#459, #488): read it per use; delete
a child menu in a
finallyaroundexec; walk a widget's own descendants, notnextInFocusChain()(#487). - Deletion (#529, #479): a queued signal to a Python callable posts to PySide's receiver — make the sender its own
(
LogBridge.Marshaler); a deletedQObject's signals and methods raiseRuntimeError; aQObjectkept alive only by its children's closures deletes itself mid-destruction;destroyedfires parent first — closures hold a token. A form keeping strong references to the widgets its grids own leaves the model's receivers doubled after a teardown (test_a_teardown_lets_go_of_every_model_connection): holdweakref.ref(#568). A host-parentedQActiona document's sub-docks make is deleted in theirteardown, or a preview leaks one per document switch (#505). - A base class's
__slot outlives its widget on PySide 6.11 (#574, #659, PYSIDE-3376, fixed in 6.12.0): a name-mangled method (self.__on_tick) a base class connects for a subclass instance keeps being called on the deleted widget ("already deleted"), andsender()readsNonein it. A@Slotdoes not help; a public name, or the method on the widget's own class, does.OverlaySurfacekeeps theQMetaObject.Connectionhandles and disconnects them on close and ondestroyed, a no-op the second time; that goes with the move to 6.12 (#525). - Mask modifiers through
.valueon Python 3.14 (#575, #660, PYSIDE-3507): on Windows~of aQt.KeyboardModifierkeeps only the bits below that member, somodifiers & ~ShiftModifierdrops Ctrl. WriteQt.KeyboardModifier(modifiers.value & ~ShiftModifier.value)(player_panel_keys); that goes with the move to Python 3.15 (#525). - Qt Multimedia (#574):
QMediaPlayer.setPositionreports its target throughpositionChangedbefore it returns, about 110 ms ahead of any frame of it, and a frame from before the seek can still arrive meanwhile. AQVideoWidgetkeeps drawing a frame set on its sink after the player that decoded it let the file go, GPU (RhiTextureHandle) frames included, and after a resize. - Signals: a signal-blocked
setTexthides the clear button, which emitstextEdited— a debounce connectstextChanged(#406); pressing aQToolButtonin a QtAds dock moves the focus to the dock's scroll area, so a field'seditingFinishedfires before the button's action — a test patchinghasFocushides it (#514); trace real connection order (#376); state kept by a signal is as reliable as its quietest listener — compute at paint time (#304, #457); afocusChangedconnection outlives its widget (#387). - Rows: filtering the current row out of a proxy drops the current index (#344); Qt moves it inside
rowsAboutToBeRemoved— defer withQTimer.singleShot(0, self, ...)(#387). - Sizing: never from geometry before the first layout —
sizeHint()(#377); a pane's minimum width must not follow its content (#457);isHidden()is the widget's own flag —isVisibleTo(ancestor)(#458); a widget made after its parent was shown stays hidden untilshow(); an unshownElidedLabelreads…(#378). - Widgets:
QColumnView—createColumnfor a delegate,setFixedWidth(0)for the preview (#378); aQToolButtonmirrors its action but not its font; aStrEnumitem comes backstr;applicationDisplayName()falls back toapplicationName()(#412);QStatusBar.addPermanentWidgetappends rightward; the agent's conftest makesNodeHost.start_latera no-op, so a host test arms the real one, kept at import (#506; #661:QTimer.singleShot(ms, receiver, callable)fires), and its callable is a method of the receiver, apartialor a lambda, never a method of a plain object nothing else holds, which is called freed (#671, PYSIDE-3517);CDockManagerworks under a plain widget (#498). A row removed from a layout anddeleteLater-ed is gone by the next wait — testshiboken6.isValid, notisVisible(#505). - Menus: a
QWidgetActionrow owns its columns — raisemaxIconWidth(#465); anaboutToShowtail keeps oneQActionGroup(#402); a card list marks its current card by its buttons alone (#463). - Drag routing (#387, #461, #485): a drag belongs to the widget that accepted its enter; a disabled widget gets
none; an ignored enter hands the drag to the nearest accepting ancestor, so a filter that ignores a link passes it
on and forwarding by hand delivers it twice (#567); a test link carries its
text/plaintoo, or aQLineEditdeclines it anyway; browsers end UTF-16text/x-moz-urlwith a NUL; aQListViewreorder ([[appendices.testing#offscreen-qt]]). - A custom delegate on Windows (#383): editor on
option.rect; nothing painted under it;HighlightedText. SimplePropertykeepsnameas_Class__name(#497): a private method__nameon the same class silently takes its place — the banner read a bound method as its text.- Settings blocks (#508): exact
QFramedirect children in child order; a platform's blocks areQObjectcontrollerssetParented beforesetupUi, theninsertWidgeted first. - Dialog traps (#416):
.uiQTableWidgetheaders fail pyright;QDialogButtonBoxorders by role;ScintillaEditeats Esc and shadowssetFocus. A floating QtAds container ignores close — quit on an accepted close (#507). - Glyphs: the Phosphor fonts name their glyphs
uniXXXXonly — render a codepoint to check it (#505:\ue30cis the magnifier). - Layout and sizing: a
QSplittertakes its maximum from its children;heightForWidthis expanded to the minimum (release it before measuring) and is -1 with no text; a framedQLabelindents unlessindentis 0; PySide has noQWIDGETSIZE_MAX. A hidden widget's grid row drops its spacing, a visible empty wrapper keeps it; a field on two viewer tabs returns a row per tab frommake_viewer_rows(#620). A widget shown or hidden from inside a sibling'sresizeEvent, during the parent layout's own pass, asks for a relayout Qt drops, and the parent keeps the old height: queue the change (MessageBanner's more lines line, #709). - Views and editors: a second view over listed rows gets no reset; two
ScintillaEdits share a document bysetDocPointer(#575). A combo item grayed byForegroundRolestays pickable (#618).ItemListEditortakes adelegate=, since a column delegate set later misses itscloseEditor; a class promoted in a.uineeds its own module, or the_uiimport is circular; a settings frame's compound control is aValueControl(#578). - Ownership: a Qt-made object held in an attribute (
addWidget's,addSeparator's action) is made in Python instead (4ad99fa, #630); one Qt replaces (QColumnView's preview column) is looked up each time (#570). Focus given to an off-screen widget crashed Qt once its document closed (#631). A child of a background tab is not hidden, only not visible, so "on screen" isisVisible(). - Painting:
ElidedLabelre-sets its tooltip on every resize, so passtooltip=(#639); it never makes the full text a tooltip, which for a long value covers half the screen (#709). AQLabelpixmap does not follow the palette: build it fromrecolored_svg_icon, and redraw onPaletteChangeandEnabledChange(#649). QTextLayout(#700): aQTextLineis a view of its layout, so a line taken from a temporary one (make_layout().lineAt(0)) is used freed and crashes the process: hold the layout in a name for as long as its lines are read. A layout is one paragraph and does not break at\n, whichdrawTextdoes: lay the text out with U+2028 in its place, one character for one, so offsets into the text still hold (LogMessageDelegate). Its line heights are notQFontMetrics' (the leading differs by font), so paint, size and hit-testing read the one layout.- The QtAds stub
typings/PySide6QtAds/__init__.pyilists only the methods the code calls: one pyright calls unknown is added there (#624). - Images beyond Qt (#650): the PySide wheels read no HEIC or AVIF, so
image_sourceroutes both to Pillow (pi-heiffor HEIC, neverpillow-heif, whose x265 is GPL). No HEIC encoder ships, so tests patchImage.open; AVIF tests use real bytes.
3. Markdown
[[[appendices.code-conventions#markdown]]]
Docs under docs/ are markdownlint-checked (.markdownlint.json; MD013 line length 120, tables exempt). Also:
- Blank lines around headings and lists (MD022/MD032); inside a blockquote the separator is an empty
>line, not a truly blank line. - Spaced table delimiter rows —
| --- | --- |— and single-space-padded cells. - No emphasis-as-heading (MD036) — use real
###headings. - By hand: no wrapped line starts with
#NNN— markdownlint reads it as a heading (MD018);awk 'length>120'over-counts lines with em dashes, so measure in characters; compare markdownlint's findings withgit show HEAD:filefirst, so only new ones are yours. - Under a spec section heading, list its GitHub issue(s) as plain list items —
- [#N: title](url)— regardless of whether the issue is open or closed. Deliberately not a- [ ]/- [x]task list: a checkbox has to be ticked in a commit every time an issue closes, which is churn in the specs for state GitHub already tracks authoritatively. The link records which issues a section belongs to; their status is read on GitHub. - Cross-renderer link rendering. Docs are read both on GitHub (blob view, PRs) and the published mkdocs site, which render some references differently:
- A bare
#123issue/PR reference autolinks natively on GitHub already;pymdownx.magiclink(mkdocs.yml) gives it the same treatment on the published site. Its issue-shorthand pattern requires digits right after#, so it never collides with a[[doc#slug]]cross-reference token (slug segments are never all-digit) — see "Symbolic cross-references" indocs/specs/README.md. - A plain relative link from a doc into a repo file outside
docs/(e.g. a.pysource file underpackages/) resolves natively on GitHub, but 404s on the built mkdocs site, since onlydocs/is ever published. Write such links as plain relative paths regardless —tools/mkdocs_relative_link_hook.pyrewrites, at build time only, any link whose target falls outsidedocs_dirto an absolute{repo_url}/blob/{branch}/...link; GitHub needs no change.
4. Testing
[[[appendices.code-conventions#testing]]]
Each test's docstring ends with a **Test steps:** bullet list spelling out the steps and checks, so intent
is readable without tracing the code — a project convention, not a pytest feature. The test stack and
how to drive it are covered in [[appendices.testing#qa-gate]].
5. Design rules
[[[appendices.code-conventions#design-rules]]]
Rules that came out of fixing a bug and hold beyond it, until a spec page takes them.
- Verifying a record is plan (cache) → check (pool) → apply (cache) (#487), dropping a finding something
overtook; a check that must see a rename is asked once
rename_locationreturns, never from amovedslot (#566). - Restored state waits for what it needs, and is saved again unchanged until applied (#576).
- A save compares one shape on both sides, judged against the file (#416).
- A write inside the rename barrier waits less than a rename waits for holders (#512; 2 s).
- A dialog's remembered checkbox saves however it closes (#542).
- A scan's flag is replaced by that root's next scan, never only added to (#498).
- What crosses from a library's threads carries the epoch of its source (#319), dropped on arrival behind a change.
- An optimistic overlay is let go by the write that carried it (#571). A queue that replaces by key keeps the replaced item's place. Waiting on a write that may be replaced listens for the model's signal, never the write's own callback (#573).
- An editor is disabled while what it shows is not safe to edit (#573).
- A value that belongs to the file is read once per file (#574), never re-read on a model signal.
- A choice that outlives one video is kept by meaning, not by id (#618).
- Cached rows go only when the user removes their root (#577): an offline or unreadable root keeps them, grayed.
- A click and the row that previews it read one function (#649:
plan_move), never two copies of the rule. - Read the firewall through its rules (#418):
Get-NetFirewallRule | Get-NetFirewallPortFilter.