Skip to content

refactor: drain no_magic_numbers baseline to zero via Final hoists (#1856 phase 2)#1872

Merged
Aureliolo merged 12 commits into
mainfrom
refactor/issue-1856-phase-2-literal-migration
May 12, 2026
Merged

refactor: drain no_magic_numbers baseline to zero via Final hoists (#1856 phase 2)#1872
Aureliolo merged 12 commits into
mainfrom
refactor/issue-1856-phase-2-literal-migration

Conversation

@Aureliolo
Copy link
Copy Markdown
Owner

Summary

Finishes off the work tracked in (closed) issue #1856 by draining scripts/no_magic_numbers_baseline.txt from 499 entries down to 0, exceeding the issue's stretch goal.

Phase 1 (#1866) tightened scripts/check_no_magic_numbers.py to recognise typed module-level constants as already-named. This phase migrates the remaining real literals into either:

  • module-level Final constants (NAME: Final[int|float] = literal) for code-level invariants and bootstrap defaults, or
  • references to existing centralised constants where the value was already named elsewhere.

Inline # lint-allow: magic-numbers markers in src/: 50 → 0.

What changed

  • 313 .py files under src/synthorg/: inline numeric literals hoisted to module-level Final constants
  • scripts/no_magic_numbers_baseline.txt: 499 entries → header-only (0 entries)
  • tests/evals/prompt/test_memory_consolidation_prompt.py: contract test relaxed to accept Final references for the consolidation temperature pin
  • Net diff: 1264 insertions / 1304 deletions (slightly negative)

No behavioural changes. No SQL / schema / migration / API / config changes. Every hoisted value was preserved exactly (verified by sampling 40+ files across the diff).

Test plan

  • uv run ruff check src/ tests/: clean
  • uv run ruff format src/ tests/: 3712 files unchanged
  • uv run mypy src/ tests/ (strict): clean across 3712 files
  • uv run python -m pytest tests/ -m unit: 28400 passed, 18 skipped (platform-only)
  • uv run python scripts/check_no_magic_numbers.py: exit 0 (no violations against the now-empty baseline)

Review coverage

Pre-reviewed by 10 parallel agents. 8 returned clean. 2 surfaced nomenclature suggestions (_DEFAULT_LIMIT repetition across controllers; _DEFAULT_LIST_LIMIT_50 value-in-name in 9 persistence files); reviewed with the author and consciously deferred since the constants are module-private and the patterns are deliberate.

Verified clean: value preservation across 40+ files, security-sensitive constants (JWT TTLs, PKCE lengths, OAuth thresholds, webhook clock-skew, rate-limit caps, sandbox config) across 18 files, API contracts across 36 controllers, SQLite/Postgres parity in persistence, docs consistency (CLAUDE.md, convention-gates.md, design pages).

Aureliolo added 10 commits May 11, 2026 23:01
- Remove 55 # lint-allow: magic-numbers markers (now 0 in src/)
- Phase 1's named-constant gate already allowlists module-level
  : int|float|Final|Final[int]|Final[float] = literal, making most
  markers redundant
- Add Final annotation to three previously-untyped module constants
  (_DEFAULT_WINDOW_SECONDS in loop_prevention/rate_limit.py,
  _STATE_TOKEN_PREFIX_LENGTH in oauth/state_service.py,
  _SUBWORKFLOW_KEYSET_ARITY in workflow/subworkflow_registry.py)
- Annotate _DEFAULT_TIMEOUT_CHECK_INTERVAL_SECONDS in api/app.py
- Convert function-parameter literal defaults to named-Final references
  (_DEFAULT_TOP_N, _DEFAULT_MIN_DEPLOYMENTS, _DEFAULT_RECENT_OUTCOMES_LIMIT,
  _DEFAULT_MAX_RESULTS, _DEFAULT_PAGE_SIZE, _DEFAULT_CHUNK_SIZE_WORDS,
  _DEFAULT_MAX_WORKERS_PER_QUERY, _DEFAULT_MAX_RETRY_COUNT,
  _DEFAULT_FORCE_FLUSH_TIMEOUT_SECONDS)
- Reuse persistence._shared.DEFAULT_LIST_LIMIT for the two approval
  repos' list_items default
- Baseline auto-shrinks 513 to 499 (Final annotations + named-reference
  defaults satisfy the gate without needing a baseline entry)

Refs #1856 (phase 2)
Section 3 (meta + adjacent) of the magic-numbers drain.  Per the user's
'default to Final invariant unless clearly operator-tunable' rule,
converts module-level untyped constants to the Final[int|float] shape
the gate already accepts, and hoists function-default literals to
named module-level Final references.

Files touched:
- meta/rules/builtin.py: 10 rule thresholds become _DEFAULT_<NAME>
  module constants referenced from constructor defaults
- meta/rollout/{ab_test,ab_comparator,regression/welch}.py:
  significance level / sample minimums / improvement threshold
  become module-level Final
- meta/chief_of_staff/learning.py: EMA + Bayesian adjuster defaults
  become module-level Final
- meta/telemetry/emitter.py: retry / backoff / HTTP-status bounds
  become Final[int|float]
- core/personality.py: Big Five compatibility weights become
  Final[float] (sum to 1.0 invariant preserved)
- memory/consolidation/density.py: signal weights + tolerance become
  Final[float]
- memory/consolidation/service.py: enforce-batch bounds Final[int]
- memory/retrieval_config.py: 7 retrieval defaults Final
- memory/embedding/fine_tune.py: 7 stage defaults hoisted to
  module-level Final
- communication/event_stream/stream.py: hub queue + dedup +
  janitor defaults Final
- communication/bus/_nats_history.py: history scan batch + timeout
  hoisted to two shared module Finals (used by 3 functions)
- engine/classification/detectors.py: minimum-text + drift
  thresholds Final
- providers/health.py: health window + thresholds Final
- persistence/ontology_protocol.py: Protocol method limit defaults
  reuse persistence._shared.DEFAULT_LIST_LIMIT
- observability/http_handler.py: HttpBatchHandler ctor defaults
  hoisted to module-level Finals

Refs #1856 (phase 2)
Section 3 continued: integrations/health, hr/training/curation,
hr/performance/composite_quality_strategy, engine/trajectory,
engine/shutdown_strategies, api/controllers/oauth, security/llm_evaluator.

All literal-RHS module-level constants now carry the Final[int|float]
annotation the magic-numbers gate accepts; structural_erosion's four
window_size function defaults reference a single shared module-level
_DEFAULT_WINDOW_SIZE constant.

Refs #1856 (phase 2)
…onstants

Replaces every 'limit: int = N' default in persistence/ Protocol and
repository methods with a named reference:

- limit=100 sites (~59) reference persistence._shared.DEFAULT_LIST_LIMIT
- limit=50 / =200 / =10 / =5 sites use a per-file _DEFAULT_LIST_LIMIT_<N>
  module-level Final constant

Affects ~50 files across persistence/, persistence/postgres/, and
persistence/sqlite/.  Behaviour is unchanged: the same numeric value
reaches the SQL LIMIT clause; the literal just lives in a named slot
the magic-numbers gate accepts.

Refs #1856 (phase 2)
Phase 2 final cleanup. The baseline shrinks from 499 stale + live
entries to a single entry at memory/fine_tune_plan.py:40 where the
constant uses Literal[2] = 2 (value-encoded-in-type, deliberate).
The gate accepts Final[int|float] but not Literal[N]; keeping the
Literal form preserves the type-level singleton-value guarantee
and leaves a single line in the baseline.

Drains: 513 to 1 (99.8% shrinkage).

Refs #1856 (phase 2)
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 11, 2026

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 11, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6ab62df1-5de4-46b6-8cac-ab398d4b3d6a

📥 Commits

Reviewing files that changed from the base of the PR and between 245dd88 and a5dfe0e.

📒 Files selected for processing (18)
  • src/synthorg/engine/loop_selector.py
  • src/synthorg/engine/workflow/validate_edges.py
  • src/synthorg/integrations/oauth/flows/device_flow.py
  • src/synthorg/persistence/connection_protocol.py
  • src/synthorg/persistence/cost_record_protocol.py
  • src/synthorg/persistence/postgres/escalation_repo.py
  • src/synthorg/persistence/postgres/fine_tune_repo.py
  • src/synthorg/persistence/postgres/org_fact_repo.py
  • src/synthorg/persistence/postgres/provider_audit_repo.py
  • src/synthorg/persistence/postgres/settings_repo.py
  • src/synthorg/persistence/postgres/version_repo.py
  • src/synthorg/persistence/sqlite/escalation_repo.py
  • src/synthorg/persistence/sqlite/fine_tune_repo.py
  • src/synthorg/persistence/sqlite/org_fact_repo.py
  • src/synthorg/persistence/sqlite/provider_audit_repo.py
  • src/synthorg/persistence/sqlite/settings_repo.py
  • src/synthorg/persistence/sqlite/version_repo.py
  • src/synthorg/persistence/task_protocol.py
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Deploy Preview
  • GitHub Check: Build Backend
  • GitHub Check: Build Fine-Tune (cpu, fine-tune-cpu)
  • GitHub Check: Build Fine-Tune (gpu, fine-tune-gpu)
  • GitHub Check: Build Web Assets (melange)
  • GitHub Check: CodSpeed Python benchmarks
  • GitHub Check: Test (Python 3.14)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (4)
src/synthorg/!(persistence)/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

Only src/synthorg/persistence/ may import sqlite/psycopg or emit raw SQL.

Files:

  • src/synthorg/engine/loop_selector.py
  • src/synthorg/integrations/oauth/flows/device_flow.py
  • src/synthorg/engine/workflow/validate_edges.py
src/synthorg/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

src/synthorg/**/*.py: Configuration precedence: DB > env > YAML > code default via SettingsService/ConfigResolver; no os.environ.get outside startup.
No hardcoded numerics; numerics live in settings/definitions/; allowlist 0/1/-1, HTTP codes, hex masks, powers-of-2, and module-level annotated named constants of the form NAME: int|float|Final|Final[int]|Final[float] = literal. Enforced by scripts/check_no_magic_numbers.py.
Comments explain WHY only; no reviewer citations / issue back-refs / migration framing. Enforced by check_no_review_origin_in_code.py + check_no_migration_framing.py.
No from __future__ import annotations (3.14 has PEP 649). Use PEP 758 except: except A, B: requires parens when binding.
Type hints on public functions; mypy strict. Google-style docstrings. Line length 88; functions <50 lines; files <800 lines.
Errors: <Domain><Condition>Error from DomainError; never inherit Exception/RuntimeError/etc directly. Enforced by check_domain_error_hierarchy.py.
Pydantic v2 frozen + extra="forbid" on API DTOs (Request/Response/Snapshot/Result/Envelope/Status/Info/Summary suffixes); @computed_field for derived; NotBlankStr for identifiers.
Args models at every system boundary; parse_typed() for every external dict ingestion. Enforced by check_boundary_typed.py.
Immutability: use model_copy(update=...) or copy.deepcopy(); deepcopy at system boundaries.
Async: use asyncio.TaskGroup for fan-out/fan-in; helpers catch Exception (re-raise MemoryError/RecursionError).
Clock seam: declare clock: Clock | None = None; tests inject FakeClock. Lifecycle: services own _lifecycle_lock; timed-out stops mark unrestartable.
Untrusted content (SEC-1): use wrap_untrusted() from engine.prompt_safety; use HTMLParseGuard for HTML.
Repository CRUD: use methods save(entity), get(id), delete(id) -> bool, list_items(...), query(...) returning tuples.
Datetime in persistence: use parse_iso_utc / `format_iso_...

Files:

  • src/synthorg/engine/loop_selector.py
  • src/synthorg/persistence/connection_protocol.py
  • src/synthorg/persistence/postgres/provider_audit_repo.py
  • src/synthorg/persistence/task_protocol.py
  • src/synthorg/persistence/cost_record_protocol.py
  • src/synthorg/persistence/sqlite/fine_tune_repo.py
  • src/synthorg/persistence/postgres/version_repo.py
  • src/synthorg/integrations/oauth/flows/device_flow.py
  • src/synthorg/persistence/sqlite/provider_audit_repo.py
  • src/synthorg/persistence/postgres/settings_repo.py
  • src/synthorg/persistence/sqlite/version_repo.py
  • src/synthorg/persistence/sqlite/escalation_repo.py
  • src/synthorg/persistence/sqlite/settings_repo.py
  • src/synthorg/persistence/postgres/fine_tune_repo.py
  • src/synthorg/persistence/sqlite/org_fact_repo.py
  • src/synthorg/persistence/postgres/org_fact_repo.py
  • src/synthorg/persistence/postgres/escalation_repo.py
  • src/synthorg/engine/workflow/validate_edges.py
src/**/*.py

⚙️ CodeRabbit configuration file

This project uses Python 3.14+ with PEP 758 except syntax: "except A, B:" (comma-separated, no parentheses) is correct and mandatory -- do NOT flag it as a typo or suggest parenthesized form. The "except builtins.MemoryError, RecursionError: raise" pattern is intentional project convention for system-error propagation. When evaluating the 50-line function limit, count only the function body excluding the signature lines, decorators, and docstring. Functions 1-5 lines over due to docstrings or multi-line signatures should not be flagged. Do not suggest extracting single-use helper functions called exactly once -- this reduces readability without improving maintainability.

Files:

  • src/synthorg/engine/loop_selector.py
  • src/synthorg/persistence/connection_protocol.py
  • src/synthorg/persistence/postgres/provider_audit_repo.py
  • src/synthorg/persistence/task_protocol.py
  • src/synthorg/persistence/cost_record_protocol.py
  • src/synthorg/persistence/sqlite/fine_tune_repo.py
  • src/synthorg/persistence/postgres/version_repo.py
  • src/synthorg/integrations/oauth/flows/device_flow.py
  • src/synthorg/persistence/sqlite/provider_audit_repo.py
  • src/synthorg/persistence/postgres/settings_repo.py
  • src/synthorg/persistence/sqlite/version_repo.py
  • src/synthorg/persistence/sqlite/escalation_repo.py
  • src/synthorg/persistence/sqlite/settings_repo.py
  • src/synthorg/persistence/postgres/fine_tune_repo.py
  • src/synthorg/persistence/sqlite/org_fact_repo.py
  • src/synthorg/persistence/postgres/org_fact_repo.py
  • src/synthorg/persistence/postgres/escalation_repo.py
  • src/synthorg/engine/workflow/validate_edges.py
src/synthorg/**/provider*.py

📄 CodeRabbit inference engine (CLAUDE.md)

Resilience: provider calls go through BaseCompletionProvider (retry + rate limit); never implement retry in driver subclasses. Retryable: RateLimitError, Provider{Timeout,Connection,Internal}Error. WebSocket: per-frame timeout closes silent peers (1008); revalidation saturation closes (4011).

Files:

  • src/synthorg/persistence/postgres/provider_audit_repo.py
  • src/synthorg/persistence/sqlite/provider_audit_repo.py
🧠 Learnings (1)
📚 Learning: 2026-05-05T09:04:46.195Z
Learnt from: Aureliolo
Repo: Aureliolo/synthorg PR: 1760
File: scripts/_dual_backend_parity_lib.py:215-216
Timestamp: 2026-05-05T09:04:46.195Z
Learning: This repository targets Python 3.14+ and follows PEP 758. Therefore, reviewer tooling should NOT treat unparenthesized multi-exception `except` clauses written without an `as` clause (e.g., `except MemoryError, RecursionError:`) as syntax errors. Only flag `except`-clause problems when they are genuinely invalid for Python 3.14+.

Applied to files:

  • src/synthorg/engine/loop_selector.py
  • src/synthorg/persistence/connection_protocol.py
  • src/synthorg/persistence/postgres/provider_audit_repo.py
  • src/synthorg/persistence/task_protocol.py
  • src/synthorg/persistence/cost_record_protocol.py
  • src/synthorg/persistence/sqlite/fine_tune_repo.py
  • src/synthorg/persistence/postgres/version_repo.py
  • src/synthorg/integrations/oauth/flows/device_flow.py
  • src/synthorg/persistence/sqlite/provider_audit_repo.py
  • src/synthorg/persistence/postgres/settings_repo.py
  • src/synthorg/persistence/sqlite/version_repo.py
  • src/synthorg/persistence/sqlite/escalation_repo.py
  • src/synthorg/persistence/sqlite/settings_repo.py
  • src/synthorg/persistence/postgres/fine_tune_repo.py
  • src/synthorg/persistence/sqlite/org_fact_repo.py
  • src/synthorg/persistence/postgres/org_fact_repo.py
  • src/synthorg/persistence/postgres/escalation_repo.py
  • src/synthorg/engine/workflow/validate_edges.py
🔇 Additional comments (33)
src/synthorg/engine/loop_selector.py (1)

52-53: Nice alignment on the threshold default source.

Using _DEFAULT_BUDGET_TIGHT_THRESHOLD in both AutoLoopConfig and select_loop_type removes drift risk and matches the no-magic-number rule cleanly.

Also applies to: 121-121, 236-236

src/synthorg/engine/workflow/validate_edges.py (1)

11-11: Centralizing _MIN_SPLIT_BRANCHES via shared validation types is a good change.

This keeps the split-branch rule consistent across workflow validation code while preserving behavior.

src/synthorg/persistence/postgres/fine_tune_repo.py (2)

33-33: Shared pagination default import looks correct.

Using the protocol-level default constant here improves consistency across backends and aligns with the no-magic-number rule.


245-245: Default limit hoists are clean and behavior-preserving.

Both list APIs now reference the shared _DEFAULT_LIST_LIMIT_50 constant, and existing clamp logic still guards bounds, so semantics remain intact.

Also applies to: 457-457

src/synthorg/persistence/sqlite/fine_tune_repo.py (2)

25-25: Protocol default import is aligned with backend parity goals.

This keeps SQLite defaults sourced from the same place as the protocol and Postgres implementation.


213-213: list_* default-limit updates are consistent and safe.

Replacing inline 50 with _DEFAULT_LIST_LIMIT_50 keeps behavior unchanged while removing magic-number usage.

Also applies to: 420-420

src/synthorg/persistence/sqlite/provider_audit_repo.py (2)

31-31: Good default-limit centralization import.

This keeps the repository default sourced from a shared constant instead of a literal and aligns with the no-magic-numbers policy.


117-117: Default parameter now matches shared protocol constant.

Using _DEFAULT_LIST_LIMIT_50 here keeps the repo and protocol defaults in sync while preserving behavior.

src/synthorg/persistence/sqlite/escalation_repo.py (1)

25-29: Shared pagination default import is correct and consistent.

This keeps SQLite pagination defaults aligned with the escalation protocol contract without changing behavior.

As per coding guidelines: "No hardcoded numerics … allow … module-level annotated named constants."

src/synthorg/persistence/postgres/escalation_repo.py (1)

28-32: Protocol-level default reuse looks good.

Using shared _DEFAULT_LIMIT/_DEFAULT_OFFSET here keeps Postgres behavior in sync with the common escalation interface.

As per coding guidelines: "No hardcoded numerics … allow … module-level annotated named constants."

src/synthorg/persistence/postgres/settings_repo.py (1)

30-30: Shared default-limit constant wiring is correct.

Line 30 and Line 128 correctly replace the inline pagination default with _DEFAULT_LIST_LIMIT_200 while preserving existing validation and limit-capping behavior.

Also applies to: 128-128

src/synthorg/persistence/sqlite/settings_repo.py (1)

18-18: Default pagination constant centralization looks good.

Line 18 and Line 99 correctly migrate the default limit to _DEFAULT_LIST_LIMIT_200 with no behavioral drift in get_all.

Also applies to: 99-99

src/synthorg/persistence/cost_record_protocol.py (2)

7-7: Centralized default import looks good.

Using DEFAULT_LIST_LIMIT from synthorg.persistence._shared keeps pagination defaults consistent across persistence protocols.


30-41: Query default + docstring are aligned and clear.

The limit default now references the shared constant, and the updated docstring correctly documents the expected pagination behavior.

src/synthorg/persistence/postgres/version_repo.py (2)

46-46: Shared default constant import is aligned and safe.

This import cleanly centralizes the pagination default and keeps behavior unchanged.

As per coding guidelines, numerics should be centralized and named constants are allowed.


340-340: Default limit now correctly references the centralized constant.

Good replacement of inline literal with the shared default in the method signature.

As per coding guidelines, numerics should be centralized and named constants are allowed.

src/synthorg/persistence/sqlite/version_repo.py (2)

41-41: Importing _DEFAULT_LIST_LIMIT_50 is a good consistency move.

This keeps SQLite defaults sourced from the same shared pagination constant.

As per coding guidelines, numerics should be centralized and named constants are allowed.


332-332: list_versions default update is correct and consistent.

Using the shared constant preserves value semantics while removing inline magic numbers.

As per coding guidelines, numerics should be centralized and named constants are allowed.

src/synthorg/persistence/task_protocol.py (1)

8-8: Good consolidation of pagination default.

Using DEFAULT_LIST_LIMIT in the protocol signature and updating the docstring keeps the contract explicit and consistent with the shared persistence defaults.

Also applies to: 46-46, 55-57

src/synthorg/persistence/connection_protocol.py (1)

17-17: Looks good—defaults are now consistently centralized.

The switch to DEFAULT_LIST_LIMIT across these protocol methods is clean and keeps pagination contracts aligned.

Also applies to: 35-35, 40-44, 52-52, 170-170

src/synthorg/integrations/oauth/flows/device_flow.py (5)

6-6: Final import is appropriate here.

No concerns on this change; it enables typed immutable defaults cleanly.


26-27: Good hoist to typed module defaults.

Defining _DEFAULT_EXPIRES_IN and _DEFAULT_MAX_WAIT_SECONDS as Final[int] removes inline literals and keeps defaults explicit.


59-59: Constructor default now correctly references centralized constant.

This keeps the DeviceFlowResult default aligned with module-level timeout semantics.


259-259: Good fix: parser fallback now uses _DEFAULT_EXPIRES_IN.

This resolves the prior split source-of-truth risk for expires_in fallback handling.


285-285: poll_for_token default now cleanly references named constant.

This is consistent with the no-magic-number migration and improves maintainability.

src/synthorg/persistence/sqlite/org_fact_repo.py (3)

40-45: Nice centralization of pagination defaults.

Importing DEFAULT_LIST_LIMIT and _DEFAULT_LIST_LIMIT_5 here removes local literals and keeps this repository aligned with shared persistence defaults.


444-445: query() default migration looks correct.

Switching the default to _DEFAULT_LIST_LIMIT_5 is clean and preserves runtime behavior since boundary clamping is unchanged.


496-497: list_by_category() default migration looks correct.

Using DEFAULT_LIST_LIMIT improves consistency across repositories while preserving existing limit/offset normalization behavior.

src/synthorg/persistence/postgres/org_fact_repo.py (3)

36-37: Good shared-constant import update.

Pulling pagination defaults from shared modules removes inline numerics and keeps protocol/repository defaults aligned.


418-419: query() default constant adoption is solid.

Replacing the literal with _DEFAULT_LIST_LIMIT_5 is a maintainability win, and the existing clamp continues to enforce bounds.


474-475: list_by_category() default update is consistent.

Using DEFAULT_LIST_LIMIT here matches the shared pagination contract without changing effective boundary behavior.

src/synthorg/persistence/postgres/provider_audit_repo.py (2)

27-27: Good centralization of pagination default constant.

This import cleanly replaces an inline literal with a shared named constant and keeps default ownership in the protocol layer.


109-109: Default limit refactor is correct and behavior-preserving.

Switching the signature default to _DEFAULT_LIST_LIMIT_50 keeps pagination semantics intact while removing the inline numeric default.


Walkthrough

This update eliminates all magic-number-style inline configuration defaults by introducing named, typed module-level constants using typing.Final throughout the codebase. Every API, service, repository, protocol, helper, and validation module now sources defaults such as pagination page sizes, thresholds, timeouts, and batch sizes from clearly named constants. Method signatures, protocol interface definitions, and internal helper logic reference these constants, supported by appropriate import and type annotation adjustments. The static-analysis suppression baseline for magic numbers is cleared, since suppressions are no longer justified or required. No core logic, validation, or runtime behavior changes are introduced. All observable changes are strictly for maintainability, typing, and future static analysis clarity.

@Aureliolo Aureliolo temporarily deployed to cloudflare-preview May 11, 2026 21:38 — with GitHub Actions Inactive
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 11, 2026

Merging this PR will not alter performance

✅ 33 untouched benchmarks
⏩ 21 skipped benchmarks1


Comparing refactor/issue-1856-phase-2-literal-migration (71ffdd6) with main (9070387)

Open in CodSpeed

Footnotes

  1. 21 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/synthorg/persistence/connection_protocol.py (1)

35-43: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Docstring default is now stale relative to the updated signature.

limit now defaults to DEFAULT_LIST_LIMIT, but the docstring still says limit=None (default) with legacy fetch-all semantics. Please update the docstring (or type/default) so the protocol contract is self-consistent.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/synthorg/persistence/connection_protocol.py` around lines 35 - 43, The
docstring for the function with signature "(limit: int = DEFAULT_LIST_LIMIT,
offset: int = 0) -> tuple[Connection, ...]" is inconsistent: it still claims
"limit=None (default)" while the code now defaults to DEFAULT_LIST_LIMIT. Update
the docstring to reflect the current contract (e.g., state that limit defaults
to DEFAULT_LIST_LIMIT and therefore returns at most that many connections unless
callers pass a different positive int; keep the notes that limit <= 0 returns ()
and negative offset is treated as 0), or alternatively change the signature to
accept Optional[int] and default limit=None if you want to retain legacy
fetch-all semantics—make the docstring and the signature/type consistent with
whichever behavior you choose.
src/synthorg/persistence/task_protocol.py (1)

46-57: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align list_tasks docs with the non-optional int limit contract.

limit is typed as int with a concrete default, but the docstring says None is a supported meaning. That contract is contradictory and can cause incorrect caller assumptions.

Suggested doc fix
-            limit: Maximum rows to return.  ``None`` means "no
-                repository-level cap" (the caller remains free to
-                impose a safety cap above).
+            limit: Maximum rows to return.
+                Callers may pass a larger value when needed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/synthorg/persistence/task_protocol.py` around lines 46 - 57, The
docstring for list_tasks is inconsistent with its signature: limit is a
non-optional int with default DEFAULT_LIST_LIMIT but the text says None means
"no repository-level cap"; fix by updating the docstring to remove the "None"
semantics and instead describe that limit is an int defaulting to
DEFAULT_LIST_LIMIT (i.e., maximum rows to return, with callers free to impose
higher-level caps), referencing the limit parameter and DEFAULT_LIST_LIMIT in
the explanation so the contract matches the list_tasks signature.
src/synthorg/persistence/cost_record_protocol.py (1)

30-41: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix query() docstring: None is no longer the default (or typed).

The method now declares limit: int = DEFAULT_LIST_LIMIT, but docs still describe None (default) semantics. Please update the contract text to match the callable signature.

Suggested doc fix
-            limit: Maximum rows to return; ``None`` (default) preserves
-                fetch-all semantics.
-            offset: Rows to skip before applying *limit*; ignored when
-                *limit* is ``None``.
+            limit: Maximum rows to return.
+            offset: Rows to skip before applying ``limit``.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/synthorg/persistence/cost_record_protocol.py` around lines 30 - 41, The
docstring for the query() method no longer matches its signature: limit is typed
as int with default DEFAULT_LIST_LIMIT (not None). Update the Args text for the
query() method in CostRecordProtocol/CostRecord to remove any reference to "None
(default)/fetch-all semantics" and instead state that limit is an integer
defaulting to DEFAULT_LIST_LIMIT which caps the number of rows returned, and
that offset is the number of rows to skip before applying that limit (i.e.,
offset is ignored only if limit is not used or set to a value that indicates "no
rows", adjust wording to match actual implementation).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/synthorg/engine/loop_selector.py`:
- Around line 228-237: AutoLoopConfig currently hardcodes 80 for
budget_tight_threshold while select_loop_type uses
_DEFAULT_BUDGET_TIGHT_THRESHOLD; update AutoLoopConfig.budget_tight_threshold to
reference the module-level constant _DEFAULT_BUDGET_TIGHT_THRESHOLD instead of
the literal 80 so both call sites share the same named constant (keep the
constant's annotation and value as-is and import/qualify it if needed).

In `@src/synthorg/integrations/oauth/flows/device_flow.py`:
- Around line 26-27: The response parser fallback currently uses the hardcoded
literal 600; change that fallback to use the module constant _DEFAULT_EXPIRES_IN
instead so there is a single source of truth (keep _DEFAULT_MAX_WAIT_SECONDS
as-is). Locate the device flow response parsing code that sets the expires_in
fallback (the branch that uses the literal 600) and replace the literal with
_DEFAULT_EXPIRES_IN, ensuring the constant is in scope for that function.

---

Outside diff comments:
In `@src/synthorg/persistence/connection_protocol.py`:
- Around line 35-43: The docstring for the function with signature "(limit: int
= DEFAULT_LIST_LIMIT, offset: int = 0) -> tuple[Connection, ...]" is
inconsistent: it still claims "limit=None (default)" while the code now defaults
to DEFAULT_LIST_LIMIT. Update the docstring to reflect the current contract
(e.g., state that limit defaults to DEFAULT_LIST_LIMIT and therefore returns at
most that many connections unless callers pass a different positive int; keep
the notes that limit <= 0 returns () and negative offset is treated as 0), or
alternatively change the signature to accept Optional[int] and default
limit=None if you want to retain legacy fetch-all semantics—make the docstring
and the signature/type consistent with whichever behavior you choose.

In `@src/synthorg/persistence/cost_record_protocol.py`:
- Around line 30-41: The docstring for the query() method no longer matches its
signature: limit is typed as int with default DEFAULT_LIST_LIMIT (not None).
Update the Args text for the query() method in CostRecordProtocol/CostRecord to
remove any reference to "None (default)/fetch-all semantics" and instead state
that limit is an integer defaulting to DEFAULT_LIST_LIMIT which caps the number
of rows returned, and that offset is the number of rows to skip before applying
that limit (i.e., offset is ignored only if limit is not used or set to a value
that indicates "no rows", adjust wording to match actual implementation).

In `@src/synthorg/persistence/task_protocol.py`:
- Around line 46-57: The docstring for list_tasks is inconsistent with its
signature: limit is a non-optional int with default DEFAULT_LIST_LIMIT but the
text says None means "no repository-level cap"; fix by updating the docstring to
remove the "None" semantics and instead describe that limit is an int defaulting
to DEFAULT_LIST_LIMIT (i.e., maximum rows to return, with callers free to impose
higher-level caps), referencing the limit parameter and DEFAULT_LIST_LIMIT in
the explanation so the contract matches the list_tasks signature.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 507c6bce-0334-4a95-b7f2-86b04351f782

📥 Commits

Reviewing files that changed from the base of the PR and between 6263795 and 245dd88.

📒 Files selected for processing (300)
  • scripts/no_magic_numbers_baseline.txt
  • src/synthorg/a2a/connection_types/a2a_peer.py
  • src/synthorg/a2a/gateway.py
  • src/synthorg/a2a/push_verifier.py
  • src/synthorg/api/app.py
  • src/synthorg/api/auth/middleware.py
  • src/synthorg/api/auth/ticket_store.py
  • src/synthorg/api/boundary.py
  • src/synthorg/api/bus_bridge.py
  • src/synthorg/api/controllers/activities.py
  • src/synthorg/api/controllers/agent_identity_versions.py
  • src/synthorg/api/controllers/agents.py
  • src/synthorg/api/controllers/analytics.py
  • src/synthorg/api/controllers/approvals.py
  • src/synthorg/api/controllers/artifacts.py
  • src/synthorg/api/controllers/audit.py
  • src/synthorg/api/controllers/backup.py
  • src/synthorg/api/controllers/budget.py
  • src/synthorg/api/controllers/budget_config_versions.py
  • src/synthorg/api/controllers/clients.py
  • src/synthorg/api/controllers/company_versions.py
  • src/synthorg/api/controllers/connections.py
  • src/synthorg/api/controllers/coordination_metrics.py
  • src/synthorg/api/controllers/custom_rules.py
  • src/synthorg/api/controllers/departments.py
  • src/synthorg/api/controllers/escalations.py
  • src/synthorg/api/controllers/evaluation_config_versions.py
  • src/synthorg/api/controllers/events.py
  • src/synthorg/api/controllers/integration_health.py
  • src/synthorg/api/controllers/meetings.py
  • src/synthorg/api/controllers/messages.py
  • src/synthorg/api/controllers/meta.py
  • src/synthorg/api/controllers/meta_analytics.py
  • src/synthorg/api/controllers/oauth.py
  • src/synthorg/api/controllers/ontology.py
  • src/synthorg/api/controllers/personalities.py
  • src/synthorg/api/controllers/projects.py
  • src/synthorg/api/controllers/reports.py
  • src/synthorg/api/controllers/requests.py
  • src/synthorg/api/controllers/role_versions.py
  • src/synthorg/api/controllers/simulations.py
  • src/synthorg/api/controllers/tasks.py
  • src/synthorg/api/controllers/users.py
  • src/synthorg/api/controllers/workflow_executions.py
  • src/synthorg/api/controllers/workflow_versions.py
  • src/synthorg/api/cursor.py
  • src/synthorg/api/dto_discovery.py
  • src/synthorg/api/exception_handlers.py
  • src/synthorg/api/lifecycle.py
  • src/synthorg/api/lifecycle_builder.py
  • src/synthorg/api/rate_limits/in_memory.py
  • src/synthorg/api/rate_limits/in_memory_inflight.py
  • src/synthorg/api/services/org_mutations.py
  • src/synthorg/api/services/ssrf_violation_service.py
  • src/synthorg/backup/service_archive.py
  • src/synthorg/budget/automated_reports.py
  • src/synthorg/budget/coordination_metrics.py
  • src/synthorg/budget/coordination_store.py
  • src/synthorg/budget/enforcer.py
  • src/synthorg/budget/optimizer.py
  • src/synthorg/budget/quota_tracker.py
  • src/synthorg/budget/rebalance.py
  • src/synthorg/budget/reports.py
  • src/synthorg/budget/risk_tracker.py
  • src/synthorg/budget/tracker.py
  • src/synthorg/client/feedback/adversarial.py
  • src/synthorg/client/feedback/scored.py
  • src/synthorg/client/generators/llm.py
  • src/synthorg/client/generators/procedural.py
  • src/synthorg/communication/bus/_nats_history.py
  • src/synthorg/communication/conflict_resolution/escalation/config.py
  • src/synthorg/communication/conflict_resolution/escalation/in_memory_store.py
  • src/synthorg/communication/conflict_resolution/escalation/notify.py
  • src/synthorg/communication/conflict_resolution/escalation/protocol.py
  • src/synthorg/communication/conflict_resolution/escalation/sweeper.py
  • src/synthorg/communication/conflict_resolution/models.py
  • src/synthorg/communication/delegation/record_store.py
  • src/synthorg/communication/event_stream/stream.py
  • src/synthorg/communication/loop_prevention/dedup.py
  • src/synthorg/communication/loop_prevention/rate_limit.py
  • src/synthorg/config/rate_limits.py
  • src/synthorg/constants.py
  • src/synthorg/core/auth/config.py
  • src/synthorg/core/concurrency/cas_retry.py
  • src/synthorg/core/personality.py
  • src/synthorg/engine/agent_engine_post_exec.py
  • src/synthorg/engine/approval_gate.py
  • src/synthorg/engine/classification/detectors.py
  • src/synthorg/engine/classification/loaders.py
  • src/synthorg/engine/classification/semantic_detectors.py
  • src/synthorg/engine/classification/sinks.py
  • src/synthorg/engine/classification/taxonomy_store.py
  • src/synthorg/engine/compaction/epistemic.py
  • src/synthorg/engine/decomposition/classifier.py
  • src/synthorg/engine/evolution/guards/rate_limit.py
  • src/synthorg/engine/evolution/guards/rollback.py
  • src/synthorg/engine/evolution/proposers/composite.py
  • src/synthorg/engine/evolution/proposers/self_report.py
  • src/synthorg/engine/evolution/proposers/separate_analyzer.py
  • src/synthorg/engine/intake/strategies/agent_intake.py
  • src/synthorg/engine/loop_selector.py
  • src/synthorg/engine/middleware/behavior_tagger.py
  • src/synthorg/engine/middleware/coordination_constraints.py
  • src/synthorg/engine/middleware/semantic_drift.py
  • src/synthorg/engine/plan_helpers.py
  • src/synthorg/engine/quality/decomposers/llm.py
  • src/synthorg/engine/routing/scorer.py
  • src/synthorg/engine/sanitization.py
  • src/synthorg/engine/shutdown.py
  • src/synthorg/engine/shutdown_strategies.py
  • src/synthorg/engine/stagnation/quality_erosion_detector.py
  • src/synthorg/engine/strategy/consensus.py
  • src/synthorg/engine/trajectory/budget_guard.py
  • src/synthorg/engine/trajectory/structural_erosion.py
  • src/synthorg/engine/workflow/condition_eval.py
  • src/synthorg/engine/workflow/sprint_velocity.py
  • src/synthorg/engine/workflow/subworkflow_registry.py
  • src/synthorg/engine/workflow/validate_edges.py
  • src/synthorg/engine/workflow/validation_types.py
  • src/synthorg/engine/workflow/version_service.py
  • src/synthorg/engine/workflow/webhook_bridge.py
  • src/synthorg/engine/workspace/disk_quota.py
  • src/synthorg/engine/workspace/semantic_checks.py
  • src/synthorg/engine/workspace/semantic_llm.py
  • src/synthorg/hr/performance/ci_quality_strategy.py
  • src/synthorg/hr/performance/composite_quality_strategy.py
  • src/synthorg/hr/performance/llm_calibration_sampler.py
  • src/synthorg/hr/performance/multi_window_strategy.py
  • src/synthorg/hr/performance/quality_override_store.py
  • src/synthorg/hr/performance/theil_sen_strategy.py
  • src/synthorg/hr/scaling/guards/approval_gate.py
  • src/synthorg/hr/scaling/guards/conflict_resolver.py
  • src/synthorg/hr/scaling/guards/cooldown.py
  • src/synthorg/hr/scaling/guards/rate_limit.py
  • src/synthorg/hr/scaling/service.py
  • src/synthorg/hr/scaling/signals/workload.py
  • src/synthorg/hr/scaling/strategies/budget_cap.py
  • src/synthorg/hr/scaling/strategies/workload.py
  • src/synthorg/hr/scaling/triggers/batched.py
  • src/synthorg/hr/training/curation/llm_curated.py
  • src/synthorg/hr/training/curation/relevance.py
  • src/synthorg/hr/training/extractors/procedural.py
  • src/synthorg/hr/training/extractors/semantic.py
  • src/synthorg/hr/training/extractors/tool_patterns.py
  • src/synthorg/hr/training/guards/review_gate.py
  • src/synthorg/hr/training/guards/sanitization.py
  • src/synthorg/hr/training/source_selectors/department_diversity.py
  • src/synthorg/hr/training/source_selectors/role_top_performers.py
  • src/synthorg/infrastructure/services.py
  • src/synthorg/integrations/health/checks/generic_http.py
  • src/synthorg/integrations/health/checks/github.py
  • src/synthorg/integrations/health/checks/slack.py
  • src/synthorg/integrations/health/checks/smtp.py
  • src/synthorg/integrations/health/prober.py
  • src/synthorg/integrations/mcp_catalog/in_memory_installations.py
  • src/synthorg/integrations/mcp_catalog/installations.py
  • src/synthorg/integrations/oauth/flows/device_flow.py
  • src/synthorg/integrations/oauth/pkce.py
  • src/synthorg/integrations/oauth/state_service.py
  • src/synthorg/integrations/oauth/token_manager.py
  • src/synthorg/integrations/rate_limiting/shared_state.py
  • src/synthorg/integrations/tunnel/ngrok_adapter.py
  • src/synthorg/integrations/webhooks/replay_protection.py
  • src/synthorg/integrations/webhooks/verifiers/slack_signing.py
  • src/synthorg/memory/backends/inmemory/adapter.py
  • src/synthorg/memory/backends/mem0/adapter.py
  • src/synthorg/memory/consolidation/abstractive.py
  • src/synthorg/memory/consolidation/config.py
  • src/synthorg/memory/consolidation/density.py
  • src/synthorg/memory/consolidation/dual_mode_strategy.py
  • src/synthorg/memory/consolidation/extractive.py
  • src/synthorg/memory/consolidation/service.py
  • src/synthorg/memory/consolidation/simple_strategy.py
  • src/synthorg/memory/consolidation/two_tier_strategy.py
  • src/synthorg/memory/embedding/fine_tune.py
  • src/synthorg/memory/fine_tune_plan.py
  • src/synthorg/memory/procedural/capture/success_capture.py
  • src/synthorg/memory/procedural/propagation/department_scoped.py
  • src/synthorg/memory/procedural/propagation/role_scoped.py
  • src/synthorg/memory/procedural/pruning/pareto_strategy.py
  • src/synthorg/memory/procedural/pruning/ttl_strategy.py
  • src/synthorg/memory/procedural/trajectory_aggregator.py
  • src/synthorg/memory/ranking.py
  • src/synthorg/memory/retrieval/hierarchical/supervisor.py
  • src/synthorg/memory/retrieval/hierarchical/workers.py
  • src/synthorg/memory/retrieval/reranking/cache.py
  • src/synthorg/memory/retrieval/reranking/llm_reranker.py
  • src/synthorg/memory/retrieval_config.py
  • src/synthorg/memory/sparse.py
  • src/synthorg/memory/tools/_args.py
  • src/synthorg/meta/analytics/service.py
  • src/synthorg/meta/appliers/github_client.py
  • src/synthorg/meta/appliers/prompt_applier.py
  • src/synthorg/meta/chief_of_staff/inflection.py
  • src/synthorg/meta/chief_of_staff/learning.py
  • src/synthorg/meta/chief_of_staff/monitor.py
  • src/synthorg/meta/chief_of_staff/outcome_store.py
  • src/synthorg/meta/chief_of_staff/protocol.py
  • src/synthorg/meta/evolution/outcome_store.py
  • src/synthorg/meta/evolution/outcome_store_protocol.py
  • src/synthorg/meta/guards/approval_gate.py
  • src/synthorg/meta/guards/rate_limit.py
  • src/synthorg/meta/mcp/handlers/analytics.py
  • src/synthorg/meta/mcp/handlers/common_args.py
  • src/synthorg/meta/reports/service.py
  • src/synthorg/meta/rollout/ab_comparator.py
  • src/synthorg/meta/rollout/ab_models.py
  • src/synthorg/meta/rollout/ab_test.py
  • src/synthorg/meta/rollout/before_after.py
  • src/synthorg/meta/rollout/canary.py
  • src/synthorg/meta/rollout/regression/statistical.py
  • src/synthorg/meta/rollout/regression/welch.py
  • src/synthorg/meta/rules/builtin.py
  • src/synthorg/meta/strategies/code_modification.py
  • src/synthorg/meta/telemetry/aggregator.py
  • src/synthorg/meta/telemetry/collector.py
  • src/synthorg/meta/telemetry/emitter.py
  • src/synthorg/meta/telemetry/protocol.py
  • src/synthorg/meta/telemetry/recommender.py
  • src/synthorg/meta/validation/ci_validator.py
  • src/synthorg/notifications/adapters/email.py
  • src/synthorg/notifications/adapters/ntfy.py
  • src/synthorg/notifications/adapters/slack.py
  • src/synthorg/observability/audit_chain/tsa_client.py
  • src/synthorg/observability/background_tasks.py
  • src/synthorg/observability/http_handler.py
  • src/synthorg/observability/otlp_handler.py
  • src/synthorg/observability/otlp_trace_handler.py
  • src/synthorg/observability/tracing/protocol.py
  • src/synthorg/ontology/drift/active.py
  • src/synthorg/ontology/drift/passive.py
  • src/synthorg/ontology/injection/hybrid.py
  • src/synthorg/ontology/injection/prompt.py
  • src/synthorg/ontology/service.py
  • src/synthorg/persistence/approval_protocol.py
  • src/synthorg/persistence/artifact_protocol.py
  • src/synthorg/persistence/atlas.py
  • src/synthorg/persistence/audit_protocol.py
  • src/synthorg/persistence/auth_protocol.py
  • src/synthorg/persistence/connection_protocol.py
  • src/synthorg/persistence/cost_record_protocol.py
  • src/synthorg/persistence/decision_protocol.py
  • src/synthorg/persistence/fine_tune_protocol.py
  • src/synthorg/persistence/integration_stubs.py
  • src/synthorg/persistence/jsonb_capability.py
  • src/synthorg/persistence/mcp_protocol.py
  • src/synthorg/persistence/memory_protocol.py
  • src/synthorg/persistence/message_protocol.py
  • src/synthorg/persistence/ontology_protocol.py
  • src/synthorg/persistence/postgres/approval_repo.py
  • src/synthorg/persistence/postgres/artifact_repo.py
  • src/synthorg/persistence/postgres/audit_repository.py
  • src/synthorg/persistence/postgres/connection_repo.py
  • src/synthorg/persistence/postgres/decision_repo.py
  • src/synthorg/persistence/postgres/escalation_repo.py
  • src/synthorg/persistence/postgres/fine_tune_repo.py
  • src/synthorg/persistence/postgres/mcp_installation_repo.py
  • src/synthorg/persistence/postgres/ontology_drift_repo.py
  • src/synthorg/persistence/postgres/ontology_entity_repo.py
  • src/synthorg/persistence/postgres/org_fact_repo.py
  • src/synthorg/persistence/postgres/provider_audit_repo.py
  • src/synthorg/persistence/postgres/repositories.py
  • src/synthorg/persistence/postgres/session_repo.py
  • src/synthorg/persistence/postgres/settings_repo.py
  • src/synthorg/persistence/postgres/ssrf_violation_repo.py
  • src/synthorg/persistence/postgres/version_repo.py
  • src/synthorg/persistence/postgres/webhook_receipt_repo.py
  • src/synthorg/persistence/provider_audit_protocol.py
  • src/synthorg/persistence/settings_protocol.py
  • src/synthorg/persistence/sqlite/approval_repo.py
  • src/synthorg/persistence/sqlite/artifact_repo.py
  • src/synthorg/persistence/sqlite/audit_repository.py
  • src/synthorg/persistence/sqlite/connection_repo.py
  • src/synthorg/persistence/sqlite/decision_repo.py
  • src/synthorg/persistence/sqlite/escalation_repo.py
  • src/synthorg/persistence/sqlite/fine_tune_repo.py
  • src/synthorg/persistence/sqlite/mcp_installation_repo.py
  • src/synthorg/persistence/sqlite/ontology_drift_repo.py
  • src/synthorg/persistence/sqlite/ontology_entity_repo.py
  • src/synthorg/persistence/sqlite/org_fact_repo.py
  • src/synthorg/persistence/sqlite/provider_audit_repo.py
  • src/synthorg/persistence/sqlite/repositories.py
  • src/synthorg/persistence/sqlite/session_repo.py
  • src/synthorg/persistence/sqlite/settings_repo.py
  • src/synthorg/persistence/sqlite/ssrf_violation_repo.py
  • src/synthorg/persistence/sqlite/version_repo.py
  • src/synthorg/persistence/sqlite/webhook_receipt_repo.py
  • src/synthorg/persistence/ssrf_violation_protocol.py
  • src/synthorg/persistence/task_protocol.py
  • src/synthorg/persistence/version_protocol.py
  • src/synthorg/providers/drivers/litellm_driver.py
  • src/synthorg/providers/health.py
  • src/synthorg/providers/health_prober.py
  • src/synthorg/providers/management/_capability_helpers.py
  • src/synthorg/providers/management/audit_service.py
  • src/synthorg/providers/management/local_models.py
  • src/synthorg/security/audit.py
  • src/synthorg/security/llm_evaluator.py
  • src/synthorg/security/timeout/factory.py
  • src/synthorg/security/timeout/policies.py
💤 Files with no reviewable changes (1)
  • scripts/no_magic_numbers_baseline.txt

Comment thread src/synthorg/engine/loop_selector.py Outdated
Comment thread src/synthorg/integrations/oauth/flows/device_flow.py
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request systematically replaces magic numbers with named constants and Final type annotations across the entire codebase, significantly reducing the baseline of linting exclusions. The changes improve code readability and maintainability by centralizing default values for timeouts, limits, and thresholds. Feedback from the reviewer highlights multiple opportunities to further improve the implementation by importing shared constants from protocol and configuration files rather than redefining them in repository-specific modules, adhering more strictly to the DRY principle.

from synthorg.engine.workflow.definition import WorkflowDefinition

_MIN_SPLIT_BRANCHES = 2
_MIN_SPLIT_BRANCHES: Final[int] = 2
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.

medium

The constant _MIN_SPLIT_BRANCHES is also defined in src/synthorg/engine/workflow/validation_types.py. To avoid duplication and improve maintainability, you could import it from there instead of redefining it.

For example:

from synthorg.engine.workflow.validation_types import (
    ValidationFinding,
    ValidationContext,
    _validate_node_exists,
    _MIN_SPLIT_BRANCHES,
)

logger = get_logger(__name__)

_DEFAULT_LIMIT = 50
_DEFAULT_LIMIT: Final[int] = 50
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.

medium

The constant _DEFAULT_LIMIT is also defined in src/synthorg/communication/conflict_resolution/escalation/protocol.py. To avoid duplication, you could import it from the protocol file. The same applies to _DEFAULT_OFFSET.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_50: Final[int] = 50
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.

medium

The constant _DEFAULT_LIST_LIMIT_50 is also defined in src/synthorg/persistence/fine_tune_protocol.py. To avoid duplication, you could import it from the protocol file.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_5: Final[int] = 5
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.

medium

The constant _DEFAULT_LIST_LIMIT_5 is also defined in src/synthorg/persistence/memory_protocol.py. To avoid duplication, you could import it from there.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_50: Final[int] = 50
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.

medium

The constant _DEFAULT_LIST_LIMIT_50 is also defined in src/synthorg/persistence/provider_audit_protocol.py. To avoid duplication, you could import it from the protocol file.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_50: Final[int] = 50
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.

medium

The constant _DEFAULT_LIST_LIMIT_50 is also defined in src/synthorg/persistence/fine_tune_protocol.py. To avoid duplication, you could import it from the protocol file.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_5: Final[int] = 5
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.

medium

The constant _DEFAULT_LIST_LIMIT_5 is also defined in src/synthorg/persistence/memory_protocol.py. To avoid duplication, you could import it from there.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_50: Final[int] = 50
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.

medium

The constant _DEFAULT_LIST_LIMIT_50 is also defined in src/synthorg/persistence/provider_audit_protocol.py. To avoid duplication, you could import it from the protocol file.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_200: Final[int] = 200
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.

medium

The constant _DEFAULT_LIST_LIMIT_200 is also defined in src/synthorg/persistence/settings_protocol.py. To avoid duplication, you could import it from there.


logger = get_logger(__name__)

_DEFAULT_LIST_LIMIT_50: Final[int] = 50
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.

medium

The constant _DEFAULT_LIST_LIMIT_50 is also defined in src/synthorg/persistence/version_protocol.py. To avoid duplication, you could import it from there.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 11, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 84.94%. Comparing base (af33ddb) to head (71ffdd6).
⚠️ Report is 2 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1872      +/-   ##
==========================================
+ Coverage   84.89%   84.94%   +0.04%     
==========================================
  Files        1804     1804              
  Lines      105233   105557     +324     
  Branches     9214     9214              
==========================================
+ Hits        89342    89669     +327     
+ Misses      13656    13654       -2     
+ Partials     2235     2234       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

- loop_selector.py: route AutoLoopConfig.budget_tight_threshold through
  _DEFAULT_BUDGET_TIGHT_THRESHOLD (move constant above the class).
- device_flow.py: use _DEFAULT_EXPIRES_IN for the response parser
  fallback instead of literal 600.
- connection_protocol.py / task_protocol.py / cost_record_protocol.py:
  align list/query docstrings with the int = DEFAULT_LIST_LIMIT signature
  (drop stale 'None default' / fetch-all semantics).
- engine/workflow/validate_edges.py: import _MIN_SPLIT_BRANCHES from
  validation_types instead of redefining locally.
- persistence/{postgres,sqlite}/{escalation,fine_tune,org_fact,
  provider_audit,settings,version}_repo.py: import the
  _DEFAULT_LIMIT/_DEFAULT_OFFSET/_DEFAULT_LIST_LIMIT_* constants from
  their respective protocol files instead of redefining.
@Aureliolo Aureliolo temporarily deployed to cloudflare-preview May 12, 2026 03:57 — with GitHub Actions Inactive
@Aureliolo Aureliolo merged commit ec8109e into main May 12, 2026
76 of 78 checks passed
@Aureliolo Aureliolo deleted the refactor/issue-1856-phase-2-literal-migration branch May 12, 2026 04:16
@Aureliolo Aureliolo temporarily deployed to cloudflare-preview May 12, 2026 04:16 — with GitHub Actions Inactive
Aureliolo pushed a commit that referenced this pull request May 12, 2026
<!-- HIGHLIGHTS_START -->
## Highlights

> _AI-generated summary (model: `openai/gpt-4.1-mini` via GitHub
Models). Commit-based changelog below._

### What you'll notice
- Password and secret fields now include an eye-toggle for easier
visibility control.
- Containers running without probes are shown as healthy in the doctor
command.
- Unloaded and missing PR-review agents are restored and available
again.

### What's new
- Gate baseline protection is enhanced to block em-dashes during
writing.

### Under the hood
- Replaced Atlas with yoyo-migrations for persistence management.
- Refactored codebase extensively, including context-bound user
authentication and registry pattern for enums.
- Improved linting by draining magic number usages and tightening mock
and constant checks.
- Updated CI to retry Docker pushes on network timeout errors.
- Updated apko lockfiles for dependency management.

<!-- HIGHLIGHTS_END -->

:robot: I have created a release *beep* *boop*
---


##
[0.8.3](v0.8.2...v0.8.3)
(2026-05-12)


### Features

* harden gate baseline protection + block em-dashes at write time
([#1860](#1860))
([b41f151](b41f151))
* **web:** eye-toggle on every password / secret field
([#1873](#1873))
([9070387](9070387))


### Bug Fixes

* **ci:** retry Docker push on Go net/http deadline + cancellation
errors ([#1877](#1877))
([23a0bfa](23a0bfa))
* **cli:** render running-no-probe containers as healthy in doctor
([#1870](#1870))
([6263795](6263795))
* restore unloaded and missing PR-review agents
([#1875](#1875))
([db004fd](db004fd)),
closes [#1871](#1871)


### Refactoring

* bind authenticated user via ContextVar
([#1858](#1858))
([57ed0b4](57ed0b4))
* code-structure cleanup (sub-tasks D + F + G + H + I)
([#1859](#1859))
([362e5c8](362e5c8))
* convert enum dispatch to registry pattern
([#1854](#1854))
([e90550e](e90550e))
* drain no_magic_numbers baseline to zero via Final hoists
([#1856](#1856) phase 2)
([#1872](#1872))
([ec8109e](ec8109e))
* drain pagination + loop-init + kill-switch baselines
([#1857](#1857))
([#1868](#1868))
([115c3c2](115c3c2))
* **persistence:** replace Atlas with yoyo-migrations
([#1876](#1876))
([1b7e975](1b7e975)),
closes [#1874](#1874)
* protocols audit follow-up (REVIEW + fold pass)
([#1869](#1869))
([af33ddb](af33ddb))
* protocols audit follow-up REMOVE pass
([#1867](#1867))
([dd1eebc](dd1eebc))
* tighten check_mock_spec gate, add mock_of[T], drain baseline
([#1862](#1862))
([240a253](240a253))
* tighten check_no_magic_numbers for named module constants
([#1856](#1856))
([#1866](#1866))
([90c933b](90c933b))


### CI/CD

* update apko lockfiles
([#1863](#1863))
([2bd32e6](2bd32e6))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

---------

Co-authored-by: synthorg-repo-bot[bot] <279117679+synthorg-repo-bot[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
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.

1 participant