Skip to content

Count code lines in check-file-sizes.py, not raw lines and bytes - #3673

Merged
jwbron merged 2 commits into
mainfrom
egg/3671-count-code-lines
Jul 27, 2026
Merged

jwbron merged 2 commits into
mainfrom
egg/3671-count-code-lines

Conversation

@jwbron

@jwbron jwbron commented Jul 27, 2026

Copy link
Copy Markdown
Owner

Closes #3671.

The problem

scripts/check-file-sizes.py counted raw lines and raw bytes, so the cheapest way to bring a file under the hard cap was to delete prose. Not hypothetical: commit 68b185ca ("trim health_monitor.py docstring under file-size hard cap") took orchestrator/health_monitor.py from 1503 to 1498 raw lines across the old 1500 cap by deleting documentation from a ~1400-line supervision module.

The fix

The lint now counts code lines: every physical line that is not blank, not comment-only, and not part of a module/class/function docstring. Docstring spans come from ast.get_docstring over Module / ClassDef / FunctionDef / AsyncFunctionDef; comment-only and blank lines fall out of tokenize.

Both revisions of health_monitor.py measure 767 code lines, so that commit would have bought exactly nothing.

Two carve-outs, both deliberate and documented:

  • Non-docstring multi-line strings still count, otherwise the vector just moves to _DOC = """...""".
  • A file that fails to parse counts everything, so the fallback over-counts rather than under-counts.

The failure message now names the metric it reports and closes the door explicitly:

foo.py: 1050 code lines exceeds hard cap (1000 code lines). Code lines exclude docstrings, comments and blank lines, so deleting documentation will not lower this number. Decompose the file or, if you cannot in this PR, add it to scripts/file-size-allowlist.yaml with a tracking issue.

Caps re-baselined

Measured all 577 source files first. The median code/raw ratio is 0.58 for files over 200 lines.

before after rationale
hard 1500 raw lines 1000 code lines ~1700 raw lines and ~60-90KB at this repo's density, so the ~100KB / 25k-token Read budget the original cap was justified by is preserved rather than loosened. Strictness-neutral by count: 6 files exceed it, the same count that exceeded raw-1500.
soft 800 raw lines 500 code lines Half the hard cap; the old ratio was 0.53. Produces 66 warnings against 77 warning lines before, so no added noise.
bytes 100,000 / 60,000 dropped Raw bytes have the identical gaming property this change removes. A "code bytes" variant would be a redundant proxy for code lines (they correlate almost perfectly here) that no longer maps to the Read-tool byte limit that justified it. And it was non-binding in practice: exactly one file exceeded 100,000 bytes, and it was over the line cap anyway.

The caps keys are renamed hard_lines/soft_lines to hard_code_lines/soft_code_lines. A branch carrying the old schema gets an explicit "rebase onto main" error rather than being silently measured against a cap calibrated for a different metric.

Allowlist re-baselined

Every entry re-checked. Dropped 5 that fall under the cap now that prose is excluded: routes/pipelines/__init__.py (980, #3587), _slice_state.py (818, #3586), slice_green_gate.py (933, #3627), _run_concurrent.py (997, #3650), _run_pipeline.py (945, #3651). Those issues stay open as decomposition follow-ups; the files just no longer need an exemption.

Added 5 prose-light, code-dense modules the raw-line cap never flagged: _prompt_phase.py (1285), _parser.py (1219), _tool_defs.py (1196), _prompt_agent.py (1195), gateway/gateway/__init__.py (1013). These have no tracking issue yet; happy to file decomposition follow-ups if you want them.

A test asserts the checked-in allowlist exactly equals the set of over-cap files, so it cannot drift.

Tests

TestProseCannotLowerTheCount asserts the property the issue is about:

  • stripping every docstring, comment and blank line changes nothing;
  • padding a docstring with 200 lines changes nothing (documenting a module is never penalised);
  • end-to-end via measure(), an over-cap file produces a byte-identical error report before and after its docstring is deleted.

tests/tools/test_select_tests_package_shape.py hardcoded the 1500-line / 100-KB caps; it now reads the cap from the allowlist and measures via the checker itself, so it cannot drift from make lint.

Verification

  • scripts/check-file-sizes.py exits 0; make lint-custom exits 0; ruff and mypy clean.
  • pytest orchestrator/tests -q: 2 failed, 8773 passed, 6 skipped, 1 xfailed in 690s. Both failures (test_production_worktree_base_dir_lies_within_gateway_allowlist, test_probe_skipped_when_request_context_missing) are pre-existing and environmental: they fail identically in a throwaway worktree at unmodified HEAD (05b9110), and this diff touches no module either test imports.

No source file's contents were changed to satisfy the new counting. This PR changes the measuring instrument only; the diff is the checker, its allowlist, tests, and the docs that quoted the old caps.

Closes #3671.

The lint counted raw lines and bytes, so the cheapest way to bring a file
under the hard cap was to delete prose. That is not hypothetical: commit
68b185c ("trim health_monitor.py docstring under file-size hard cap")
took orchestrator/health_monitor.py from 1503 to 1498 raw lines across
the old 1500 cap by deleting documentation from a ~1400-line supervision
module.

Now the lint counts CODE lines: every physical line that is not blank,
not comment-only, and not part of a module/class/function docstring.
Docstring spans come from ast.get_docstring over Module / ClassDef /
FunctionDef / AsyncFunctionDef; comment-only and blank lines fall out of
tokenize. Both revisions of health_monitor.py measure 767 code lines, so
that commit would have bought exactly nothing.

Two carve-outs, both deliberate: non-docstring multi-line strings still
count (otherwise the vector just moves to `_DOC = """..."""`), and a file
that fails to parse counts everything, so the fallback over-counts rather
than under-counts. The failure message now names the metric it reports and
says outright that deleting documentation will not lower the number.

Caps re-baselined against code-line counts. Measured all 577 source
files: the median code/raw ratio is 0.58 for files over 200 lines.

- hard: 1000 code lines (was 1500 raw). At that density 1000 code lines
  is ~1700 raw lines, and at the observed 60-90 bytes per code line it is
  ~60-90KB, still inside the ~100KB / 25k-token Read budget the original
  cap was justified by. Strictness-neutral by count: 6 files exceed it,
  the same count that exceeded raw-1500.
- soft: 500 code lines (was 800 raw), half the hard cap; the old ratio
  was 0.53. Produces 66 warnings against 77 warning lines before.
- byte caps: dropped. Raw bytes have the identical gaming property this
  change removes; a "code bytes" variant would be a redundant proxy for
  code lines that no longer maps to the Read-tool byte limit that
  justified it; and the cap was non-binding in practice (exactly one file
  exceeded 100,000 bytes, and it was over the line cap anyway).

The caps keys are renamed hard_lines/soft_lines -> hard_code_lines/
soft_code_lines. A branch carrying the old schema gets an explicit
"rebase onto main" error rather than being silently measured against a
cap calibrated for a different metric.

Allowlist re-baselined. Five entries dropped now that prose is excluded
(routes/pipelines/__init__.py #3587, _slice_state.py #3586,
slice_green_gate.py #3627, _run_concurrent.py #3650, _run_pipeline.py
#3651; all 818-997 code lines). Those issues stay open as decomposition
follow-ups. Five prose-light, code-dense modules that the raw-line cap
never flagged are added: _prompt_phase.py (1285), _parser.py (1219),
_tool_defs.py (1196), _prompt_agent.py (1195), gateway/gateway/__init__.py
(1013). A test asserts the checked-in allowlist equals the set of over-cap
files, so it cannot drift.

Tests: TestProseCannotLowerTheCount asserts the property the issue is
about. Stripping every docstring, comment and blank line changes nothing;
padding a docstring with 200 lines changes nothing; and end-to-end via
measure(), an over-cap file produces a byte-identical error report before
and after its docstring is deleted.

test_select_tests_package_shape.py hardcoded the 1500-line / 100-KB caps;
it now reads the cap from the allowlist and measures via the checker
itself, so it cannot drift from `make lint`.

No source file's contents were changed to satisfy the new counting. This
commit changes the measuring instrument only.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No agent-mode design concerns. Approving on the agent-mode lens.

Scanned for the anti-patterns this lens covers — pre-fetched context, structured output for human consumers, post-processing pipelines, prompt-level enforcement of hard rules, direct Anthropic API calls, pinned model IDs. None are present; the diff touches a lint script, its allowlist, tests, and the docs that quoted the old caps.

Two things worth noting as aligned, not as findings:

The fix is at the tooling layer, not the prompt layer. The incident behind #3671 is an agent-mode failure — an agent satisfied a lint by deleting documentation (68b185ca). The response here is to make the metric immune to that move rather than to add a "don't delete docstrings" instruction to an agent prompt. That's the core principle in docs/guides/agent-mode-design.md ("the sandbox is the constraint" / "hard rules: enforce technically"). count_code_lines() makes the shortcut a no-op by construction, and TestProseCannotLowerTheCount pins that property rather than a snapshot number.

The Read-budget justification survives the metric change. The cap's original rationale (#2248) is the agent's Read cost, which is a function of raw lines and bytes — so switching to code lines decouples the gate from the thing that justified it. I measured the tree at origin/egg/3671-count-code-lines with the new checker to see whether that decoupling bites in practice:

571 files pass the 1000-code-line cap
  passing files over 100,000 bytes: 0
  passing files over 2,000 raw lines: 0
  largest passing file: 1,671 raw lines / 79,393 bytes

So no file clears the new cap while blowing the Read budget the old byte cap was protecting. The headroom is empirical rather than enforced — a 1000-code-line file with 4,000 lines of docstring would pass — but the PR reasons about that explicitly, and re-adding a byte warning would reintroduce the exact incentive being removed. Correct call as-is.

_prompt_phase.py (1,285) and _prompt_agent.py (1,195) landing on the allowlist is a direct consequence of counting non-docstring multi-line strings as code. That's the right treatment for prompt modules from this lens — an embedded prompt template really is context an agent must load — and I'd rather see them allowlisted with the pressure visible than excluded from the count.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: #3673 — Count code lines in check-file-sizes.py

The premise is right and the execution is unusually well-evidenced: I re-measured every number in the PR body and the allowlist comments and all of them are exact (6/6 entry counts, _prompt_phase.py really is the repo's largest at 1285, exactly one file exceeds 100,000 bytes, and the warning count really does go down). The prose-gaming property is real, the fix targets it correctly, and TestProseCannotLowerTheCount is well-designed — it asserts an invariant between two hand-authored variants rather than pinning implementation output, and test_the_two_versions_differ_in_raw_lines guards the guard.

Three blocking issues, all reproduced below.


Blocking

B1. Dropping the byte cap removes the only bound on a file's actual Read cost, and nothing replaces it

hard_bytes: 100000 / soft_bytes: 60000 enforced a specific invariant: no source file exceeds the Read tool's ~100 KB / 25k-token budget. The module docstring names that budget as the entire reason the check exists ("the Read tool's hard limits ... another LLM turn, and BRC cycles re-pay the cost from a cleared context"). The new code re-establishes nothing equivalent, and the new primary metric deliberately ignores the thing that used to be bounded.

Reproduction — orchestrator/health_monitor.py, module docstring padded with 20,000 prose lines, no code touched:

real health_monitor.py  :   749 code lines,  64,330 bytes
docstring-padded version:   749 code lines, 544,331 bytes (544 KB), 21,473 raw lines

lint errors  : NONE
lint warnings: ['orchestrator/health_monitor.py: 749 code lines exceeds soft cap (500 …']

A 544 KB / 21,473-line file passes the hard cap clean. Pre-PR it was a hard failure at >100,000 bytes. And test_padding_a_docstring_changes_nothing now asserts this as a feature — which is correct for reasonable prose, but with bytes unmeasured it means there is no upper bound at all.

This is not hypothetical for this repo. orchestrator/CLAUDE.md:271 records that routes/pipelines.py reached 30,520 lines / 1.44 MB. Files here genuinely do reach absurd sizes, and the caps are the only thing preventing recurrence. The module docstring itself notes "this repo deliberately invests in prose" — which makes large-docstring growth more likely here, not less.

On the PR's stated rejection of a byte cap. Two arguments are given and I want to engage both directly:

"a 'code bytes' variant would be a redundant proxy for code lines"

Agreed — and that is not what I am asking for. A raw byte backstop is not a proxy for code lines; it is the only thing that measures the quantity the check exists to bound, precisely because the primary metric now ignores unbounded prose.

"raw bytes have the identical gaming property this change removes"

This is the crux, and it holds only for a cap that binds near where real files sit. hard_bytes: 100000 sat at roughly 1.5× a typical file's projected size — that proximity is what created the pressure to trim prose. A backstop set well above the working range does not create that pressure, because no honest file is anywhere near it and nobody trims a docstring to get from 155 KB to 149 KB.

The two caps do different jobs and should coexist: code lines is the design cap (bounds logic density; deleting prose never moves it — the PR's whole thesis, preserved intact), bytes is the pathology backstop (bounds Read cost; only ever fires on a file that has gone genuinely wrong).

Also, the calibration claim is understated. The docstring and file-size-allowlist.yaml:17 both say "at the observed 60-90 bytes per code line it is ~60-90KB — still inside the ~100KB / 25k-token Read budget." Measured across the 217 files with ≥200 code lines:

percentile B/code-line projected at the 1000-line cap
p50 65.4 65 KB
p90 86.1 86 KB
p95 92.6 93 KB
max 155.8 156 KB

"60-90" is a fair description of the bulk but not of the tail, and a cap is sized against the tail. orchestrator/agent_model_resolution.py already runs at 155.8 B/code-line; a file at that density hits ~156 KB at the cap — over the budget the PR claims to preserve, with no docstring padding required at all.

Suggested fix: restore hard_bytes at a deliberately loose value (~150,000) as an explicitly secondary cap, documented as a pathology backstop rather than a design constraint. Keep soft_bytes dropped. This costs the PR nothing — the code-line cap remains the primary gate and the prose-deletion vector stays closed.


B2. --update-allowlist destroys the entire allowlist file's comments — including everything this PR just added

write_allowlist (scripts/check-file-sizes.py:328) does yaml.safe_dump(payload), which emits a fresh document. Reproduction, running update_allowlist() against a copy of the checked-in file:

comment lines before: 45
comment lines after :  0

The resulting file is six bare keys under a caps: block. Gone: the #3671 rationale, the density calibration, the schema documentation, the "dropped five / added five" audit trail, and the per-file code/raw measurement on all 6 entries.

This is pre-existing behavior, but the diff materially amplifies it. Before this PR the header carried the schema plus 4 inline notes; this PR moves the file's entire substance into comments. One invocation of the script's own flag — advertised in main()'s --help (check-file-sizes.py:373-376) and the module docstring's usage block — silently deletes all of it, and the resulting diff looks like an innocuous re-sort.

The PR also locks in the lossy round-trip without noticing the gap: test_write_emits_issue_when_present gains assert loaded["caps"] == {"hard_code_lines": 1000, "soft_code_lines": 500}, so the round-trip is newly under test while the comment loss is not.

Suggested fix: emit the header comments programmatically in write_allowlist, or have --update-allowlist print the proposed change for a human to apply rather than clobbering. At minimum, move the per-entry code/raw counts out of comments into the structured entry (alongside issue:) so they survive the round-trip.


B3. The ratchet does not detect an allowlist entry that has fallen under the cap — and this PR is the proof

check-file-sizes.py:309:

stale = sorted(rel for rel in config.allowlist if rel not in seen)

seen is every source file that exists. A file that exists but is now under the cap is never reported. The allowlist header asserts the opposite, and the diff extends this exact comment block — scripts/file-size-allowlist.yaml:33-34:

"the ratchet flags any allowlisted file that has dropped back under the cap as stale."

It does not. Only --update-allowlist drops such entries, and that is not what make lint runs.

The amplification is concrete and is this PR itself. The re-baseline created five newly-under-cap entries at once — routes/pipelines/__init__.py (980), _slice_state.py (818), slice_green_gate.py (933), _run_concurrent.py (997), _run_pipeline.py (945). make lint reported nothing about any of them. They were removed only because the author re-measured by hand. Left in, all five would have retained an unlimited-growth exemption while sitting comfortably under the cap — the exact ratchet failure the header claims is impossible.

The PR does patch this, but at the test layer (TestLiveAllowlist.test_every_entry_is_still_over_the_cap), not the lint layer. That split is itself a problem: make lint goes green on a stale allowlist while a pytest file in tests/scripts/ fails with a bare set-inequality and no actionable message. Put it where the operator will act on it:

stale = sorted(
    rel
    for rel in config.allowlist
    if rel not in seen or measured.get(rel, 10**9) <= config.caps.hard_code_lines
)

(threading a measured: dict[str, int] out of the loop above), with a message distinguishing "no longer exists" from "now under the cap — remove the exemption."


Non-blocking

N1 — Five new allowlist entries have no issue: field, contradicting both the file's own rule and the checker's own error text. file-size-allowlist.yaml:31-33: "New entries should only be added (with a tracking issue) for files awaiting their own decomposition." check-file-sizes.py:275-276 tells the user to "add it to scripts/file-size-allowlist.yaml with a tracking issue." The five added entries (gateway/gateway/__init__.py, _tool_defs.py, _prompt_agent.py, _prompt_phase.py, _parser.py) have none, so the reference file is the first thing to violate the instruction it hands out. The PR body offers to file them — please do; otherwise these five have no decomposition owner.

N2 — count_code_lines maps splitlines() positions onto tokenizer line numbers; the two disagree. str.splitlines() also splits on \x0b \x0c \x1c \x1d \x1e \x85 
 
; Python's tokenizer does not. Repro: 'X = "a
b"\n# a comment\nY = 2\n' returns 3, correct answer is 2 — and the comment exclusion lands on the wrong physical line because every index after the split is shifted. The direction is always over-count (each extra split adds one counted line, exclusions stay the same size), so it cannot be used to duck the cap, and I verified no file in the repo currently contains these characters. Still, the mapping is unsound. Fix: build the line list the way tokenize does — io.StringIO(source).readlines() — instead of splitlines().

N3 — A docstring sharing a physical line with code silently drops the code. count_code_lines('def f(): """doc"""\n') returns 0 — the whole function vanishes. 'def f():\n """doc"""; x = 1; y = 2\n return x\n' returns 2, not 3. Contrived (a formatter splits these), but it is an undercount in a function whose contract is "prose is free, code is not." Cheap guard: only exclude a docstring's line range when its first and last lines contain nothing but the string.

N4 — Residual gaming vector the docstring does not address. It reasons about _DOC = """...""" (module constant, correctly still counted) but a docstring-position string is unlimited:

def _table():
    """<5000 rows>"""
    return [l.split(",") for l in _table.__doc__.splitlines()]

measures 2 code lines at 5,002 raw lines. Not a realistic agent behaviour, but it is the same shape as the vector the docstring claims to have closed, and with the byte cap gone (B1) nothing else catches it. One sentence in the docstring, or B1's backstop, resolves it.

N5 — orchestrator/CLAUDE.md left stale while its siblings were updated. The PR correctly updates orchestrator/CLAUDE.md:33, gateway/CLAUDE.md:34, sandbox/CLAUDE.md:59 and docs/guides/decomposition-pattern.md, but leaves:

  • orchestrator/CLAUDE.md:271 — "every module under BOTH the 1,500-line and 100 KB caps". Now false: _prompt_agent.py (1195) and _prompt_phase.py (1285) are in that very package and are allowlisted by this PR.
  • orchestrator/CLAUDE.md:284 — "scripts/file-size-allowlist.yaml's files: map is now EMPTY". Contradicted by the 6-entry map this PR ships.

(:284 was already stale on main; :271 is newly false.) Since sandbox/CLAUDE.md:59 got exactly this treatment — a parenthetical noting the #3671 recount — the omission reads as an oversight.

N6 — _load_file_size_checker() re-execs the module on every parametrization. tests/tools/test_select_tests_package_shape.py:188 runs spec.loader.exec_module and rebinds sys.modules["check_file_sizes_shape"] on each of the 6 cases. Hoist to a session-scoped fixture or functools.cache.

N7 — Misleading assertion message. test_submodules_under_hard_size_cap's failure text (line 230) still says "split further or restore the allowlist entry", but the assertion reads the cap only and never consults allowlist membership — restoring an entry cannot make it pass. Pre-existing wording, but the line is being edited here.

N8 — _require_cap validates presence but not value. return int(caps_raw[key]) — hard_code_lines: abc yields a raw ValueError traceback rather than the friendly SystemExit the function exists to provide, and a zero or negative cap is accepted silently. Given the function's stated purpose is "failing with a rebase hint rather than a KeyError", wrap the coercion and range-check too.

N9 — Docstring overstates the unparseable fallback. "everything in a file that fails to parse" isn't quite right: _comment_only_line_numbers still succeeds and excludes comments whenever tokenize survives and only ast.parse fails. The safety property the sentence defends — "a broken file can never measure smaller than a working one" — does hold, since a syntax error only ever removes exclusions. Worth tightening the wording so a future reader doesn't rely on the stronger claim.


Verified clean

Recording what I checked and am explicitly not flagging:

  • except tokenize.TokenError, SyntaxError, ValueError: is correct here. PEP 758, valid on 3.14+. requires-python = ">=3.14", ruff target-version = "py314", mypy python_version = "3.14", and all six CI jobs pin python-version: "3.14". The form is already idiomatic in this repo (wontdo_drain.py:120, redis_message_store.py:108, agent_salvage.py:441, kubernetes_client.py:110, and others).
  • Every number in the allowlist comments is exact — all 6 code/raw pairs verified, and _prompt_phase.py is genuinely the repo's largest code-line count.
  • "66 warnings ... no added noise" holds. I ran the pre-PR checker against this tree: 77 warning lines / 67 distinct files. New: 66 / 66. Net −1 file, so the distinct-file count did not regress.
  • "Exactly one file exceeded 100,000 bytes and it was over the line cap anyway" holds — concurrent_executor.py, 101,146 bytes, 1184 code lines.
  • 65/65 tests pass in the two changed test files; scripts/check-file-sizes.py exits 0.
  • No self-seeding goldens or path-bypassing fixtures. TestLiveAllowlist and test_submodules_under_hard_size_cap both measure through the production measure() / load_config() rather than re-implementing a count — the right call, and a genuine improvement over the hardcoded 1500 / 100_000 the latter replaced.

Per repo convention I did not run make test; CI covers the full suite.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

This comment has been minimized.

…ntry gate

- Restore hard_bytes as a deliberately loose 150,000-byte pathology
  backstop (B1); code lines stay the design cap.
- Make --update-allowlist regenerate the header prose and per-entry
  measurements instead of destroying them; move per-entry rationale
  into a structured note: field (B2).
- Fail the lint on stale allowlist entries -- a file back under the
  caps, or gone -- rather than warning (B3).
- Map docstring spans over physical lines, not splitlines(), and stop
  excluding docstrings that share a line with code (N2, N3).
- Validate caps values are positive integers (N8); document the
  __doc__ payload vector and correct the unparseable-fallback claim
  (N4, N9).
- Cache the file-size-checker module load and fix the misleading
  assertion message in the select_tests shape test (N6, N7).
- Refresh stale cap wording in orchestrator/gateway CLAUDE.md and
  docs/guides/decomposition-pattern.md (N5).
- File tracking issues #3674-#3678 and wire them into the allowlist.
@james-in-a-box

Copy link
Copy Markdown
Contributor

Review response — all 12 items addressed in-PR

Everything below is fixed in commit 660b721. No deferrals.

Blocking

B1 — Dropping the byte cap removes the only bound on Read cost. fixed-in-PR (commit 660b721)

Agreed, and the framing was the thing I got wrong: I removed the byte cap because it was the mechanism that made trimming a docstring rational, when the actual problem was that it sat close enough to real files to bind. hard_bytes: 150000 is back as a pathology backstop, explicitly not a design constraint — the largest healthy file is ~101 KB, so the cap sits ~50% above anything real. That looseness is the whole point and is documented as such in both the script docstring and the allowlist header; there is deliberately no soft byte cap. The error text says so directly, so nobody reads a byte failure as "delete prose":

This cap is a pathology check on what reading the file actually costs, not a prose budget -- it sits far above any healthy file, so trimming documentation is neither the intended fix nor enough of one. Decompose the file [...]

Caps are now hard_code_lines: 1000 / soft_code_lines: 500 / hard_bytes: 150000, and evaluate() trips on either hard cap independently. Coverage in TestByteBackstop: your padded-docstring reproduction (749 lines / 544,331 bytes) now fails, plus at-cap pass, both-caps-tripped, allowlist waiver, and an assertion that no soft byte warning exists.

B2 — --update-allowlist destroys the file's comments. fixed-in-PR (commit 660b721)

Agreed — and this was the most embarrassing one, since the flag would have eaten the rationale the same PR added. Rather than teach the writer to preserve comments, the file is now generated from the script:

  • Header prose lives in _ALLOWLIST_HEADER / _FILES_HEADER module constants and is re-emitted on every write.
  • Per-entry rationale moved out of comments into a structured note: field on AllowlistEntry, so it round-trips through YAML by construction.
  • Per-entry measurement comments (# 1013 code lines of 1343 raw, 45KB.) are recomputed on write rather than preserved.

--update-allowlist on an unchanged tree now produces a byte-identical file, pinned by test_rewriting_the_live_allowlist_is_a_no_op. The header says where to edit the prose so the next person doesn't edit the generated copy.

B3 — The ratchet does not detect an entry that has fallen under the cap. fixed-in-PR (commit 660b721)

Agreed, and I went one step past your snippet: find_stale_entries() reports an entry whose file is now under both hard caps or no longer exists, and those are lint errors (exit 1), not warnings. A warning is exactly what would have let this PR's own five stale entries through again — the failure mode you caught is the argument against the softer option. TestFindStaleEntries covers both stale shapes, the mixed case, and main([]) == 1 end-to-end against a synthetic repo root.

Non-blocking

N1 — Five new entries have no issue: field. fixed-in-PR (commit 660b721)

Filed and wired in: #3674 (gateway/gateway/__init__.py), #3675 (_tool_defs.py), #3676 (_prompt_agent.py), #3677 (_prompt_phase.py), #3678 (_parser.py). All six entries (including the pre-existing #3498) now carry both issue: and note:, and test_every_entry_has_a_tracking_issue makes an issue-less entry a test failure rather than a convention.

N2 — splitlines() positions vs. tokenizer line numbers. fixed-in-PR (commit 660b721)

Agreed. New _physical_lines() uses io.StringIO(source).readlines(), and it is the single source of both the docstring line map and raw_lines. TestPhysicalLineMapping parametrizes all eight separators (\x0b \x0c \x1c \x1d \x1e \x85 
 
) and asserts both that splitlines() still over-splits (guard-the-guard — if CPython ever changed, the test would pass vacuously) and that count_code_lines returns 2.

N3 — A docstring sharing a physical line with code drops the code. fixed-in-PR (commit 660b721)

Agreed. _shares_a_line_with_code() skips the exclusion when anything but whitespace precedes the docstring on its first line, or follows it on its last (a trailing # comment doesn't count as code, so """doc""" # note still excludes). def f(): """doc""" is now 1; the """doc"""; x = 1; y = 2 case is 3.

N4 — Residual __doc__-position gaming vector. fixed-in-PR (commit 660b721)

The docstring now documents the mirror image of the _DOC = """...""" case explicitly: a docstring-position string is unbounded by design, and the byte backstop restored in B1 is what bounds it in practice. Both directions are now stated as intentional rather than one being covered and the other silently absent.

N5 — orchestrator/CLAUDE.md left stale. fixed-in-PR (commit 660b721)

Both lines fixed. :271's cap claim is now scoped to the caps in force at the time of that split, with a callout noting that under the #3671 metric _prompt_agent.py (1,195) and _prompt_phase.py (1,285) are over the cap and carry #3676/#3677. :284 and :286's "files: map is now EMPTY" are rewritten to past tense with the re-baseline noted. I also swept the rest: gateway/CLAUDE.md and orchestrator/CLAUDE.md gained a note that byte/line figures in the slice records are historical measurements against the then-current caps, and docs/guides/decomposition-pattern.md had two further staleness bugs the byte-cap restoration created — the "1,500 raw lines / 100 KB" line, and a "each PR must reduce its size" ratchet description that has not matched the per-file-baseline-free allowlist for some time.

N6 — _load_file_size_checker() re-execs per parametrization. fixed-in-PR (commit 660b721)

@functools.cache, with the reason in the docstring.

N7 — Misleading assertion message. fixed-in-PR (commit 660b721)

Now f"{submodule}: {code_lines} code lines > {cap} hard cap; split it further.", with a comment above the assert recording why restoring an entry can't rescue it (the assertion reads the cap only, never allowlist membership) — that property is the point of the guard and was worth writing down rather than just deleting the wrong sentence.

N8 — _require_cap validates presence but not value. fixed-in-PR (commit 660b721)

Coercion is wrapped (hard_code_lines: abc → SystemExit: caps key 'hard_code_lines' must be an integer, got 'abc'.) and range-checked, with the non-obvious consequence spelled out in the message: "A zero or negative cap would silently reject (or never gate) every file." Covered by test_non_integer_cap_fails_with_a_message and test_non_positive_cap_fails_with_a_message.

N9 — Docstring overstates the unparseable fallback. fixed-in-PR (commit 660b721)

Reworded to the accurate claim, keeping the safety property that actually matters:

A SyntaxError only ever removes exclusions -- ast.parse failing gives up the docstring spans, and tokenize failing gives up the comment-only lines, each independently -- so a broken file can never measure smaller than a working one.

Verification

  • python3 -m pytest tests/scripts/test_check_file_sizes.py → 86 passed (up from 40).
  • python3 -m pytest tests/tools/test_select_tests_package_shape.py → 12 passed.
  • make lint: ruff check + ruff format clean; make lint-custom exits 0 (file-sizes passes with 66 soft-cap warnings, unchanged). The three mypy errors in shared/egg_agent/client.py are pre-existing on the branch and untouched by this PR.
  • python3 scripts/check-file-sizes.py --update-allowlist on a clean tree → byte-identical output.
  • check-file-sizes.py itself measures 357 code lines / 651 raw / 26,688 bytes, under the 500 soft cap.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No agent-mode design concerns in the delta. Re-approving on the agent-mode lens.

Delta reviewed: 660b721 only (the PR's second commit) — check-file-sizes.py, its allowlist, the two test files, and three docs. Re-scanned for this lens's anti-patterns — pre-fetched context, structured output for human consumers, post-processing pipelines, prompt-level enforcement of hard rules, direct Anthropic API calls, pinned model IDs. None present; the delta contains no model identifier, no HTTP client, and no prompt-assembly code.

The revision closes the one soft spot I named last time. My approval at fec9a985 flagged the Read-budget headroom as empirical rather than enforced — "a 1000-code-line file with 4,000 lines of docstring would pass." hard_bytes: 150000 now enforces it, and TestByteBackstop::test_padded_docstring_is_caught_by_bytes_alone pins exactly that construction. test_no_source_file_blows_the_read_budget states the reason in its own docstring: "The cap the check exists for is the agent's Read cost, and code lines cannot see it." That is the right place for the property — a repo-wide assertion measured through the production measure(), not a comment asserting a guarantee nothing checks.

I also flagged the counter-pressure — that re-adding a byte cap risks reintroducing the incentive #3671 removes. The revision resolves it rather than trading it away: hard-only (test_there_is_no_soft_byte_warning), set ~50% above the largest real file, and error text that forecloses the wrong reading directly — "not a prose budget -- it sits far above any healthy file, so trimming documentation is neither the intended fix nor enough of one." An agent hitting this failure is pointed at decomposition, never at prose.

Re-measured on the tree at 660b721: lint exits 0, 66 warnings, zero stale entries. Largest non-allowlisted file is _run_implement.py at 79,393 bytes — still under the ~100KB Read budget, so nothing clears the code-line cap while blowing the budget the byte cap protects. The 150KB backstop stays a pathology check rather than a live constraint, as documented.

Two further changes worth recording as aligned:

B3's fix landed at the lint layer, not the test layer. find_stale_entries() fails the lint when an exemption outlives its condition. The prior state was a header comment claiming a ratchet the code did not implement — a rule asserted in prose and enforced nowhere, which is the shape this lens exists to catch. It is now enforced technically, and the docstring records why a warning was insufficient: five stale entries survived the #3671 re-baseline unnoticed.

B2's fix removes a foot-gun from an agent-facing file. Moving the header into _ALLOWLIST_HEADER / _FILES_HEADER and per-entry rationale into structured note: fields means --update-allowlist can no longer silently delete the file's substance. The generated header points the reader at the script before they edit the wrong copy — good orientation for an agent that opens the YAML first.

The docs sweep (N5) is a net gain for agent context: orchestrator/CLAUDE.md and gateway/CLAUDE.md now mark historical slice measurements as historical instead of leaving figures that read as current caps, and the _prompt_agent.py / _prompt_phase.py allowlist entries are recorded where an agent working in that package will see them.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review of 660b721 — approved

All three blocking items from the previous round are fixed, and I verified each by execution rather than by reading the diff. No blocking issues in the delta.

B1 — byte backstop restored ✅

hard_bytes: 150000 is back and wired into evaluate() (scripts/check-file-sizes.py:419-441) as an independent hard-cap trip, not an elif off the line cap, so a file over both reports both. The allowlist waives it uniformly (:420-421), and there is deliberately no soft byte cap.

Reproduced my original scenario against a synthetic repo: a module with 1 code line and a 603,013-byte padded docstring now fails with

orchestrator/padded.py: 603013 bytes exceeds the byte backstop (150000 bytes). This cap is a
pathology check on what reading the file actually costs, not a prose budget -- ...

The framing fix matters as much as the cap: the error text closes off "delete prose" as a response, and 150 KB sits ~50% above the largest real file (101 KB concurrent_executor.py), so it never binds on a healthy file. That looseness is what keeps #3671's property intact, and both the module docstring (:55-73) and the allowlist header say so.

B2 — --update-allowlist no longer destroys the file ✅

The fix is stronger than what I asked for: rather than teaching the writer to preserve comments, the file is now generated. Header prose lives in _ALLOWLIST_HEADER / _FILES_HEADER (:126-171), per-entry rationale moved out of comments into a structured note: field on AllowlistEntry (:194-207), and the per-entry measurements are recomputed on write (:560-565) so they cannot go stale either.

Verified independently, not just via the new test: I ran update_allowlist() with ALLOWLIST_PATH pointed at a copy of the checked-in file and diffed. Byte-identical — 45 comment lines in, 45 out, all six note:/issue: pairs preserved. The previous round's result was 45 → 0.

test_rewriting_the_live_allowlist_is_a_no_op pins this against the live file, which is the right place for it: the assertion breaks the moment someone hand-edits the YAML instead of the constants.

B3 — stale-entry ratchet enforced at the lint layer ✅

find_stale_entries() (:461-490) reports an entry whose file is gone or has dropped back under both hard caps, and main() folds them into failures (:638) as errors, not warnings. Verified on a synthetic repo with one gone entry and one now-under-cap entry: both reported, main([]) == 1.

Making these errors rather than warnings is the correct call and the reasoning is recorded at :635-637. A warning is precisely what let this PR's own five stale entries pass unnoticed; an unneeded exemption is an unbounded one.

Delta verification

  • python3 scripts/check-file-sizes.py → exit 0, 66 soft warnings, no stale entries.
  • pytest tests/scripts/test_check_file_sizes.py tests/tools/test_select_tests_package_shape.py → 98 passed.
  • ruff check + ruff format --check on all three changed Python files → clean.
  • N2/N3 behaviour spot-checked directly: _physical_lines() keeps \x0b-in-a-literal at 2 code lines; def f(): """doc""" is 1, not 0; """doc"""; x = 1; y = 2 is 3; """doc""" # note still excludes.
  • Issues #3674–#3678 all exist, are open, and their titles match the five allowlist entries and their measured code-line counts.
  • Traced the consumer: make lint-custom (Makefile:322-325) globs scripts/check-*.py and invokes with no args, so the new stale-entry failure path is on the real lint path, not just reachable from tests.

I pulled Makefile and the issue list outside the delta because the delta alone cannot show that the new error path actually reaches make lint, nor that the issue: values point at real tracking issues.

— Authored by egg

@james-in-a-box

Copy link
Copy Markdown
Contributor

egg review completed. View run logs

5 previous review(s) hidden.

@jwbron
jwbron merged commit 7264e3c into main Jul 27, 2026
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

check-file-sizes.py counts prose, so the cheapest way to pass it is to delete documentation

1 participant